qExecutor.c 211.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * 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/>.
 */
H
Haojun Liao 已提交
15
#include <qfill.h>
16 17 18 19
#include "os.h"

#include "hash.h"
#include "hashfunc.h"
20 21
#include "qExecutor.h"
#include "qUtil.h"
H
hjxilinx 已提交
22
#include "qast.h"
23
#include "qresultBuf.h"
H
hjxilinx 已提交
24
#include "query.h"
S
slguan 已提交
25
#include "queryLog.h"
26
#include "taosmsg.h"
27
#include "tdataformat.h"
28
#include "tlosertree.h"
29
#include "tscUtil.h"  // todo move the function to common module
30 31
#include "tscompression.h"
#include "ttime.h"
32 33 34 35 36 37 38 39 40 41 42

#define DEFAULT_INTERN_BUF_SIZE 16384L

/**
 * check if the primary column is load by default, otherwise, the program will
 * forced to load primary column explicitly.
 */
#define Q_STATUS_EQUAL(p, s) (((p) & (s)) != 0)
#define TSDB_COL_IS_TAG(f) (((f)&TSDB_COL_TAG) != 0)
#define QUERY_IS_ASC_QUERY(q) (GET_FORWARD_DIRECTION_FACTOR((q)->order.order) == QUERY_ASC_FORWARD_STEP)

43
#define IS_MASTER_SCAN(runtime)        ((runtime)->scanFlag == MASTER_SCAN)
H
hjxilinx 已提交
44
#define IS_REVERSE_SCAN(runtime)       ((runtime)->scanFlag == REVERSE_SCAN)
45
#define SET_MASTER_SCAN_FLAG(runtime)  ((runtime)->scanFlag = MASTER_SCAN)
H
hjxilinx 已提交
46
#define SET_REVERSE_SCAN_FLAG(runtime) ((runtime)->scanFlag = REVERSE_SCAN)
47

48
#define GET_QINFO_ADDR(x) ((void *)((char *)(x)-offsetof(SQInfo, runtimeEnv)))
49

50
#define GET_COL_DATA_POS(query, index, step) ((query)->pos + (index) * (step))
51
#define SWITCH_ORDER(n) (((n) = ((n) == TSDB_ORDER_ASC) ? TSDB_ORDER_DESC : TSDB_ORDER_ASC))
52 53 54

/* get the qinfo struct address from the query struct address */
#define GET_COLUMN_BYTES(query, colidx) \
55 56
  ((query)->colList[(query)->pSelectExpr[colidx].base.colInfo.colIndex].bytes)
#define GET_COLUMN_TYPE(query, colidx) ((query)->colList[(query)->pSelectExpr[colidx].base.colInfo.colIndex].type)
57 58 59

typedef struct SPointInterpoSupporter {
  int32_t numOfCols;
H
hjxilinx 已提交
60 61
  SArray* prev;
  SArray* next;
62 63 64
} SPointInterpoSupporter;

typedef enum {
H
hjxilinx 已提交
65
  // when query starts to execute, this status will set
66 67
  QUERY_NOT_COMPLETED = 0x1u,

H
hjxilinx 已提交
68 69
  /* result output buffer is full, current query is paused.
   * this status is only exist in group-by clause and diff/add/division/multiply/ query.
70
   */
71 72
  QUERY_RESBUF_FULL = 0x2u,

H
hjxilinx 已提交
73 74 75
  /* query is over
   * 1. this status is used in one row result query process, e.g., count/sum/first/last/ avg...etc.
   * 2. when all data within queried time window, it is also denoted as query_completed
76
   */
77
  QUERY_COMPLETED = 0x4u,
78

H
hjxilinx 已提交
79 80
  /* when the result is not completed return to client, this status will be
   * usually used in case of interval query with interpolation option
81
   */
82
  QUERY_OVER = 0x8u,
83 84 85 86 87 88 89 90
} vnodeQueryStatus;

enum {
  TS_JOIN_TS_EQUAL = 0,
  TS_JOIN_TS_NOT_EQUALS = 1,
  TS_JOIN_TAG_NOT_EQUALS = 2,
};

91
typedef struct {
92 93 94 95 96 97
  int32_t     status;       // query status
  TSKEY       lastKey;      // the lastKey value before query executed
  STimeWindow w;            // whole query time window
  STimeWindow curWindow;    // current query window
  int32_t     windowIndex;  // index of active time window result for interval query
  STSCursor   cur;
98 99
} SQueryStatusInfo;

100
#define CLEAR_QUERY_STATUS(q, st)   ((q)->status &= (~(st)))
101
static void setQueryStatus(SQuery *pQuery, int8_t status);
102

H
hjxilinx 已提交
103
static bool isIntervalQuery(SQuery *pQuery) { return pQuery->intervalTime > 0; }
104

H
hjxilinx 已提交
105
// todo move to utility
106
static int32_t mergeIntoGroupResultImpl(SQInfo *pQInfo, SArray *group);
107

H
hjxilinx 已提交
108
static void setWindowResOutputBuf(SQueryRuntimeEnv *pRuntimeEnv, SWindowResult *pResult);
109 110 111
static void resetMergeResultBuf(SQuery *pQuery, SQLFunctionCtx *pCtx, SResultInfo *pResultInfo);
static bool functionNeedToExecute(SQueryRuntimeEnv *pRuntimeEnv, SQLFunctionCtx *pCtx, int32_t functionId);
static void getNextTimeWindow(SQuery *pQuery, STimeWindow *pTimeWindow);
112

113
static void setExecParams(SQuery *pQuery, SQLFunctionCtx *pCtx, void *inputData, TSKEY *tsCol, int32_t size,
114 115
                          int32_t functionId, SDataStatis *pStatis, bool hasNull, void *param, int32_t scanFlag);
static void initCtxOutputBuf(SQueryRuntimeEnv *pRuntimeEnv);
116
static void destroyTableQueryInfo(STableQueryInfo *pTableQueryInfo, int32_t numOfCols);
117 118
static void resetCtxOutputBuf(SQueryRuntimeEnv *pRuntimeEnv);
static bool hasMainOutput(SQuery *pQuery);
H
hjxilinx 已提交
119
static void buildTagQueryResult(SQInfo *pQInfo);
120

H
hjxilinx 已提交
121
static int32_t setAdditionalInfo(SQInfo *pQInfo, STableId *pTableId, STableQueryInfo *pTableQueryInfo);
122
static int32_t flushFromResultBuf(SQInfo *pQInfo);
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192

bool getNeighborPoints(SQInfo *pQInfo, void *pMeterObj, SPointInterpoSupporter *pPointInterpSupporter) {
#if 0
  SQueryRuntimeEnv *pRuntimeEnv = &pSupporter->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;

  if (!isPointInterpoQuery(pQuery)) {
    return false;
  }

  /*
   * for interpolate point query, points that are directly before/after the specified point are required
   */
  if (isFirstLastRowQuery(pQuery)) {
    assert(!QUERY_IS_ASC_QUERY(pQuery));
  } else {
    assert(QUERY_IS_ASC_QUERY(pQuery));
  }
  assert(pPointInterpSupporter != NULL && pQuery->skey == pQuery->ekey);

  SCacheBlock *pBlock = NULL;

  qTrace("QInfo:%p get next data point, fileId:%d, slot:%d, pos:%d", GET_QINFO_ADDR(pQuery), pQuery->fileId,
         pQuery->slot, pQuery->pos);

  // save the point that is directly after or equals to the specified point
  getOneRowFromDataBlock(pRuntimeEnv, pPointInterpSupporter->pNextPoint, pQuery->pos);

  /*
   * 1. for last_row query, return immediately.
   * 2. the specified timestamp equals to the required key, interpolation according to neighbor points is not necessary
   *    for interp query.
   */
  TSKEY actualKey = *(TSKEY *)pPointInterpSupporter->pNextPoint[0];
  if (isFirstLastRowQuery(pQuery) || actualKey == pQuery->skey) {
    setQueryStatus(pQuery, QUERY_NOT_COMPLETED);

    /*
     * the retrieved ts may not equals to pMeterObj->lastKey due to cache re-allocation
     * set the pQuery->ekey/pQuery->skey/pQuery->lastKey to be the new value.
     */
    if (pQuery->ekey != actualKey) {
      pQuery->skey = actualKey;
      pQuery->ekey = actualKey;
      pQuery->lastKey = actualKey;
      pSupporter->rawSKey = actualKey;
      pSupporter->rawEKey = actualKey;
    }
    return true;
  }

  /* the qualified point is not the first point in data block */
  if (pQuery->pos > 0) {
    int32_t prevPos = pQuery->pos - 1;

    /* save the point that is directly after the specified point */
    getOneRowFromDataBlock(pRuntimeEnv, pPointInterpSupporter->pPrevPoint, prevPos);
  } else {
    __block_search_fn_t searchFn = vnodeSearchKeyFunc[pMeterObj->searchAlgorithm];

//    savePointPosition(&pRuntimeEnv->startPos, pQuery->fileId, pQuery->slot, pQuery->pos);

    // backwards movement would not set the pQuery->pos correct. We need to set it manually later.
    moveToNextBlock(pRuntimeEnv, QUERY_DESC_FORWARD_STEP, searchFn, true);

    /*
     * no previous data exists.
     * reset the status and load the data block that contains the qualified point
     */
    if (Q_STATUS_EQUAL(pQuery->over, QUERY_NO_DATA_TO_CHECK)) {
S
slguan 已提交
193
      qTrace("QInfo:%p no previous data block, start fileId:%d, slot:%d, pos:%d, qrange:%" PRId64 "-%" PRId64
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
             ", out of range",
             GET_QINFO_ADDR(pQuery), pRuntimeEnv->startPos.fileId, pRuntimeEnv->startPos.slot,
             pRuntimeEnv->startPos.pos, pQuery->skey, pQuery->ekey);

      // no result, return immediately
      setQueryStatus(pQuery, QUERY_COMPLETED);
      return false;
    } else {  // prev has been located
      if (pQuery->fileId >= 0) {
        pQuery->pos = pQuery->pBlock[pQuery->slot].numOfPoints - 1;
        getOneRowFromDataBlock(pRuntimeEnv, pPointInterpSupporter->pPrevPoint, pQuery->pos);

        qTrace("QInfo:%p get prev data point, fileId:%d, slot:%d, pos:%d, pQuery->pos:%d", GET_QINFO_ADDR(pQuery),
               pQuery->fileId, pQuery->slot, pQuery->pos, pQuery->pos);
      } else {
        // moveToNextBlock make sure there is a available cache block, if exists
        assert(vnodeIsDatablockLoaded(pRuntimeEnv, pMeterObj, -1, true) == DISK_BLOCK_NO_NEED_TO_LOAD);
        pBlock = &pRuntimeEnv->cacheBlock;

        pQuery->pos = pBlock->numOfPoints - 1;
        getOneRowFromDataBlock(pRuntimeEnv, pPointInterpSupporter->pPrevPoint, pQuery->pos);

        qTrace("QInfo:%p get prev data point, fileId:%d, slot:%d, pos:%d, pQuery->pos:%d", GET_QINFO_ADDR(pQuery),
               pQuery->fileId, pQuery->slot, pBlock->numOfPoints - 1, pQuery->pos);
      }
    }
  }

  pQuery->skey = *(TSKEY *)pPointInterpSupporter->pPrevPoint[0];
  pQuery->ekey = *(TSKEY *)pPointInterpSupporter->pNextPoint[0];
  pQuery->lastKey = pQuery->skey;
#endif
  return true;
}

229
bool doFilterData(SQuery *pQuery, int32_t elemPos) {
230 231
  for (int32_t k = 0; k < pQuery->numOfFilterCols; ++k) {
    SSingleColumnFilterInfo *pFilterInfo = &pQuery->pFilterInfo[k];
232 233 234
    
    char *pElem = pFilterInfo->pData + pFilterInfo->info.bytes * elemPos;
    if (isNull(pElem, pFilterInfo->info.type)) {
235 236
      return false;
    }
237

238 239
    bool qualified = false;
    for (int32_t j = 0; j < pFilterInfo->numOfFilters; ++j) {
240
      SColumnFilterElem *pFilterElem = &pFilterInfo->pFilters[j];
241
      
242 243 244 245 246
      if (pFilterElem->fp(pFilterElem, pElem, pElem)) {
        qualified = true;
        break;
      }
    }
247

248 249 250 251
    if (!qualified) {
      return false;
    }
  }
252

253 254 255 256 257 258
  return true;
}

int64_t getNumOfResult(SQueryRuntimeEnv *pRuntimeEnv) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
  bool    hasMainFunction = hasMainOutput(pQuery);
259

260
  int64_t maxOutput = 0;
261
  for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
262
    int32_t functionId = pQuery->pSelectExpr[j].base.functionId;
263

264 265 266 267 268 269 270 271
    /*
     * ts, tag, tagprj function can not decide the output number of current query
     * the number of output result is decided by main output
     */
    if (hasMainFunction &&
        (functionId == TSDB_FUNC_TS || functionId == TSDB_FUNC_TAG || functionId == TSDB_FUNC_TAGPRJ)) {
      continue;
    }
272

273 274 275 276 277
    SResultInfo *pResInfo = GET_RES_INFO(&pRuntimeEnv->pCtx[j]);
    if (pResInfo != NULL && maxOutput < pResInfo->numOfRes) {
      maxOutput = pResInfo->numOfRes;
    }
  }
278

279
  assert(maxOutput >= 0);
280 281 282
  return maxOutput;
}

283 284 285 286 287 288 289 290 291
/*
 * the value of number of result needs to be update due to offset value upated.
 */
void updateNumOfResult(SQueryRuntimeEnv *pRuntimeEnv, int32_t numOfRes) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
  
  for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
    SResultInfo *pResInfo = GET_RES_INFO(&pRuntimeEnv->pCtx[j]);
    
H
Haojun Liao 已提交
292 293 294 295 296 297 298
    int16_t functionId = pRuntimeEnv->pCtx[j].functionId;
    if (functionId == TSDB_FUNC_TS || functionId == TSDB_FUNC_TAG || functionId == TSDB_FUNC_TAGPRJ ||
        functionId == TSDB_FUNC_TS_DUMMY) {
      continue;
    }
    
    assert(pResInfo->numOfRes > numOfRes);
299 300 301 302
    pResInfo->numOfRes = numOfRes;
  }
}

303 304 305 306 307 308 309 310 311
static int32_t getGroupResultId(int32_t groupIndex) {
  int32_t base = 200000;
  return base + (groupIndex * 10000);
}

bool isGroupbyNormalCol(SSqlGroupbyExpr *pGroupbyExpr) {
  if (pGroupbyExpr == NULL || pGroupbyExpr->numOfGroupCols == 0) {
    return false;
  }
312

313
  for (int32_t i = 0; i < pGroupbyExpr->numOfGroupCols; ++i) {
314
    SColIndex *pColIndex = taosArrayGet(pGroupbyExpr->columnInfo, i);
315 316 317 318 319
    if (pColIndex->flag == TSDB_COL_NORMAL) {
      /*
       * make sure the normal column locates at the second position if tbname exists in group by clause
       */
      if (pGroupbyExpr->numOfGroupCols > 1) {
320
        assert(pColIndex->colIndex > 0);
321
      }
322

323 324 325
      return true;
    }
  }
326

327 328 329 330 331
  return false;
}

int16_t getGroupbyColumnType(SQuery *pQuery, SSqlGroupbyExpr *pGroupbyExpr) {
  assert(pGroupbyExpr != NULL);
332

333 334
  int32_t colId = -2;
  int16_t type = TSDB_DATA_TYPE_NULL;
335

336
  for (int32_t i = 0; i < pGroupbyExpr->numOfGroupCols; ++i) {
337
    SColIndex *pColIndex = taosArrayGet(pGroupbyExpr->columnInfo, i);
338 339 340 341 342
    if (pColIndex->flag == TSDB_COL_NORMAL) {
      colId = pColIndex->colId;
      break;
    }
  }
343

344
  for (int32_t i = 0; i < pQuery->numOfCols; ++i) {
345 346
    if (colId == pQuery->colList[i].colId) {
      type = pQuery->colList[i].type;
347 348 349
      break;
    }
  }
350

351 352 353 354 355 356
  return type;
}

bool isSelectivityWithTagsQuery(SQuery *pQuery) {
  bool    hasTags = false;
  int32_t numOfSelectivity = 0;
357

358
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
359
    int32_t functId = pQuery->pSelectExpr[i].base.functionId;
360 361 362 363
    if (functId == TSDB_FUNC_TAG_DUMMY || functId == TSDB_FUNC_TS_DUMMY) {
      hasTags = true;
      continue;
    }
364

365 366 367 368
    if ((aAggs[functId].nStatus & TSDB_FUNCSTATE_SELECTIVITY) != 0) {
      numOfSelectivity++;
    }
  }
369

370 371 372
  if (numOfSelectivity > 0 && hasTags) {
    return true;
  }
373

374 375 376
  return false;
}

377
bool isTSCompQuery(SQuery *pQuery) { return pQuery->pSelectExpr[0].base.functionId == TSDB_FUNC_TS_COMP; }
378

379
static bool limitResults(SQuery *pQuery) {
380 381 382
  if ((pQuery->limit.limit > 0) && (pQuery->rec.total + pQuery->rec.rows > pQuery->limit.limit)) {
    pQuery->rec.rows = pQuery->limit.limit - pQuery->rec.total;
    assert(pQuery->rec.rows > 0);
383

384 385 386
    setQueryStatus(pQuery, QUERY_COMPLETED);
    return true;
  }
387

388 389 390 391
  return false;
}

static bool isTopBottomQuery(SQuery *pQuery) {
392
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
393
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
394 395 396
    if (functionId == TSDB_FUNC_TS) {
      continue;
    }
397

398 399 400 401
    if (functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM) {
      return true;
    }
  }
402

403 404 405
  return false;
}

406
static SDataStatis *getStatisInfo(SQuery *pQuery, SDataStatis *pStatis, SDataBlockInfo *pDataBlockInfo, int32_t index) {
407
  // for a tag column, no corresponding field info
408
  SColIndex *pColIndexEx = &pQuery->pSelectExpr[index].base.colInfo;
409 410 411
  if (TSDB_COL_IS_TAG(pColIndexEx->flag)) {
    return NULL;
  }
412

413 414 415 416 417 418 419 420 421
  /*
   * Choose the right column field info by field id, since the file block may be out of date,
   * which means the newest table schema is not equalled to the schema of this block.
   */
  for (int32_t i = 0; i < pDataBlockInfo->numOfCols; ++i) {
    if (pColIndexEx->colId == pStatis[i].colId) {
      return &pStatis[i];
    }
  }
422

423 424 425
  return NULL;
}

426 427 428 429 430 431 432 433
/**
 * @param pQuery
 * @param col
 * @param pDataBlockInfo
 * @param pStatis
 * @param pColStatis
 * @return
 */
434
static bool hasNullValue(SQuery *pQuery, int32_t col, SDataBlockInfo *pDataBlockInfo, SDataStatis *pStatis,
435
                         SDataStatis **pColStatis) {
436
  SColIndex *pColIndex = &pQuery->pSelectExpr[col].base.colInfo;
437
  if (TSDB_COL_IS_TAG(pColIndex->flag)) {
438 439
    return false;
  }
440

441 442 443 444
  // query on primary timestamp column, not null value at all
  if (pColIndex->colId == PRIMARYKEY_TIMESTAMP_COL_INDEX) {
    return false;
  }
445

446 447
  if (pStatis != NULL) {
    *pColStatis = getStatisInfo(pQuery, pStatis, pDataBlockInfo, col);
H
hjxilinx 已提交
448 449
  } else {
    *pColStatis = NULL;
450
  }
451

452 453 454
  if ((*pColStatis) != NULL && (*pColStatis)->numOfNull == 0) {
    return false;
  }
455

456 457 458 459 460 461
  return true;
}

static SWindowResult *doSetTimeWindowFromKey(SQueryRuntimeEnv *pRuntimeEnv, SWindowResInfo *pWindowResInfo, char *pData,
                                             int16_t bytes) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
462

463 464 465 466 467 468
  int32_t *p1 = (int32_t *)taosHashGet(pWindowResInfo->hashList, pData, bytes);
  if (p1 != NULL) {
    pWindowResInfo->curIndex = *p1;
  } else {  // more than the capacity, reallocate the resources
    if (pWindowResInfo->size >= pWindowResInfo->capacity) {
      int64_t newCap = pWindowResInfo->capacity * 2;
469

470 471 472 473 474 475 476
      char *t = realloc(pWindowResInfo->pResult, newCap * sizeof(SWindowResult));
      if (t != NULL) {
        pWindowResInfo->pResult = (SWindowResult *)t;
        memset(&pWindowResInfo->pResult[pWindowResInfo->capacity], 0, sizeof(SWindowResult) * pWindowResInfo->capacity);
      } else {
        // todo
      }
477

478 479 480 481
      for (int32_t i = pWindowResInfo->capacity; i < newCap; ++i) {
        SPosInfo pos = {-1, -1};
        createQueryResultInfo(pQuery, &pWindowResInfo->pResult[i], pRuntimeEnv->stableQuery, &pos);
      }
482

483 484
      pWindowResInfo->capacity = newCap;
    }
485

486 487 488 489
    // add a new result set for a new group
    pWindowResInfo->curIndex = pWindowResInfo->size++;
    taosHashPut(pWindowResInfo->hashList, pData, bytes, (char *)&pWindowResInfo->curIndex, sizeof(int32_t));
  }
490

491 492 493 494 495 496
  return getWindowResult(pWindowResInfo, pWindowResInfo->curIndex);
}

// get the correct time window according to the handled timestamp
static STimeWindow getActiveTimeWindow(SWindowResInfo *pWindowResInfo, int64_t ts, SQuery *pQuery) {
  STimeWindow w = {0};
497

498 499 500 501 502 503 504
  if (pWindowResInfo->curIndex == -1) {  // the first window, from the previous stored value
    w.skey = pWindowResInfo->prevSKey;
    w.ekey = w.skey + pQuery->intervalTime - 1;
  } else {
    int32_t slot = curTimeWindow(pWindowResInfo);
    w = getWindowResult(pWindowResInfo, slot)->window;
  }
505

506 507
  if (w.skey > ts || w.ekey < ts) {
    int64_t st = w.skey;
508

509 510 511
    if (st > ts) {
      st -= ((st - ts + pQuery->slidingTime - 1) / pQuery->slidingTime) * pQuery->slidingTime;
    }
512

513 514 515 516
    int64_t et = st + pQuery->intervalTime - 1;
    if (et < ts) {
      st += ((ts - et + pQuery->slidingTime - 1) / pQuery->slidingTime) * pQuery->slidingTime;
    }
517

518 519 520
    w.skey = st;
    w.ekey = w.skey + pQuery->intervalTime - 1;
  }
521

522 523 524 525 526 527 528
  /*
   * query border check, skey should not be bounded by the query time range, since the value skey will
   * be used as the time window index value. So we only change ekey of time window accordingly.
   */
  if (w.ekey > pQuery->window.ekey && QUERY_IS_ASC_QUERY(pQuery)) {
    w.ekey = pQuery->window.ekey;
  }
529

530
  assert(ts >= w.skey && ts <= w.ekey);
531

532 533 534 535 536 537 538 539
  return w;
}

static int32_t addNewWindowResultBuf(SWindowResult *pWindowRes, SDiskbasedResultBuf *pResultBuf, int32_t sid,
                                     int32_t numOfRowsPerPage) {
  if (pWindowRes->pos.pageId != -1) {
    return 0;
  }
540

541
  tFilePage *pData = NULL;
542

543 544 545
  // in the first scan, new space needed for results
  int32_t pageId = -1;
  SIDList list = getDataBufPagesIdList(pResultBuf, sid);
546

547 548 549 550 551
  if (list.size == 0) {
    pData = getNewDataBuf(pResultBuf, sid, &pageId);
  } else {
    pageId = getLastPageId(&list);
    pData = getResultBufferPageById(pResultBuf, pageId);
552

553
    if (pData->num >= numOfRowsPerPage) {
554 555
      pData = getNewDataBuf(pResultBuf, sid, &pageId);
      if (pData != NULL) {
556
        assert(pData->num == 0);  // number of elements must be 0 for new allocated buffer
557 558 559
      }
    }
  }
560

561 562 563
  if (pData == NULL) {
    return -1;
  }
564

565 566 567
  // set the number of rows in current disk page
  if (pWindowRes->pos.pageId == -1) {  // not allocated yet, allocate new buffer
    pWindowRes->pos.pageId = pageId;
568
    pWindowRes->pos.rowId = pData->num++;
569
  }
570

571 572 573 574 575 576 577
  return 0;
}

static int32_t setWindowOutputBufByKey(SQueryRuntimeEnv *pRuntimeEnv, SWindowResInfo *pWindowResInfo, int32_t sid,
                                       STimeWindow *win) {
  assert(win->skey <= win->ekey);
  SDiskbasedResultBuf *pResultBuf = pRuntimeEnv->pResultBuf;
578

579 580 581 582
  SWindowResult *pWindowRes = doSetTimeWindowFromKey(pRuntimeEnv, pWindowResInfo, (char *)&win->skey, TSDB_KEYSIZE);
  if (pWindowRes == NULL) {
    return -1;
  }
583

584 585 586 587 588 589 590
  // not assign result buffer yet, add new result buffer
  if (pWindowRes->pos.pageId == -1) {
    int32_t ret = addNewWindowResultBuf(pWindowRes, pResultBuf, sid, pRuntimeEnv->numOfRowsPerPage);
    if (ret != 0) {
      return -1;
    }
  }
591

592 593
  // set time window for current result
  pWindowRes->window = *win;
594

595 596
  setWindowResOutputBuf(pRuntimeEnv, pWindowRes);
  initCtxOutputBuf(pRuntimeEnv);
597

598 599 600 601 602 603 604 605 606 607 608 609
  return TSDB_CODE_SUCCESS;
}

static SWindowStatus *getTimeWindowResStatus(SWindowResInfo *pWindowResInfo, int32_t slot) {
  assert(slot >= 0 && slot < pWindowResInfo->size);
  return &pWindowResInfo->pResult[slot].status;
}

static int32_t getForwardStepsInBlock(int32_t numOfPoints, __block_search_fn_t searchFn, TSKEY ekey, int16_t pos,
                                      int16_t order, int64_t *pData) {
  int32_t endPos = searchFn((char *)pData, numOfPoints, ekey, order);
  int32_t forwardStep = 0;
610

611
  if (endPos >= 0) {
612
    forwardStep = (order == TSDB_ORDER_ASC) ? (endPos - pos) : (pos - endPos);
613
    assert(forwardStep >= 0);
614

615 616 617 618 619
    // endPos data is equalled to the key so, we do need to read the element in endPos
    if (pData[endPos] == ekey) {
      forwardStep += 1;
    }
  }
620

621 622 623 624 625 626 627 628 629 630 631
  return forwardStep;
}

/**
 * NOTE: the query status only set for the first scan of master scan.
 */
static void doCheckQueryCompleted(SQueryRuntimeEnv *pRuntimeEnv, TSKEY lastKey, SWindowResInfo *pWindowResInfo) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
  if (pRuntimeEnv->scanFlag != MASTER_SCAN || (!isIntervalQuery(pQuery))) {
    return;
  }
632

633 634 635 636
  // no qualified results exist, abort check
  if (pWindowResInfo->size == 0) {
    return;
  }
637

638
  // query completed
H
hjxilinx 已提交
639 640
  if ((lastKey >= pQuery->current->win.ekey && QUERY_IS_ASC_QUERY(pQuery)) ||
      (lastKey <= pQuery->current->win.ekey && !QUERY_IS_ASC_QUERY(pQuery))) {
641
    closeAllTimeWindow(pWindowResInfo);
642

643 644 645 646
    pWindowResInfo->curIndex = pWindowResInfo->size - 1;
    setQueryStatus(pQuery, QUERY_COMPLETED | QUERY_RESBUF_FULL);
  } else {  // set the current index to be the last unclosed window
    int32_t i = 0;
647
    int64_t skey = TSKEY_INITIAL_VAL;
648

649
    // TODO opt performance: get the closed time window here
650 651 652 653 654
    for (i = 0; i < pWindowResInfo->size; ++i) {
      SWindowResult *pResult = &pWindowResInfo->pResult[i];
      if (pResult->status.closed) {
        continue;
      }
655

656 657 658 659 660 661 662 663
      if ((pResult->window.ekey <= lastKey && QUERY_IS_ASC_QUERY(pQuery)) ||
          (pResult->window.skey >= lastKey && !QUERY_IS_ASC_QUERY(pQuery))) {
        closeTimeWindow(pWindowResInfo, i);
      } else {
        skey = pResult->window.skey;
        break;
      }
    }
664

665
    // all windows are closed, set the last one to be the skey
666
    if (skey == TSKEY_INITIAL_VAL) {
667 668 669 670 671
      assert(i == pWindowResInfo->size);
      pWindowResInfo->curIndex = pWindowResInfo->size - 1;
    } else {
      pWindowResInfo->curIndex = i;
    }
672

673
    pWindowResInfo->prevSKey = pWindowResInfo->pResult[pWindowResInfo->curIndex].window.skey;
674

675 676 677 678 679
    // the number of completed slots are larger than the threshold, dump to client immediately.
    int32_t n = numOfClosedTimeWindow(pWindowResInfo);
    if (n > pWindowResInfo->threshold) {
      setQueryStatus(pQuery, QUERY_RESBUF_FULL);
    }
680

H
hjxilinx 已提交
681
    qTrace("QInfo:%p total window:%d, closed:%d", GET_QINFO_ADDR(pRuntimeEnv), pWindowResInfo->size, n);
682
  }
683

684
  assert(pWindowResInfo->prevSKey != TSKEY_INITIAL_VAL);
685 686 687
}

static int32_t getNumOfRowsInTimeWindow(SQuery *pQuery, SDataBlockInfo *pDataBlockInfo, TSKEY *pPrimaryColumn,
H
hjxilinx 已提交
688
                                        int32_t startPos, TSKEY ekey, __block_search_fn_t searchFn, bool updateLastKey) {
689
  assert(startPos >= 0 && startPos < pDataBlockInfo->rows);
690

691 692 693
  int32_t num = -1;
  int32_t order = pQuery->order.order;
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
694

H
hjxilinx 已提交
695 696
  STableQueryInfo* item = pQuery->current;
  
697 698
  if (QUERY_IS_ASC_QUERY(pQuery)) {
    if (ekey < pDataBlockInfo->window.ekey) {
699
      num = getForwardStepsInBlock(pDataBlockInfo->rows, searchFn, ekey, startPos, order, pPrimaryColumn);
700 701 702 703
      if (num == 0) {  // no qualified data in current block, do not update the lastKey value
        assert(ekey < pPrimaryColumn[startPos]);
      } else {
        if (updateLastKey) {
H
hjxilinx 已提交
704
          item->lastKey = pPrimaryColumn[startPos + (num - 1)] + step;
705 706 707
        }
      }
    } else {
708
      num = pDataBlockInfo->rows - startPos;
709
      if (updateLastKey) {
H
hjxilinx 已提交
710
        item->lastKey = pDataBlockInfo->window.ekey + step;
711 712 713 714
      }
    }
  } else {  // desc
    if (ekey > pDataBlockInfo->window.skey) {
715
      num = getForwardStepsInBlock(pDataBlockInfo->rows, searchFn, ekey, startPos, order, pPrimaryColumn);
716 717 718 719
      if (num == 0) {  // no qualified data in current block, do not update the lastKey value
        assert(ekey > pPrimaryColumn[startPos]);
      } else {
        if (updateLastKey) {
H
hjxilinx 已提交
720
          item->lastKey = pPrimaryColumn[startPos - (num - 1)] + step;
721 722 723 724 725
        }
      }
    } else {
      num = startPos + 1;
      if (updateLastKey) {
H
hjxilinx 已提交
726
        item->lastKey = pDataBlockInfo->window.skey + step;
727 728 729
      }
    }
  }
730

731 732 733 734 735
  assert(num >= 0);
  return num;
}

static void doBlockwiseApplyFunctions(SQueryRuntimeEnv *pRuntimeEnv, SWindowStatus *pStatus, STimeWindow *pWin,
736
                                      int32_t startPos, int32_t forwardStep, TSKEY *tsBuf) {
737 738
  SQuery *        pQuery = pRuntimeEnv->pQuery;
  SQLFunctionCtx *pCtx = pRuntimeEnv->pCtx;
739

740
  if (IS_MASTER_SCAN(pRuntimeEnv) || pStatus->closed) {
741
    for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
742
      int32_t functionId = pQuery->pSelectExpr[k].base.functionId;
743

744 745 746
      pCtx[k].nStartQueryTimestamp = pWin->skey;
      pCtx[k].size = forwardStep;
      pCtx[k].startOffset = (QUERY_IS_ASC_QUERY(pQuery)) ? startPos : startPos - (forwardStep - 1);
747

748 749 750
      if ((aAggs[functionId].nStatus & TSDB_FUNCSTATE_SELECTIVITY) != 0) {
        pCtx[k].ptsList = &tsBuf[pCtx[k].startOffset];
      }
751

752 753 754 755 756 757 758 759 760 761 762
      if (functionNeedToExecute(pRuntimeEnv, &pCtx[k], functionId)) {
        aAggs[functionId].xFunction(&pCtx[k]);
      }
    }
  }
}

static void doRowwiseApplyFunctions(SQueryRuntimeEnv *pRuntimeEnv, SWindowStatus *pStatus, STimeWindow *pWin,
                                    int32_t offset) {
  SQuery *        pQuery = pRuntimeEnv->pQuery;
  SQLFunctionCtx *pCtx = pRuntimeEnv->pCtx;
763

764
  if (IS_MASTER_SCAN(pRuntimeEnv) || pStatus->closed) {
765
    for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
766
      pCtx[k].nStartQueryTimestamp = pWin->skey;
767

768
      int32_t functionId = pQuery->pSelectExpr[k].base.functionId;
769 770 771 772 773 774 775 776
      if (functionNeedToExecute(pRuntimeEnv, &pCtx[k], functionId)) {
        aAggs[functionId].xFunctionF(&pCtx[k], offset);
      }
    }
  }
}

static int32_t getNextQualifiedWindow(SQueryRuntimeEnv *pRuntimeEnv, STimeWindow *pNextWin,
777 778
                                      SDataBlockInfo *pDataBlockInfo, TSKEY *primaryKeys,
                                      __block_search_fn_t searchFn) {
779
  SQuery *pQuery = pRuntimeEnv->pQuery;
780

781 782 783 784 785
  while (1) {
    if ((pNextWin->ekey > pQuery->window.ekey && QUERY_IS_ASC_QUERY(pQuery)) ||
        (pNextWin->skey < pQuery->window.ekey && !QUERY_IS_ASC_QUERY(pQuery))) {
      return -1;
    }
786

787
    getNextTimeWindow(pQuery, pNextWin);
788

789 790 791 792 793
    // next time window is not in current block
    if ((pNextWin->skey > pDataBlockInfo->window.ekey && QUERY_IS_ASC_QUERY(pQuery)) ||
        (pNextWin->ekey < pDataBlockInfo->window.skey && !QUERY_IS_ASC_QUERY(pQuery))) {
      return -1;
    }
794

795 796 797 798 799 800 801 802 803 804 805 806
    TSKEY startKey = -1;
    if (QUERY_IS_ASC_QUERY(pQuery)) {
      startKey = pNextWin->skey;
      if (startKey < pQuery->window.skey) {
        startKey = pQuery->window.skey;
      }
    } else {
      startKey = pNextWin->ekey;
      if (startKey > pQuery->window.skey) {
        startKey = pQuery->window.skey;
      }
    }
807

808
    int32_t startPos = searchFn((char *)primaryKeys, pDataBlockInfo->rows, startKey, pQuery->order.order);
809

810 811 812 813 814 815 816 817
    /*
     * This time window does not cover any data, try next time window,
     * this case may happen when the time window is too small
     */
    if ((primaryKeys[startPos] > pNextWin->ekey && QUERY_IS_ASC_QUERY(pQuery)) ||
        (primaryKeys[startPos] < pNextWin->skey && !QUERY_IS_ASC_QUERY(pQuery))) {
      continue;
    }
818

819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
    return startPos;
  }
}

static TSKEY reviseWindowEkey(SQuery *pQuery, STimeWindow *pWindow) {
  TSKEY ekey = -1;
  if (QUERY_IS_ASC_QUERY(pQuery)) {
    ekey = pWindow->ekey;
    if (ekey > pQuery->window.ekey) {
      ekey = pQuery->window.ekey;
    }
  } else {
    ekey = pWindow->skey;
    if (ekey < pQuery->window.ekey) {
      ekey = pQuery->window.ekey;
    }
  }
836

837 838 839
  return ekey;
}

H
hjxilinx 已提交
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854
//todo binary search
static void* getDataBlockImpl(SArray* pDataBlock, int32_t colId) {
  int32_t numOfCols = taosArrayGetSize(pDataBlock);
  
  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData *p = taosArrayGet(pDataBlock, i);
    if (colId == p->info.colId) {
      return p->pData;
    }
  }
  
  return NULL;
}

static char *getDataBlock(SQueryRuntimeEnv *pRuntimeEnv, SArithmeticSupport *sas, int32_t col, int32_t size,
855
                    SArray *pDataBlock) {
856
  char *dataBlock = NULL;
857 858 859
  SQuery *pQuery = pRuntimeEnv->pQuery;
  
  SQLFunctionCtx *pCtx = pRuntimeEnv->pCtx;
860

861
  int32_t functionId = pQuery->pSelectExpr[col].base.functionId;
862
  if (functionId == TSDB_FUNC_ARITHM) {
863
    sas->pArithExpr = &pQuery->pSelectExpr[col];
864

865 866 867 868 869 870
    // set the start offset to be the lowest start position, no matter asc/desc query order
    if (QUERY_IS_ASC_QUERY(pQuery)) {
      pCtx->startOffset = pQuery->pos;
    } else {
      pCtx->startOffset = pQuery->pos - (size - 1);
    }
871 872 873 874 875 876 877
  
    sas->offset  = 0;
    sas->colList = pQuery->colList;
    sas->numOfCols = pQuery->numOfCols;
    sas->data    = calloc(pQuery->numOfCols, POINTER_BYTES);
    
    // here the pQuery->colList and sas->colList are identical
878
    for (int32_t i = 0; i < pQuery->numOfCols; ++i) {
879
      SColumnInfo *pColMsg = &pQuery->colList[i];
880 881 882 883 884 885 886 887 888 889 890 891 892 893
  
      int32_t numOfCols = taosArrayGetSize(pDataBlock);
      
      dataBlock = NULL;
      for (int32_t k = 0; k < numOfCols; ++k) {  //todo refactor
        SColumnInfoData *p = taosArrayGet(pDataBlock, k);
        if (pColMsg->colId == p->info.colId) {
          dataBlock = p->pData;
          break;
        }
      }
      
      assert(dataBlock != NULL);
      sas->data[i] = dataBlock + pCtx->startOffset * pQuery->colList[i].bytes;  // start from the offset
894
    }
895

896
  } else {  // other type of query function
897
    SColIndex *pCol = &pQuery->pSelectExpr[col].base.colInfo;
898
    if (TSDB_COL_IS_TAG(pCol->flag) || pDataBlock == NULL) {
899 900
      dataBlock = NULL;
    } else {
H
hjxilinx 已提交
901
      dataBlock = getDataBlockImpl(pDataBlock, pCol->colId);
902 903
    }
  }
904

905 906 907 908 909 910 911 912 913 914 915 916 917
  return dataBlock;
}

/**
 *
 * @param pRuntimeEnv
 * @param forwardStep
 * @param primaryKeyCol
 * @param pFields
 * @param isDiskFileBlock
 * @return                  the incremental number of output value, so it maybe 0 for fixed number of query,
 *                          such as count/min/max etc.
 */
918
static void blockwiseApplyFunctions(SQueryRuntimeEnv *pRuntimeEnv, SDataStatis *pStatis,
919 920
                                       SDataBlockInfo *pDataBlockInfo, SWindowResInfo *pWindowResInfo,
                                       __block_search_fn_t searchFn, SArray *pDataBlock) {
921 922
  SQLFunctionCtx *pCtx = pRuntimeEnv->pCtx;
  SQuery *        pQuery = pRuntimeEnv->pQuery;
923

H
hjxilinx 已提交
924
  SColumnInfoData *pColInfo = NULL;
H
hjxilinx 已提交
925 926
  
  TSKEY *primaryKeyCol = NULL;
927 928 929 930
  if (pDataBlock != NULL) {
    pColInfo = taosArrayGet(pDataBlock, 0);
    primaryKeyCol = (TSKEY *)(pColInfo->pData);
  }
931

932
  SArithmeticSupport *sasArray = calloc((size_t)pQuery->numOfOutput, sizeof(SArithmeticSupport));
933
  
934
  for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
935
    int32_t functionId = pQuery->pSelectExpr[k].base.functionId;
936

937
    SDataStatis *tpField = NULL;
938 939

    bool  hasNull = hasNullValue(pQuery, k, pDataBlockInfo, pStatis, &tpField);
H
hjxilinx 已提交
940
    char *dataBlock = getDataBlock(pRuntimeEnv, &sasArray[k], k, pDataBlockInfo->rows, pDataBlock);
941

942 943
    setExecParams(pQuery, &pCtx[k], dataBlock, primaryKeyCol, pDataBlockInfo->rows, functionId, tpField, hasNull,
                  &sasArray[k], pRuntimeEnv->scanFlag);
944
  }
945

946 947 948 949
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);
  if (isIntervalQuery(pQuery)) {
    int32_t offset = GET_COL_DATA_POS(pQuery, 0, step);
    TSKEY   ts = primaryKeyCol[offset];
950

951
    STimeWindow win = getActiveTimeWindow(pWindowResInfo, ts, pQuery);
H
hjxilinx 已提交
952
    if (setWindowOutputBufByKey(pRuntimeEnv, pWindowResInfo, pDataBlockInfo->tid, &win) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
953
      return;
954
    }
955

956 957 958
    TSKEY   ekey = reviseWindowEkey(pQuery, &win);
    int32_t forwardStep =
        getNumOfRowsInTimeWindow(pQuery, pDataBlockInfo, primaryKeyCol, pQuery->pos, ekey, searchFn, true);
959

960 961
    SWindowStatus *pStatus = getTimeWindowResStatus(pWindowResInfo, curTimeWindow(pWindowResInfo));
    doBlockwiseApplyFunctions(pRuntimeEnv, pStatus, &win, pQuery->pos, forwardStep, primaryKeyCol);
962

963 964
    int32_t     index = pWindowResInfo->curIndex;
    STimeWindow nextWin = win;
965

966
    while (1) {
967
      int32_t startPos = getNextQualifiedWindow(pRuntimeEnv, &nextWin, pDataBlockInfo, primaryKeyCol, searchFn);
968 969 970
      if (startPos < 0) {
        break;
      }
971

972
      // null data, failed to allocate more memory buffer
H
hjxilinx 已提交
973
      if (setWindowOutputBufByKey(pRuntimeEnv, pWindowResInfo, pDataBlockInfo->tid, &nextWin) != TSDB_CODE_SUCCESS) {
974 975
        break;
      }
976

977 978
      ekey = reviseWindowEkey(pQuery, &nextWin);
      forwardStep = getNumOfRowsInTimeWindow(pQuery, pDataBlockInfo, primaryKeyCol, startPos, ekey, searchFn, true);
979

980 981 982
      pStatus = getTimeWindowResStatus(pWindowResInfo, curTimeWindow(pWindowResInfo));
      doBlockwiseApplyFunctions(pRuntimeEnv, pStatus, &nextWin, startPos, forwardStep, primaryKeyCol);
    }
983

984 985 986 987 988 989 990
    pWindowResInfo->curIndex = index;
  } else {
    /*
     * the sqlfunctionCtx parameters should be set done before all functions are invoked,
     * since the selectivity + tag_prj query needs all parameters been set done.
     * tag_prj function are changed to be TSDB_FUNC_TAG_DUMMY
     */
991
    for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
992
      int32_t functionId = pQuery->pSelectExpr[k].base.functionId;
993 994 995 996 997
      if (functionNeedToExecute(pRuntimeEnv, &pCtx[k], functionId)) {
        aAggs[functionId].xFunction(&pCtx[k]);
      }
    }
  }
998

999 1000 1001 1002 1003 1004 1005 1006
  for(int32_t i = 0; i < pQuery->numOfOutput; ++i) {
    if (pQuery->pSelectExpr[i].base.functionId != TSDB_FUNC_ARITHM) {
      continue;
    }
    
    tfree(sasArray[i].data);
  }
  
1007 1008 1009 1010 1011 1012 1013
  tfree(sasArray);
}

static int32_t setGroupResultOutputBuf(SQueryRuntimeEnv *pRuntimeEnv, char *pData, int16_t type, int16_t bytes) {
  if (isNull(pData, type)) {  // ignore the null value
    return -1;
  }
1014

1015
  int32_t GROUPRESULTID = 1;
1016

1017
  SDiskbasedResultBuf *pResultBuf = pRuntimeEnv->pResultBuf;
1018

1019 1020 1021 1022
  SWindowResult *pWindowRes = doSetTimeWindowFromKey(pRuntimeEnv, &pRuntimeEnv->windowResInfo, pData, bytes);
  if (pWindowRes == NULL) {
    return -1;
  }
1023

1024 1025 1026 1027 1028 1029 1030
  // not assign result buffer yet, add new result buffer
  if (pWindowRes->pos.pageId == -1) {
    int32_t ret = addNewWindowResultBuf(pWindowRes, pResultBuf, GROUPRESULTID, pRuntimeEnv->numOfRowsPerPage);
    if (ret != 0) {
      return -1;
    }
  }
1031

1032 1033 1034 1035 1036
  setWindowResOutputBuf(pRuntimeEnv, pWindowRes);
  initCtxOutputBuf(pRuntimeEnv);
  return TSDB_CODE_SUCCESS;
}

1037
static char *getGroupbyColumnData(SQuery *pQuery, int16_t *type, int16_t *bytes, SArray* pDataBlock) {
1038
  SSqlGroupbyExpr *pGroupbyExpr = pQuery->pGroupbyExpr;
1039

1040
  for (int32_t k = 0; k < pGroupbyExpr->numOfGroupCols; ++k) {
1041 1042
    SColIndex* pColIndex = taosArrayGet(pGroupbyExpr->columnInfo, k);
    if (pColIndex->flag == TSDB_COL_TAG) {
1043 1044
      continue;
    }
1045

1046
    int16_t colIndex = -1;
1047
    int32_t colId = pColIndex->colId;
1048

1049
    for (int32_t i = 0; i < pQuery->numOfCols; ++i) {
1050
      if (pQuery->colList[i].colId == colId) {
1051 1052 1053 1054
        colIndex = i;
        break;
      }
    }
1055

1056
    assert(colIndex >= 0 && colIndex < pQuery->numOfCols);
1057

1058 1059
    *type = pQuery->colList[colIndex].type;
    *bytes = pQuery->colList[colIndex].bytes;
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
    /*
     *  the colIndex is acquired from the first meter of all qualified meters in this vnode during query prepare
     * stage, the remain meter may not have the required column in cache actually. So, the validation of required
     * column in cache with the corresponding meter schema is reinforced.
     */
    int32_t numOfCols = taosArrayGetSize(pDataBlock);
  
    for (int32_t i = 0; i < numOfCols; ++i) {
      SColumnInfoData *p = taosArrayGet(pDataBlock, i);
      if (pColIndex->colId == p->info.colId) {
        return p->pData;
      }
    }
1073
  }
1074 1075
  
  return NULL;
1076 1077 1078 1079
}

static int32_t doTSJoinFilter(SQueryRuntimeEnv *pRuntimeEnv, int32_t offset) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
1080

1081 1082
  STSElem         elem = tsBufGetElem(pRuntimeEnv->pTSBuf);
  SQLFunctionCtx *pCtx = pRuntimeEnv->pCtx;
1083

1084 1085 1086 1087
  // compare tag first
  if (pCtx[0].tag.i64Key != elem.tag) {
    return TS_JOIN_TAG_NOT_EQUALS;
  }
1088

1089 1090 1091
  TSKEY key = *(TSKEY *)(pCtx[0].aInputElemBuf + TSDB_KEYSIZE * offset);

#if defined(_DEBUG_VIEW)
1092 1093
  printf("elem in comp ts file:%" PRId64 ", key:%" PRId64 ", tag:%"PRIu64", query order:%d, ts order:%d, traverse:%d, index:%d\n",
         elem.ts, key, elem.tag, pQuery->order.order, pRuntimeEnv->pTSBuf->tsOrder,
1094 1095
         pRuntimeEnv->pTSBuf->cur.order, pRuntimeEnv->pTSBuf->cur.tsIndex);
#endif
1096

1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
  if (QUERY_IS_ASC_QUERY(pQuery)) {
    if (key < elem.ts) {
      return TS_JOIN_TS_NOT_EQUALS;
    } else if (key > elem.ts) {
      assert(false);
    }
  } else {
    if (key > elem.ts) {
      return TS_JOIN_TS_NOT_EQUALS;
    } else if (key < elem.ts) {
      assert(false);
    }
  }
1110

1111 1112 1113 1114 1115
  return TS_JOIN_TS_EQUAL;
}

static bool functionNeedToExecute(SQueryRuntimeEnv *pRuntimeEnv, SQLFunctionCtx *pCtx, int32_t functionId) {
  SResultInfo *pResInfo = GET_RES_INFO(pCtx);
H
hjxilinx 已提交
1116 1117
  SQuery* pQuery = pRuntimeEnv->pQuery;
  
1118 1119 1120
  if (pResInfo->complete || functionId == TSDB_FUNC_TAG_DUMMY || functionId == TSDB_FUNC_TS_DUMMY) {
    return false;
  }
1121

H
hjxilinx 已提交
1122 1123 1124 1125 1126 1127
  if (functionId == TSDB_FUNC_LAST_DST || functionId == TSDB_FUNC_LAST) {
    return !QUERY_IS_ASC_QUERY(pQuery);
  } else if (functionId == TSDB_FUNC_FIRST_DST || functionId == TSDB_FUNC_FIRST) {
    return QUERY_IS_ASC_QUERY(pQuery);
  }
  
1128
  // in the supplementary scan, only the following functions need to be executed
H
hjxilinx 已提交
1129
  if (IS_REVERSE_SCAN(pRuntimeEnv)) {// && (functionId == TSDB_FUNC_TAG || functionId == TSDB_FUNC_TS)) {
1130 1131
    return false;
  }
1132

1133 1134 1135
  return true;
}

1136 1137
static void rowwiseApplyFunctions(SQueryRuntimeEnv *pRuntimeEnv, SDataStatis *pStatis, SDataBlockInfo *pDataBlockInfo,
    SWindowResInfo *pWindowResInfo, SArray *pDataBlock) {
1138
  SQLFunctionCtx *pCtx = pRuntimeEnv->pCtx;
1139 1140
  
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
1141 1142
  STableQueryInfo* item = pQuery->current;
  
1143
  TSKEY  *primaryKeyCol = (TSKEY*) ((SColumnInfoData *)taosArrayGet(pDataBlock, 0))->pData;
H
hjxilinx 已提交
1144
  bool    groupbyStateValue = isGroupbyNormalCol(pQuery->pGroupbyExpr);
1145
  SArithmeticSupport *sasArray = calloc((size_t)pQuery->numOfOutput, sizeof(SArithmeticSupport));
1146

1147 1148
  int16_t type = 0;
  int16_t bytes = 0;
1149

1150 1151
  char *groupbyColumnData = NULL;
  if (groupbyStateValue) {
1152
    groupbyColumnData = getGroupbyColumnData(pQuery, &type, &bytes, pDataBlock);
1153
  }
1154

1155
  for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
1156
    int32_t functionId = pQuery->pSelectExpr[k].base.functionId;
1157 1158 1159

    SDataStatis *pColStatis = NULL;

1160
    bool  hasNull = hasNullValue(pQuery, k, pDataBlockInfo, pStatis, &pColStatis);
H
hjxilinx 已提交
1161
    char *dataBlock = getDataBlock(pRuntimeEnv, &sasArray[k], k, pDataBlockInfo->rows, pDataBlock);
1162

1163 1164
    setExecParams(pQuery, &pCtx[k], dataBlock, primaryKeyCol, pDataBlockInfo->rows, functionId, pColStatis, hasNull,
                  &sasArray[k], pRuntimeEnv->scanFlag);
1165
  }
1166

1167 1168
  // set the input column data
  for (int32_t k = 0; k < pQuery->numOfFilterCols; ++k) {
1169
    SSingleColumnFilterInfo *pFilterInfo = &pQuery->pFilterInfo[k];
H
hjxilinx 已提交
1170 1171
    pFilterInfo->pData = getDataBlockImpl(pDataBlock, pFilterInfo->info.colId);
    assert(pFilterInfo->pData != NULL);
1172
  }
1173

1174
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);
1175

1176 1177 1178 1179
  // from top to bottom in desc
  // from bottom to top in asc order
  if (pRuntimeEnv->pTSBuf != NULL) {
    SQInfo *pQInfo = (SQInfo *)GET_QINFO_ADDR(pQuery);
1180
    qTrace("QInfo:%p process data rows, numOfRows:%d, query order:%d, ts comp order:%d", pQInfo, pDataBlockInfo->rows,
1181 1182
           pQuery->order.order, pRuntimeEnv->pTSBuf->cur.order);
  }
1183

1184
  int32_t j = 0;
H
hjxilinx 已提交
1185 1186
  int32_t offset = -1;
  
1187
  for (j = 0; j < pDataBlockInfo->rows; ++j) {
H
hjxilinx 已提交
1188
    offset = GET_COL_DATA_POS(pQuery, j, step);
1189

1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    if (pRuntimeEnv->pTSBuf != NULL) {
      int32_t r = doTSJoinFilter(pRuntimeEnv, offset);
      if (r == TS_JOIN_TAG_NOT_EQUALS) {
        break;
      } else if (r == TS_JOIN_TS_NOT_EQUALS) {
        continue;
      } else {
        assert(r == TS_JOIN_TS_EQUAL);
      }
    }
1200

1201
    if (pQuery->numOfFilterCols > 0 && (!doFilterData(pQuery, offset))) {
1202 1203
      continue;
    }
1204

1205 1206 1207 1208 1209
    // interval window query
    if (isIntervalQuery(pQuery)) {
      // decide the time window according to the primary timestamp
      int64_t     ts = primaryKeyCol[offset];
      STimeWindow win = getActiveTimeWindow(pWindowResInfo, ts, pQuery);
1210

H
hjxilinx 已提交
1211
      int32_t ret = setWindowOutputBufByKey(pRuntimeEnv, pWindowResInfo, pDataBlockInfo->tid, &win);
1212 1213 1214
      if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
        continue;
      }
1215

1216 1217
      // all startOffset are identical
      offset -= pCtx[0].startOffset;
1218

1219 1220
      SWindowStatus *pStatus = getTimeWindowResStatus(pWindowResInfo, curTimeWindow(pWindowResInfo));
      doRowwiseApplyFunctions(pRuntimeEnv, pStatus, &win, offset);
1221

1222 1223
      STimeWindow nextWin = win;
      int32_t     index = pWindowResInfo->curIndex;
1224

1225 1226
      while (1) {
        getNextTimeWindow(pQuery, &nextWin);
H
Haojun Liao 已提交
1227
        if (/*pWindowResInfo->startTime > nextWin.skey ||*/
1228
            (nextWin.skey > pQuery->window.ekey && QUERY_IS_ASC_QUERY(pQuery)) ||
H
Haojun Liao 已提交
1229
            (nextWin.skey < pQuery->window.ekey && !QUERY_IS_ASC_QUERY(pQuery))) {
1230 1231
          break;
        }
1232

1233 1234 1235
        if (ts < nextWin.skey || ts > nextWin.ekey) {
          break;
        }
1236

1237
        // null data, failed to allocate more memory buffer
H
hjxilinx 已提交
1238
        if (setWindowOutputBufByKey(pRuntimeEnv, pWindowResInfo, pDataBlockInfo->tid, &nextWin) != TSDB_CODE_SUCCESS) {
1239 1240
          break;
        }
1241

1242 1243 1244
        pStatus = getTimeWindowResStatus(pWindowResInfo, curTimeWindow(pWindowResInfo));
        doRowwiseApplyFunctions(pRuntimeEnv, pStatus, &nextWin, offset);
      }
1245

1246 1247 1248 1249
      pWindowResInfo->curIndex = index;
    } else {  // other queries
      // decide which group this rows belongs to according to current state value
      if (groupbyStateValue) {
H
hjxilinx 已提交
1250
        char *val = groupbyColumnData + bytes * offset;
1251

H
hjxilinx 已提交
1252
        int32_t ret = setGroupResultOutputBuf(pRuntimeEnv, val, type, bytes);
1253 1254 1255 1256
        if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
          continue;
        }
      }
1257

1258 1259
      // all startOffset are identical
      offset -= pCtx[0].startOffset;
1260

1261
      for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
1262
        int32_t functionId = pQuery->pSelectExpr[k].base.functionId;
1263 1264 1265 1266 1267
        if (functionNeedToExecute(pRuntimeEnv, &pCtx[k], functionId)) {
          aAggs[functionId].xFunctionF(&pCtx[k], offset);
        }
      }
    }
1268

1269 1270 1271
    if (pRuntimeEnv->pTSBuf != NULL) {
      // if timestamp filter list is empty, quit current query
      if (!tsBufNextPos(pRuntimeEnv->pTSBuf)) {
H
hjxilinx 已提交
1272
        setQueryStatus(pQuery, QUERY_COMPLETED);
1273 1274 1275 1276
        break;
      }
    }
  }
1277
  
H
hjxilinx 已提交
1278
  item->lastKey = primaryKeyCol[offset] + step;
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
  
  // todo refactor: extract method
  for(int32_t i = 0; i < pQuery->numOfOutput; ++i) {
    if (pQuery->pSelectExpr[i].base.functionId != TSDB_FUNC_ARITHM) {
      continue;
    }
    
    tfree(sasArray[i].data);
  }
  
1289 1290 1291 1292
  free(sasArray);
}

static int32_t tableApplyFunctionsOnBlock(SQueryRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pDataBlockInfo,
H
hjxilinx 已提交
1293
                                          SDataStatis *pStatis, __block_search_fn_t searchFn, SArray *pDataBlock) {
H
hjxilinx 已提交
1294
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
1295 1296 1297
  
  STableQueryInfo* pTableQInfo = pQuery->current;
  SWindowResInfo*  pWindowResInfo = &pRuntimeEnv->windowResInfo;
H
hjxilinx 已提交
1298
  
1299
  if (pQuery->numOfFilterCols > 0 || pRuntimeEnv->pTSBuf != NULL || isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
1300
    rowwiseApplyFunctions(pRuntimeEnv, pStatis, pDataBlockInfo, pWindowResInfo, pDataBlock);
1301
  } else {
1302
    blockwiseApplyFunctions(pRuntimeEnv, pStatis, pDataBlockInfo, pWindowResInfo, searchFn, pDataBlock);
1303
  }
1304 1305

  TSKEY lastKey = QUERY_IS_ASC_QUERY(pQuery) ? pDataBlockInfo->window.ekey : pDataBlockInfo->window.skey;
H
hjxilinx 已提交
1306
  pTableQInfo->lastKey = lastKey + GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);
1307

1308
  doCheckQueryCompleted(pRuntimeEnv, lastKey, pWindowResInfo);
1309

1310 1311 1312 1313 1314 1315
  // interval query with limit applied
  if (isIntervalQuery(pQuery) && pQuery->limit.limit > 0 &&
      (pQuery->limit.limit + pQuery->limit.offset) <= numOfClosedTimeWindow(pWindowResInfo) &&
      pRuntimeEnv->scanFlag == MASTER_SCAN) {
    setQueryStatus(pQuery, QUERY_COMPLETED);
  }
1316

1317
  int32_t numOfRes = getNumOfResult(pRuntimeEnv);
1318

1319 1320 1321 1322
  // update the number of output result
  if (numOfRes > 0 && pQuery->checkBuffer == 1) {
    assert(numOfRes >= pQuery->rec.rows);
    pQuery->rec.rows = numOfRes;
1323

1324 1325 1326
    if (numOfRes >= pQuery->rec.threshold) {
      setQueryStatus(pQuery, QUERY_RESBUF_FULL);
    }
H
Haojun Liao 已提交
1327
    
H
Haojun Liao 已提交
1328
    if ((pQuery->limit.limit >= 0) && numOfRes >= (pQuery->limit.limit + pQuery->limit.offset)) {
H
Haojun Liao 已提交
1329 1330
      setQueryStatus(pQuery, QUERY_COMPLETED);
    }
1331
  }
1332

1333
  return numOfRes;
1334 1335
}

1336
void setExecParams(SQuery *pQuery, SQLFunctionCtx *pCtx, void *inputData, TSKEY *tsCol, int32_t size,
1337 1338
                   int32_t functionId, SDataStatis *pStatis, bool hasNull, void *param, int32_t scanFlag) {
  pCtx->scanFlag = scanFlag;
1339

1340 1341
  pCtx->aInputElemBuf = inputData;
  pCtx->hasNull = hasNull;
1342

1343 1344 1345 1346 1347 1348 1349
  if (pStatis != NULL) {
    pCtx->preAggVals.isSet = true;
    pCtx->preAggVals.size = size;
    pCtx->preAggVals.statis = *pStatis;
  } else {
    pCtx->preAggVals.isSet = false;
  }
1350 1351 1352 1353

  pCtx->startOffset = QUERY_IS_ASC_QUERY(pQuery) ? pQuery->pos : 0;
  pCtx->size = QUERY_IS_ASC_QUERY(pQuery) ? size - pQuery->pos : pQuery->pos + 1;

1354 1355 1356
  uint32_t status = aAggs[functionId].nStatus;
  if (((status & (TSDB_FUNCSTATE_SELECTIVITY | TSDB_FUNCSTATE_NEED_TS)) != 0) && (tsCol != NULL)) {
    pCtx->ptsList = &tsCol[pCtx->startOffset];
1357
  }
1358

1359 1360 1361 1362 1363
  if (functionId >= TSDB_FUNC_FIRST_DST && functionId <= TSDB_FUNC_LAST_DST) {
    // last_dist or first_dist function
    // store the first&last timestamp into the intermediate buffer [1], the true
    // value may be null but timestamp will never be null
  } else if (functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM || functionId == TSDB_FUNC_TWA ||
1364
             functionId == TSDB_FUNC_DIFF || (functionId >= TSDB_FUNC_RATE && functionId <= TSDB_FUNC_AVG_IRATE)) {
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
    /*
     * leastsquares function needs two columns of input, currently, the x value of linear equation is set to
     * timestamp column, and the y-value is the column specified in pQuery->pSelectExpr[i].colIdxInBuffer
     *
     * top/bottom function needs timestamp to indicate when the
     * top/bottom values emerge, so does diff function
     */
    if (functionId == TSDB_FUNC_TWA) {
      STwaInfo *pTWAInfo = GET_RES_INFO(pCtx)->interResultBuf;
      pTWAInfo->SKey = pQuery->window.skey;
      pTWAInfo->EKey = pQuery->window.ekey;
    }
1377

1378 1379 1380
  } else if (functionId == TSDB_FUNC_ARITHM) {
    pCtx->param[1].pz = param;
  }
1381

1382 1383 1384 1385 1386 1387
#if defined(_DEBUG_VIEW)
  //  int64_t *tsList = (int64_t *)primaryColumnData;
//  int64_t  s = tsList[0];
//  int64_t  e = tsList[size - 1];

//    if (IS_DATA_BLOCK_LOADED(blockStatus)) {
S
slguan 已提交
1388
//        qTrace("QInfo:%p query ts:%lld-%lld, offset:%d, rows:%d, bstatus:%d,
1389 1390 1391
//        functId:%d", GET_QINFO_ADDR(pQuery),
//               s, e, startOffset, size, blockStatus, functionId);
//    } else {
S
slguan 已提交
1392
//        qTrace("QInfo:%p block not loaded, bstatus:%d",
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
//        GET_QINFO_ADDR(pQuery), blockStatus);
//    }
#endif
}

// set the output buffer for the selectivity + tag query
static void setCtxTagColumnInfo(SQuery *pQuery, SQLFunctionCtx *pCtx) {
  if (isSelectivityWithTagsQuery(pQuery)) {
    int32_t         num = 0;
    SQLFunctionCtx *p = NULL;
1403

1404
    int16_t tagLen = 0;
1405

1406 1407
    SQLFunctionCtx **pTagCtx = calloc(pQuery->numOfOutput, POINTER_BYTES);
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1408
      SSqlFuncMsg *pSqlFuncMsg = &pQuery->pSelectExpr[i].base;
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
      if (pSqlFuncMsg->functionId == TSDB_FUNC_TAG_DUMMY || pSqlFuncMsg->functionId == TSDB_FUNC_TS_DUMMY) {
        tagLen += pCtx[i].outputBytes;
        pTagCtx[num++] = &pCtx[i];
      } else if ((aAggs[pSqlFuncMsg->functionId].nStatus & TSDB_FUNCSTATE_SELECTIVITY) != 0) {
        p = &pCtx[i];
      } else if (pSqlFuncMsg->functionId == TSDB_FUNC_TS || pSqlFuncMsg->functionId == TSDB_FUNC_TAG) {
        // tag function may be the group by tag column
        // ts may be the required primary timestamp column
        continue;
      } else {
        // the column may be the normal column, group by normal_column, the functionId is TSDB_FUNC_PRJ
      }
    }
1422

1423 1424 1425 1426 1427 1428 1429
    p->tagInfo.pTagCtxList = pTagCtx;
    p->tagInfo.numOfTagCols = num;
    p->tagInfo.tagsLen = tagLen;
  }
}

static void setWindowResultInfo(SResultInfo *pResultInfo, SQuery *pQuery, bool isStableQuery) {
1430
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1431
    setResultInfoBuf(&pResultInfo[i], pQuery->pSelectExpr[i].interBytes, isStableQuery);
1432 1433 1434
  }
}

1435
static int32_t setupQueryRuntimeEnv(SQueryRuntimeEnv *pRuntimeEnv, int16_t order) {
S
slguan 已提交
1436
  qTrace("QInfo:%p setup runtime env", GET_QINFO_ADDR(pRuntimeEnv));
1437 1438
  SQuery *pQuery = pRuntimeEnv->pQuery;

1439 1440
  pRuntimeEnv->resultInfo = calloc(pQuery->numOfOutput, sizeof(SResultInfo));
  pRuntimeEnv->pCtx = (SQLFunctionCtx *)calloc(pQuery->numOfOutput, sizeof(SQLFunctionCtx));
1441

1442
  if (pRuntimeEnv->resultInfo == NULL || pRuntimeEnv->pCtx == NULL) {
1443
    goto _clean;
1444
  }
1445

1446
  pRuntimeEnv->offset[0] = 0;
1447
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1448
    SSqlFuncMsg *pSqlFuncMsg = &pQuery->pSelectExpr[i].base;
1449

1450
    SQLFunctionCtx *pCtx = &pRuntimeEnv->pCtx[i];
1451 1452 1453 1454
    SColIndex* pIndex = &pSqlFuncMsg->colInfo;
    
    int32_t index = pSqlFuncMsg->colInfo.colIndex;
    if (TSDB_COL_IS_TAG(pIndex->flag)) {
1455
      if (pIndex->colId == TSDB_TBNAME_COLUMN_INDEX) {  // todo refactor
H
hjxilinx 已提交
1456
        pCtx->inputBytes = TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE;
1457 1458 1459 1460 1461
        pCtx->inputType = TSDB_DATA_TYPE_BINARY;
      } else {
        pCtx->inputBytes = pQuery->tagColList[index].bytes;
        pCtx->inputType = pQuery->tagColList[index].type;
      }
1462 1463 1464 1465 1466
    } else {
      pCtx->inputBytes = pQuery->colList[index].bytes;
      pCtx->inputType = pQuery->colList[index].type;
    }
    
1467
    pCtx->ptsOutputBuf = NULL;
1468

1469 1470
    pCtx->outputBytes = pQuery->pSelectExpr[i].bytes;
    pCtx->outputType = pQuery->pSelectExpr[i].type;
1471

1472 1473
    pCtx->order = pQuery->order.order;
    pCtx->functionId = pSqlFuncMsg->functionId;
1474

1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
    pCtx->numOfParams = pSqlFuncMsg->numOfParams;
    for (int32_t j = 0; j < pCtx->numOfParams; ++j) {
      int16_t type = pSqlFuncMsg->arg[j].argType;
      int16_t bytes = pSqlFuncMsg->arg[j].argBytes;
      if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
        tVariantCreateFromBinary(&pCtx->param[j], pSqlFuncMsg->arg->argValue.pz, bytes, type);
      } else {
        tVariantCreateFromBinary(&pCtx->param[j], (char *)&pSqlFuncMsg->arg[j].argValue.i64, bytes, type);
      }
    }
1485

1486 1487
    // set the order information for top/bottom query
    int32_t functionId = pCtx->functionId;
1488

1489
    if (functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM || functionId == TSDB_FUNC_DIFF) {
1490
      int32_t f = pQuery->pSelectExpr[0].base.functionId;
1491
      assert(f == TSDB_FUNC_TS || f == TSDB_FUNC_TS_DUMMY);
1492

1493 1494 1495 1496
      pCtx->param[2].i64Key = order;
      pCtx->param[2].nType = TSDB_DATA_TYPE_BIGINT;
      pCtx->param[3].i64Key = functionId;
      pCtx->param[3].nType = TSDB_DATA_TYPE_BIGINT;
1497

1498 1499
      pCtx->param[1].i64Key = pQuery->order.orderColId;
    }
1500

1501 1502 1503 1504
    if (i > 0) {
      pRuntimeEnv->offset[i] = pRuntimeEnv->offset[i - 1] + pRuntimeEnv->pCtx[i - 1].outputBytes;
    }
  }
1505

1506
  // set the intermediate result output buffer
1507
  setWindowResultInfo(pRuntimeEnv->resultInfo, pQuery, pRuntimeEnv->stableQuery);
1508

1509
  // if it is group by normal column, do not set output buffer, the output buffer is pResult
1510
  if (!isGroupbyNormalCol(pQuery->pGroupbyExpr) && !pRuntimeEnv->stableQuery) {
1511 1512
    resetCtxOutputBuf(pRuntimeEnv);
  }
1513

1514 1515
  setCtxTagColumnInfo(pQuery, pRuntimeEnv->pCtx);
  return TSDB_CODE_SUCCESS;
1516

1517
_clean:
1518 1519
  tfree(pRuntimeEnv->resultInfo);
  tfree(pRuntimeEnv->pCtx);
1520

1521 1522 1523 1524 1525 1526 1527
  return TSDB_CODE_SERV_OUT_OF_MEMORY;
}

static void teardownQueryRuntimeEnv(SQueryRuntimeEnv *pRuntimeEnv) {
  if (pRuntimeEnv->pQuery == NULL) {
    return;
  }
1528

1529
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
1530 1531 1532
  SQInfo* pQInfo = (SQInfo*) GET_QINFO_ADDR(pRuntimeEnv);
  
  qTrace("QInfo:%p teardown runtime env", pQInfo);
1533
  cleanupTimeWindowInfo(&pRuntimeEnv->windowResInfo, pQuery->numOfOutput);
1534

1535
  if (pRuntimeEnv->pCtx != NULL) {
1536
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1537
      SQLFunctionCtx *pCtx = &pRuntimeEnv->pCtx[i];
1538

1539 1540 1541
      for (int32_t j = 0; j < pCtx->numOfParams; ++j) {
        tVariantDestroy(&pCtx->param[j]);
      }
1542

1543 1544 1545 1546
      tVariantDestroy(&pCtx->tag);
      tfree(pCtx->tagInfo.pTagCtxList);
      tfree(pRuntimeEnv->resultInfo[i].interResultBuf);
    }
1547

1548 1549 1550
    tfree(pRuntimeEnv->resultInfo);
    tfree(pRuntimeEnv->pCtx);
  }
1551

1552
  taosDestoryFillInfo(pRuntimeEnv->pFillInfo);
1553

H
hjxilinx 已提交
1554
  destroyResultBuf(pRuntimeEnv->pResultBuf, pQInfo);
1555
  tsdbCleanupQueryHandle(pRuntimeEnv->pQueryHandle);
1556
  tsdbCleanupQueryHandle(pRuntimeEnv->pSecQueryHandle);
1557

1558 1559 1560
  pRuntimeEnv->pTSBuf = tsBufDestory(pRuntimeEnv->pTSBuf);
}

1561 1562
static bool isQueryKilled(SQInfo *pQInfo) {
  return (pQInfo->code == TSDB_CODE_QUERY_CANCELLED);
1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
#if 0
  /*
   * check if the queried meter is going to be deleted.
   * if it will be deleted soon, stop current query ASAP.
   */
  SMeterObj *pMeterObj = pQInfo->pObj;
  if (vnodeIsMeterState(pMeterObj, TSDB_METER_STATE_DROPPING)) {
    pQInfo->killed = 1;
    return true;
  }
  
  return (pQInfo->killed == 1);
#endif
}

1578
static void setQueryKilled(SQInfo *pQInfo) { pQInfo->code = TSDB_CODE_QUERY_CANCELLED; }
H
hjxilinx 已提交
1579

H
hjxilinx 已提交
1580
static bool isFixedOutputQuery(SQuery *pQuery) {
1581 1582 1583
  if (pQuery->intervalTime != 0) {
    return false;
  }
1584

1585 1586 1587 1588
  // Note:top/bottom query is fixed output query
  if (isTopBottomQuery(pQuery) || isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
    return true;
  }
1589

1590
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1591
    SSqlFuncMsg *pExprMsg = &pQuery->pSelectExpr[i].base;
1592

1593 1594
    // ignore the ts_comp function
    if (i == 0 && pExprMsg->functionId == TSDB_FUNC_PRJ && pExprMsg->numOfParams == 1 &&
1595
        pExprMsg->colInfo.colIndex == PRIMARYKEY_TIMESTAMP_COL_INDEX) {
1596 1597
      continue;
    }
1598

1599 1600 1601
    if (pExprMsg->functionId == TSDB_FUNC_TS || pExprMsg->functionId == TSDB_FUNC_TS_DUMMY) {
      continue;
    }
1602

1603 1604 1605 1606
    if (!IS_MULTIOUTPUT(aAggs[pExprMsg->functionId].nStatus)) {
      return true;
    }
  }
1607

1608 1609 1610
  return false;
}

H
hjxilinx 已提交
1611
static bool isPointInterpoQuery(SQuery *pQuery) {
1612
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1613
    int32_t functionID = pQuery->pSelectExpr[i].base.functionId;
1614 1615 1616 1617
    if (functionID == TSDB_FUNC_INTERP || functionID == TSDB_FUNC_LAST_ROW) {
      return true;
    }
  }
1618

1619 1620 1621 1622
  return false;
}

// TODO REFACTOR:MERGE WITH CLIENT-SIDE FUNCTION
H
hjxilinx 已提交
1623
static bool isSumAvgRateQuery(SQuery *pQuery) {
1624
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1625
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
1626 1627 1628
    if (functionId == TSDB_FUNC_TS) {
      continue;
    }
1629

1630 1631 1632 1633 1634
    if (functionId == TSDB_FUNC_SUM_RATE || functionId == TSDB_FUNC_SUM_IRATE || functionId == TSDB_FUNC_AVG_RATE ||
        functionId == TSDB_FUNC_AVG_IRATE) {
      return true;
    }
  }
1635

1636 1637 1638
  return false;
}

H
hjxilinx 已提交
1639
static bool isFirstLastRowQuery(SQuery *pQuery) {
1640
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1641
    int32_t functionID = pQuery->pSelectExpr[i].base.functionId;
1642 1643 1644 1645
    if (functionID == TSDB_FUNC_LAST_ROW) {
      return true;
    }
  }
1646

1647 1648 1649
  return false;
}

H
hjxilinx 已提交
1650
static UNUSED_FUNC bool notHasQueryTimeRange(SQuery *pQuery) {
1651
  return (pQuery->window.skey == 0 && pQuery->window.ekey == INT64_MAX && QUERY_IS_ASC_QUERY(pQuery)) ||
1652
         (pQuery->window.skey == INT64_MAX && pQuery->window.ekey == 0 && (!QUERY_IS_ASC_QUERY(pQuery)));
1653 1654
}

H
hjxilinx 已提交
1655
static bool needReverseScan(SQuery *pQuery) {
1656
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1657
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
1658 1659 1660
    if (functionId == TSDB_FUNC_TS || functionId == TSDB_FUNC_TS_DUMMY || functionId == TSDB_FUNC_TAG) {
      continue;
    }
1661

1662 1663 1664 1665 1666
    if (((functionId == TSDB_FUNC_LAST || functionId == TSDB_FUNC_LAST_DST) && QUERY_IS_ASC_QUERY(pQuery)) ||
        ((functionId == TSDB_FUNC_FIRST || functionId == TSDB_FUNC_FIRST_DST) && !QUERY_IS_ASC_QUERY(pQuery))) {
      return true;
    }
  }
1667

1668 1669
  return false;
}
H
hjxilinx 已提交
1670 1671 1672 1673

static bool onlyQueryTags(SQuery* pQuery) {
  for(int32_t i = 0; i < pQuery->numOfOutput; ++i) {
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
1674
    if (functionId != TSDB_FUNC_TAGPRJ && functionId != TSDB_FUNC_TID_TAG) {
H
hjxilinx 已提交
1675 1676 1677 1678 1679 1680 1681
      return false;
    }
  }
  
  return true;
}

1682 1683
/////////////////////////////////////////////////////////////////////////////////////////////

1684 1685
void getAlignQueryTimeWindow(SQuery *pQuery, int64_t key, int64_t keyFirst, int64_t keyLast, int64_t *realSkey,
                             int64_t *realEkey, STimeWindow *win) {
1686
  assert(key >= keyFirst && key <= keyLast && pQuery->slidingTime <= pQuery->intervalTime);
1687

1688
  win->skey = taosGetIntervalStartTimestamp(key, pQuery->slidingTime, pQuery->slidingTimeUnit, pQuery->precision);
1689

1690 1691 1692 1693 1694 1695
  if (keyFirst > (INT64_MAX - pQuery->intervalTime)) {
    /*
     * if the realSkey > INT64_MAX - pQuery->intervalTime, the query duration between
     * realSkey and realEkey must be less than one interval.Therefore, no need to adjust the query ranges.
     */
    assert(keyLast - keyFirst < pQuery->intervalTime);
1696

1697 1698
    *realSkey = keyFirst;
    *realEkey = keyLast;
1699

1700 1701 1702
    win->ekey = INT64_MAX;
    return;
  }
1703

1704
  win->ekey = win->skey + pQuery->intervalTime - 1;
1705

1706 1707 1708 1709 1710
  if (win->skey < keyFirst) {
    *realSkey = keyFirst;
  } else {
    *realSkey = win->skey;
  }
1711

1712 1713 1714 1715 1716 1717 1718
  if (win->ekey < keyLast) {
    *realEkey = win->ekey;
  } else {
    *realEkey = keyLast;
  }
}

1719
static UNUSED_FUNC bool doGetQueryPos(TSKEY key, SQInfo *pQInfo, SPointInterpoSupporter *pPointInterpSupporter) {
1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739
#if 0
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;
  SMeterObj *       pMeterObj = pRuntimeEnv->pTabObj;
  
  /* key in query range. If not, no qualified in disk file */
  if (key != -1 && key <= pQuery->window.ekey) {
    if (isPointInterpoQuery(pQuery)) { /* no qualified data in this query range */
      return getNeighborPoints(pQInfo, pMeterObj, pPointInterpSupporter);
    } else {
      return true;
    }
  } else {  // key > pQuery->window.ekey, abort for normal query, continue for interp query
    if (isPointInterpoQuery(pQuery)) {
      return getNeighborPoints(pQInfo, pMeterObj, pPointInterpSupporter);
    } else {
      return false;
    }
  }
#endif
1740
  return true;
1741 1742
}

1743
static UNUSED_FUNC bool doSetDataInfo(SQInfo *pQInfo, SPointInterpoSupporter *pPointInterpSupporter, void *pMeterObj,
1744
                                      TSKEY nextKey) {
1745 1746
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;
1747

1748 1749 1750 1751 1752 1753
  if (isFirstLastRowQuery(pQuery)) {
    /*
     * if the pQuery->window.skey != pQuery->window.ekey for last_row query,
     * the query range is existed, so set them both the value of nextKey
     */
    if (pQuery->window.skey != pQuery->window.ekey) {
1754 1755 1756
      assert(pQuery->window.skey >= pQuery->window.ekey && !QUERY_IS_ASC_QUERY(pQuery) &&
             nextKey >= pQuery->window.ekey && nextKey <= pQuery->window.skey);

1757 1758 1759
      pQuery->window.skey = nextKey;
      pQuery->window.ekey = nextKey;
    }
1760

1761 1762 1763 1764 1765 1766 1767 1768
    return getNeighborPoints(pQInfo, pMeterObj, pPointInterpSupporter);
  } else {
    return true;
  }
}

static void setScanLimitationByResultBuffer(SQuery *pQuery) {
  if (isTopBottomQuery(pQuery)) {
1769
    pQuery->checkBuffer = 0;
1770
  } else if (isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
1771
    pQuery->checkBuffer = 0;
1772 1773
  } else {
    bool hasMultioutput = false;
1774
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1775
      SSqlFuncMsg *pExprMsg = &pQuery->pSelectExpr[i].base;
1776 1777 1778
      if (pExprMsg->functionId == TSDB_FUNC_TS || pExprMsg->functionId == TSDB_FUNC_TS_DUMMY) {
        continue;
      }
1779

1780 1781 1782 1783 1784
      hasMultioutput = IS_MULTIOUTPUT(aAggs[pExprMsg->functionId].nStatus);
      if (!hasMultioutput) {
        break;
      }
    }
1785

1786
    pQuery->checkBuffer = hasMultioutput ? 1 : 0;
1787 1788 1789 1790 1791 1792 1793 1794 1795
  }
}

/*
 * todo add more parameters to check soon..
 */
bool vnodeParametersSafetyCheck(SQuery *pQuery) {
  // load data column information is incorrect
  for (int32_t i = 0; i < pQuery->numOfCols - 1; ++i) {
1796
    if (pQuery->colList[i].colId == pQuery->colList[i + 1].colId) {
S
slguan 已提交
1797
      qError("QInfo:%p invalid data load column for query", GET_QINFO_ADDR(pQuery));
1798 1799 1800 1801 1802 1803 1804 1805 1806
      return false;
    }
  }
  return true;
}

// todo ignore the avg/sum/min/max/count/stddev/top/bottom functions, of which
// the scan order is not matter
static bool onlyOneQueryType(SQuery *pQuery, int32_t functId, int32_t functIdDst) {
1807
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1808
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
1809

1810 1811 1812 1813
    if (functionId == TSDB_FUNC_TS || functionId == TSDB_FUNC_TS_DUMMY || functionId == TSDB_FUNC_TAG ||
        functionId == TSDB_FUNC_TAG_DUMMY) {
      continue;
    }
1814

1815 1816 1817 1818
    if (functionId != functId && functionId != functIdDst) {
      return false;
    }
  }
1819

1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
  return true;
}

static bool onlyFirstQuery(SQuery *pQuery) { return onlyOneQueryType(pQuery, TSDB_FUNC_FIRST, TSDB_FUNC_FIRST_DST); }

static bool onlyLastQuery(SQuery *pQuery) { return onlyOneQueryType(pQuery, TSDB_FUNC_LAST, TSDB_FUNC_LAST_DST); }

static void changeExecuteScanOrder(SQuery *pQuery, bool metricQuery) {
  // in case of point-interpolation query, use asc order scan
  char msg[] = "QInfo:%p scan order changed for %s query, old:%d, new:%d, qrange exchanged, old qrange:%" PRId64
               "-%" PRId64 ", new qrange:%" PRId64 "-%" PRId64;
1831

1832 1833 1834
  // todo handle the case the the order irrelevant query type mixed up with order critical query type
  // descending order query for last_row query
  if (isFirstLastRowQuery(pQuery)) {
S
slguan 已提交
1835
    qTrace("QInfo:%p scan order changed for last_row query, old:%d, new:%d", GET_QINFO_ADDR(pQuery),
1836
           pQuery->order.order, TSDB_ORDER_DESC);
1837

1838
    pQuery->order.order = TSDB_ORDER_DESC;
1839

1840 1841
    int64_t skey = MIN(pQuery->window.skey, pQuery->window.ekey);
    int64_t ekey = MAX(pQuery->window.skey, pQuery->window.ekey);
1842

1843 1844
    pQuery->window.skey = ekey;
    pQuery->window.ekey = skey;
1845

1846 1847
    return;
  }
1848

1849 1850
  if (isPointInterpoQuery(pQuery) && pQuery->intervalTime == 0) {
    if (!QUERY_IS_ASC_QUERY(pQuery)) {
S
slguan 已提交
1851
      qTrace(msg, GET_QINFO_ADDR(pQuery), "interp", pQuery->order.order, TSDB_ORDER_ASC, pQuery->window.skey,
1852
             pQuery->window.ekey, pQuery->window.ekey, pQuery->window.skey);
1853 1854
      SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);
    }
1855

1856
    pQuery->order.order = TSDB_ORDER_ASC;
1857 1858
    return;
  }
1859

1860 1861 1862
  if (pQuery->intervalTime == 0) {
    if (onlyFirstQuery(pQuery)) {
      if (!QUERY_IS_ASC_QUERY(pQuery)) {
S
slguan 已提交
1863
        qTrace(msg, GET_QINFO_ADDR(pQuery), "only-first", pQuery->order.order, TSDB_ORDER_ASC, pQuery->window.skey,
1864 1865
               pQuery->window.ekey, pQuery->window.ekey, pQuery->window.skey);

1866 1867
        SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);
      }
1868

1869
      pQuery->order.order = TSDB_ORDER_ASC;
1870 1871
    } else if (onlyLastQuery(pQuery)) {
      if (QUERY_IS_ASC_QUERY(pQuery)) {
S
slguan 已提交
1872
        qTrace(msg, GET_QINFO_ADDR(pQuery), "only-last", pQuery->order.order, TSDB_ORDER_DESC, pQuery->window.skey,
1873 1874
               pQuery->window.ekey, pQuery->window.ekey, pQuery->window.skey);

1875 1876
        SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);
      }
1877

1878
      pQuery->order.order = TSDB_ORDER_DESC;
1879
    }
1880

1881 1882 1883 1884
  } else {  // interval query
    if (metricQuery) {
      if (onlyFirstQuery(pQuery)) {
        if (!QUERY_IS_ASC_QUERY(pQuery)) {
S
slguan 已提交
1885
          qTrace(msg, GET_QINFO_ADDR(pQuery), "only-first stable", pQuery->order.order, TSDB_ORDER_ASC,
1886 1887
                 pQuery->window.skey, pQuery->window.ekey, pQuery->window.ekey, pQuery->window.skey);

1888 1889
          SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);
        }
1890

1891
        pQuery->order.order = TSDB_ORDER_ASC;
1892 1893
      } else if (onlyLastQuery(pQuery)) {
        if (QUERY_IS_ASC_QUERY(pQuery)) {
S
slguan 已提交
1894
          qTrace(msg, GET_QINFO_ADDR(pQuery), "only-last stable", pQuery->order.order, TSDB_ORDER_DESC,
1895 1896
                 pQuery->window.skey, pQuery->window.ekey, pQuery->window.ekey, pQuery->window.skey);

1897 1898
          SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);
        }
1899

1900
        pQuery->order.order = TSDB_ORDER_DESC;
1901 1902 1903 1904 1905
      }
    }
  }
}

H
hjxilinx 已提交
1906
static UNUSED_FUNC void doSetInterpVal(SQLFunctionCtx *pCtx, TSKEY ts, int16_t type, int32_t index, char *data) {
1907
  assert(pCtx->param[index].pz == NULL);
1908

1909 1910
  int32_t len = 0;
  size_t  t = 0;
1911

1912 1913
  if (type == TSDB_DATA_TYPE_BINARY) {
    t = strlen(data);
1914

1915 1916 1917 1918
    len = t + 1 + TSDB_KEYSIZE;
    pCtx->param[index].pz = calloc(1, len);
  } else if (type == TSDB_DATA_TYPE_NCHAR) {
    t = wcslen((const wchar_t *)data);
1919

1920 1921 1922 1923 1924 1925
    len = (t + 1) * TSDB_NCHAR_SIZE + TSDB_KEYSIZE;
    pCtx->param[index].pz = calloc(1, len);
  } else {
    len = TSDB_KEYSIZE * 2;
    pCtx->param[index].pz = malloc(len);
  }
1926

1927
  pCtx->param[index].nType = TSDB_DATA_TYPE_BINARY;
1928

1929 1930 1931
  char *z = pCtx->param[index].pz;
  *(TSKEY *)z = ts;
  z += TSDB_KEYSIZE;
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
  switch (type) {
    case TSDB_DATA_TYPE_FLOAT:
      *(double *)z = GET_FLOAT_VAL(data);
      break;
    case TSDB_DATA_TYPE_DOUBLE:
      *(double *)z = GET_DOUBLE_VAL(data);
      break;
    case TSDB_DATA_TYPE_INT:
    case TSDB_DATA_TYPE_BOOL:
    case TSDB_DATA_TYPE_BIGINT:
    case TSDB_DATA_TYPE_TINYINT:
    case TSDB_DATA_TYPE_SMALLINT:
    case TSDB_DATA_TYPE_TIMESTAMP:
      *(int64_t *)z = GET_INT64_VAL(data);
      break;
    case TSDB_DATA_TYPE_BINARY:
      strncpy(z, data, t);
      break;
    case TSDB_DATA_TYPE_NCHAR: {
      wcsncpy((wchar_t *)z, (const wchar_t *)data, t);
    } break;
    default:
      assert(0);
  }
1957

1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
  pCtx->param[index].nLen = len;
}

/**
 * param[1]: default value/previous value of specified timestamp
 * param[2]: next value of specified timestamp
 * param[3]: denotes if the result is a precious result or interpolation results
 *
 * @param pQInfo
 * @param pQInfo
 * @param pInterpoRaw
 */
void pointInterpSupporterSetData(SQInfo *pQInfo, SPointInterpoSupporter *pPointInterpSupport) {
H
hjxilinx 已提交
1971
#if 0
1972
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
1973 1974
  SQuery *          pQuery = pRuntimeEnv->pQuery;

1975 1976 1977 1978
  // not point interpolation query, abort
  if (!isPointInterpoQuery(pQuery)) {
    return;
  }
1979

1980
  int32_t count = 1;
H
hjxilinx 已提交
1981
  TSKEY key = *(TSKEY *)pPointInterpSupport->next[0];
1982

1983 1984
  if (key == pQuery->window.skey) {
    // the queried timestamp has value, return it directly without interpolation
1985
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1986
      tVariantCreateFromBinary(&pRuntimeEnv->pCtx[i].param[3], (char *)&count, sizeof(count), TSDB_DATA_TYPE_INT);
1987

1988 1989 1990 1991 1992 1993
      pRuntimeEnv->pCtx[i].param[0].i64Key = key;
      pRuntimeEnv->pCtx[i].param[0].nType = TSDB_DATA_TYPE_BIGINT;
    }
  } else {
    // set the direct previous(next) point for process
    count = 2;
1994

1995
    if (pQuery->fillType == TSDB_FILL_SET_VALUE) {
1996
      for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1997
        SQLFunctionCtx *pCtx = &pRuntimeEnv->pCtx[i];
1998

1999 2000 2001 2002
        // only the function of interp needs the corresponding information
        if (pCtx->functionId != TSDB_FUNC_INTERP) {
          continue;
        }
2003

2004
        pCtx->numOfParams = 4;
2005

2006 2007
        SInterpInfo *pInterpInfo = (SInterpInfo *)pRuntimeEnv->pCtx[i].aOutputBuf;
        pInterpInfo->pInterpDetail = calloc(1, sizeof(SInterpInfoDetail));
2008

2009
        SInterpInfoDetail *pInterpDetail = pInterpInfo->pInterpDetail;
2010

2011
        // for primary timestamp column, set the flag
2012
        if (pQuery->pSelectExpr[i].base.colInfo.colId == PRIMARYKEY_TIMESTAMP_COL_INDEX) {
2013 2014
          pInterpDetail->primaryCol = 1;
        }
2015

2016
        tVariantCreateFromBinary(&pCtx->param[3], (char *)&count, sizeof(count), TSDB_DATA_TYPE_INT);
2017

2018 2019 2020 2021 2022
        if (isNull((char *)&pQuery->defaultVal[i], pCtx->inputType)) {
          pCtx->param[1].nType = TSDB_DATA_TYPE_NULL;
        } else {
          tVariantCreateFromBinary(&pCtx->param[1], (char *)&pQuery->defaultVal[i], pCtx->inputBytes, pCtx->inputType);
        }
2023

2024
        pInterpDetail->ts = pQuery->window.skey;
2025
        pInterpDetail->type = pQuery->fillType;
2026 2027 2028 2029
      }
    } else {
      TSKEY prevKey = *(TSKEY *)pPointInterpSupport->pPrevPoint[0];
      TSKEY nextKey = *(TSKEY *)pPointInterpSupport->pNextPoint[0];
2030

2031
      for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
2032
        SQLFunctionCtx *pCtx = &pRuntimeEnv->pCtx[i];
2033

2034
        // tag column does not need the interp environment
2035
        if (pQuery->pSelectExpr[i].base.functionId == TSDB_FUNC_TAG) {
2036 2037
          continue;
        }
2038

2039
        int32_t      colInBuf = 0;  // pQuery->pSelectExpr[i].base.colInfo.colIdxInBuf;
2040
        SInterpInfo *pInterpInfo = (SInterpInfo *)pRuntimeEnv->pCtx[i].aOutputBuf;
2041

2042 2043
        pInterpInfo->pInterpDetail = calloc(1, sizeof(SInterpInfoDetail));
        SInterpInfoDetail *pInterpDetail = pInterpInfo->pInterpDetail;
2044 2045

        //        int32_t type = GET_COLUMN_TYPE(pQuery, i);
2046 2047
        int32_t type = 0;
        assert(0);
2048

2049
        // for primary timestamp column, set the flag
2050
        if (pQuery->pSelectExpr[i].base.colInfo.colId == PRIMARYKEY_TIMESTAMP_COL_INDEX) {
2051 2052 2053 2054 2055
          pInterpDetail->primaryCol = 1;
        } else {
          doSetInterpVal(pCtx, prevKey, type, 1, pPointInterpSupport->pPrevPoint[colInBuf]);
          doSetInterpVal(pCtx, nextKey, type, 2, pPointInterpSupport->pNextPoint[colInBuf]);
        }
2056

2057
        tVariantCreateFromBinary(&pRuntimeEnv->pCtx[i].param[3], (char *)&count, sizeof(count), TSDB_DATA_TYPE_INT);
2058

2059
        pInterpDetail->ts = pQInfo->runtimeEnv.pQuery->window.skey;
2060
        pInterpDetail->type = pQuery->fillType;
2061 2062 2063
      }
    }
  }
H
hjxilinx 已提交
2064
#endif
2065 2066 2067
}

void pointInterpSupporterInit(SQuery *pQuery, SPointInterpoSupporter *pInterpoSupport) {
H
hjxilinx 已提交
2068
#if 0
2069 2070 2071
  if (isPointInterpoQuery(pQuery)) {
    pInterpoSupport->pPrevPoint = malloc(pQuery->numOfCols * POINTER_BYTES);
    pInterpoSupport->pNextPoint = malloc(pQuery->numOfCols * POINTER_BYTES);
2072

2073
    pInterpoSupport->numOfCols = pQuery->numOfCols;
2074

2075 2076 2077
    /* get appropriated size for one row data source*/
    int32_t len = 0;
    for (int32_t i = 0; i < pQuery->numOfCols; ++i) {
2078
      len += pQuery->colList[i].bytes;
2079
    }
2080 2081 2082

    //    assert(PRIMARY_TSCOL_LOADED(pQuery));

2083 2084
    void *prev = calloc(1, len);
    void *next = calloc(1, len);
2085

2086
    int32_t offset = 0;
2087

2088 2089 2090
    for (int32_t i = 0; i < pQuery->numOfCols; ++i) {
      pInterpoSupport->pPrevPoint[i] = prev + offset;
      pInterpoSupport->pNextPoint[i] = next + offset;
2091

2092
      offset += pQuery->colList[i].bytes;
2093 2094
    }
  }
H
hjxilinx 已提交
2095
#endif
2096 2097 2098
}

void pointInterpSupporterDestroy(SPointInterpoSupporter *pPointInterpSupport) {
H
hjxilinx 已提交
2099
#if 0
2100 2101 2102
  if (pPointInterpSupport->numOfCols <= 0 || pPointInterpSupport->pPrevPoint == NULL) {
    return;
  }
2103

2104 2105
  tfree(pPointInterpSupport->pPrevPoint[0]);
  tfree(pPointInterpSupport->pNextPoint[0]);
2106

2107 2108
  tfree(pPointInterpSupport->pPrevPoint);
  tfree(pPointInterpSupport->pNextPoint);
2109

2110
  pPointInterpSupport->numOfCols = 0;
H
hjxilinx 已提交
2111
#endif
2112 2113 2114 2115 2116
}

static int32_t getInitialPageNum(SQInfo *pQInfo) {
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
  int32_t INITIAL_RESULT_ROWS_VALUE = 16;
2117

2118
  int32_t num = 0;
2119

2120 2121 2122
  if (isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
    num = 128;
  } else if (isIntervalQuery(pQuery)) {  // time window query, allocate one page for each table
2123
    size_t s = pQInfo->groupInfo.numOfTables;
2124
    num = MAX(s, INITIAL_RESULT_ROWS_VALUE);
2125 2126
  } else {    // for super table query, one page for each subset
    num = 1;  // pQInfo->pSidSet->numOfSubSet;
2127
  }
2128

2129 2130 2131 2132 2133 2134
  assert(num > 0);
  return num;
}

static int32_t getRowParamForMultiRowsOutput(SQuery *pQuery, bool isSTableQuery) {
  int32_t rowparam = 1;
2135

2136
  if (isTopBottomQuery(pQuery) && (!isSTableQuery)) {
2137
    rowparam = pQuery->pSelectExpr[1].base.arg->argValue.i64;
2138
  }
2139

2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
  return rowparam;
}

static int32_t getNumOfRowsInResultPage(SQuery *pQuery, bool isSTableQuery) {
  int32_t rowSize = pQuery->rowSize * getRowParamForMultiRowsOutput(pQuery, isSTableQuery);
  return (DEFAULT_INTERN_BUF_SIZE - sizeof(tFilePage)) / rowSize;
}

char *getPosInResultPage(SQueryRuntimeEnv *pRuntimeEnv, int32_t columnIndex, SWindowResult *pResult) {
  assert(pResult != NULL && pRuntimeEnv != NULL);
2150

2151 2152
  SQuery *   pQuery = pRuntimeEnv->pQuery;
  tFilePage *page = getResultBufferPageById(pRuntimeEnv->pResultBuf, pResult->pos.pageId);
2153

2154 2155
  int32_t numOfRows = getNumOfRowsInResultPage(pQuery, pRuntimeEnv->stableQuery);
  int32_t realRowId = pResult->pos.rowId * getRowParamForMultiRowsOutput(pQuery, pRuntimeEnv->stableQuery);
2156

2157
  return ((char *)page->data) + pRuntimeEnv->offset[columnIndex] * numOfRows +
2158
         pQuery->pSelectExpr[columnIndex].bytes * realRowId;
2159 2160 2161 2162 2163 2164
}

/**
 * decrease the refcount for each table involved in this query
 * @param pQInfo
 */
2165
UNUSED_FUNC void vnodeDecMeterRefcnt(SQInfo *pQInfo) {
2166
  if (pQInfo != NULL) {
2167
    //    assert(taosHashGetSize(pQInfo->groupInfo) >= 1);
2168 2169 2170
  }

#if 0
2171
  if (pQInfo == NULL || pQInfo->groupInfo.numOfTables == 1) {
2172
    atomic_fetch_sub_32(&pQInfo->pObj->numOfQueries, 1);
S
slguan 已提交
2173
    qTrace("QInfo:%p vid:%d sid:%d meterId:%s, query is over, numOfQueries:%d", pQInfo, pQInfo->pObj->vnode,
2174 2175 2176
           pQInfo->pObj->sid, pQInfo->pObj->meterId, pQInfo->pObj->numOfQueries);
  } else {
    int32_t num = 0;
2177 2178
    for (int32_t i = 0; i < pQInfo->groupInfo.numOfTables; ++i) {
      SMeterObj *pMeter = getMeterObj(pQInfo->groupInfo, pQInfo->pSidSet->pTableIdList[i]->sid);
2179 2180 2181
      atomic_fetch_sub_32(&(pMeter->numOfQueries), 1);
      
      if (pMeter->numOfQueries > 0) {
S
slguan 已提交
2182
        qTrace("QInfo:%p vid:%d sid:%d meterId:%s, query is over, numOfQueries:%d", pQInfo, pMeter->vnode, pMeter->sid,
2183 2184 2185 2186 2187 2188 2189 2190 2191
               pMeter->meterId, pMeter->numOfQueries);
        num++;
      }
    }
    
    /*
     * in order to reduce log output, for all meters of which numOfQueries count are 0,
     * we do not output corresponding information
     */
2192
    num = pQInfo->groupInfo.numOfTables - num;
S
slguan 已提交
2193
    qTrace("QInfo:%p metric query is over, dec query ref for %d meters, numOfQueries on %d meters are 0", pQInfo,
2194
           pQInfo->groupInfo.numOfTables, num);
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
  }
#endif
}

static bool needToLoadDataBlock(SQuery *pQuery, SDataStatis *pDataStatis, SQLFunctionCtx *pCtx,
                                int32_t numOfTotalPoints) {
  if (pDataStatis == NULL) {
    return true;
  }

#if 0
  for (int32_t k = 0; k < pQuery->numOfFilterCols; ++k) {
    SSingleColumnFilterInfo *pFilterInfo = &pQuery->pFilterInfo[k];
2208
    int32_t                  colIndex = pFilterInfo->info.colIndex;
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
    
    // this column not valid in current data block
    if (colIndex < 0 || pDataStatis[colIndex].colId != pFilterInfo->info.data.colId) {
      continue;
    }
    
    // not support pre-filter operation on binary/nchar data type
    if (!vnodeSupportPrefilter(pFilterInfo->info.data.type)) {
      continue;
    }
    
    // all points in current column are NULL, no need to check its boundary value
    if (pDataStatis[colIndex].numOfNull == numOfTotalPoints) {
      continue;
    }
    
    if (pFilterInfo->info.info.type == TSDB_DATA_TYPE_FLOAT) {
      float minval = *(double *)(&pDataStatis[colIndex].min);
      float maxval = *(double *)(&pDataStatis[colIndex].max);
      
      for (int32_t i = 0; i < pFilterInfo->numOfFilters; ++i) {
        if (pFilterInfo->pFilters[i].fp(&pFilterInfo->pFilters[i], (char *)&minval, (char *)&maxval)) {
          return true;
        }
      }
    } else {
      for (int32_t i = 0; i < pFilterInfo->numOfFilters; ++i) {
        if (pFilterInfo->pFilters[i].fp(&pFilterInfo->pFilters[i], (char *)&pDataStatis[colIndex].min,
                                        (char *)&pDataStatis[colIndex].max)) {
          return true;
        }
      }
    }
  }
  
  // todo disable this opt code block temporarily
2245
  //  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
2246
  //    int32_t functId = pQuery->pSelectExpr[i].base.functionId;
2247 2248 2249 2250
  //    if (functId == TSDB_FUNC_TOP || functId == TSDB_FUNC_BOTTOM) {
  //      return top_bot_datablock_filter(&pCtx[i], functId, (char *)&pField[i].min, (char *)&pField[i].max);
  //    }
  //  }
2251

2252 2253 2254 2255 2256 2257 2258
#endif
  return true;
}

// previous time window may not be of the same size of pQuery->intervalTime
static void getNextTimeWindow(SQuery *pQuery, STimeWindow *pTimeWindow) {
  int32_t factor = GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);
2259

2260 2261 2262 2263
  pTimeWindow->skey += (pQuery->slidingTime * factor);
  pTimeWindow->ekey = pTimeWindow->skey + (pQuery->intervalTime - 1);
}

H
hjxilinx 已提交
2264
SArray *loadDataBlockOnDemand(SQueryRuntimeEnv *pRuntimeEnv, void* pQueryHandle, SDataBlockInfo* pBlockInfo, SDataStatis **pStatis) {
2265
  SQuery *pQuery = pRuntimeEnv->pQuery;
2266 2267 2268 2269

  uint32_t r = 0;
  SArray * pDataBlock = NULL;

2270 2271 2272
  if (pQuery->numOfFilterCols > 0) {
    r = BLK_DATA_ALL_NEEDED;
  } else {
2273
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
2274 2275
      int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
      int32_t colId = pQuery->pSelectExpr[i].base.colInfo.colId;
2276
      r |= aAggs[functionId].dataReqFunc(&pRuntimeEnv->pCtx[i], pQuery->window.skey, pQuery->window.ekey, colId);
2277
    }
2278

2279 2280 2281 2282
    if (pRuntimeEnv->pTSBuf > 0 || isIntervalQuery(pQuery)) {
      r |= BLK_DATA_ALL_NEEDED;
    }
  }
2283

2284
  if (r == BLK_DATA_NO_NEEDED) {
H
hjxilinx 已提交
2285
    qTrace("QInfo:%p data block ignored, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_QINFO_ADDR(pRuntimeEnv),
2286
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
2287
  } else if (r == BLK_DATA_FILEDS_NEEDED) {
H
hjxilinx 已提交
2288
    if (tsdbRetrieveDataBlockStatisInfo(pQueryHandle, pStatis) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
2289
      //        return DISK_DATA_LOAD_FAILED;
2290
    }
2291

2292
    if (*pStatis == NULL) {
H
hjxilinx 已提交
2293
      pDataBlock = tsdbRetrieveDataBlock(pQueryHandle, NULL);
2294 2295 2296
    }
  } else {
    assert(r == BLK_DATA_ALL_NEEDED);
H
hjxilinx 已提交
2297
    if (tsdbRetrieveDataBlockStatisInfo(pQueryHandle, pStatis) != TSDB_CODE_SUCCESS) {
2298 2299
      //        return DISK_DATA_LOAD_FAILED;
    }
2300

2301 2302 2303 2304 2305
    /*
     * if this block is completed included in the query range, do more filter operation
     * filter the data block according to the value filter condition.
     * no need to load the data block, continue for next block
     */
2306
    if (!needToLoadDataBlock(pQuery, *pStatis, pRuntimeEnv->pCtx, pBlockInfo->rows)) {
2307
#if defined(_DEBUG_VIEW)
2308
      qTrace("QInfo:%p block discarded by per-filter", GET_QINFO_ADDR(pRuntimeEnv));
2309 2310 2311
#endif
      //        return DISK_DATA_DISCARDED;
    }
2312

H
hjxilinx 已提交
2313
    pDataBlock = tsdbRetrieveDataBlock(pQueryHandle, NULL);
2314
  }
2315

2316 2317 2318
  return pDataBlock;
}

H
hjxilinx 已提交
2319
int32_t binarySearchForKey(char *pValue, int num, TSKEY key, int order) {
2320 2321
  int32_t midPos = -1;
  int32_t numOfPoints;
2322

2323 2324 2325
  if (num <= 0) {
    return -1;
  }
2326

2327
  assert(order == TSDB_ORDER_ASC || order == TSDB_ORDER_DESC);
2328 2329

  TSKEY * keyList = (TSKEY *)pValue;
2330
  int32_t firstPos = 0;
2331
  int32_t lastPos = num - 1;
2332

2333
  if (order == TSDB_ORDER_DESC) {
H
hjxilinx 已提交
2334 2335 2336 2337 2338
    // find the first position which is smaller than the key
    while (1) {
      if (key >= keyList[lastPos]) return lastPos;
      if (key == keyList[firstPos]) return firstPos;
      if (key < keyList[firstPos]) return firstPos - 1;
2339

H
hjxilinx 已提交
2340 2341
      numOfPoints = lastPos - firstPos + 1;
      midPos = (numOfPoints >> 1) + firstPos;
2342

H
hjxilinx 已提交
2343 2344 2345 2346 2347 2348 2349 2350
      if (key < keyList[midPos]) {
        lastPos = midPos - 1;
      } else if (key > keyList[midPos]) {
        firstPos = midPos + 1;
      } else {
        break;
      }
    }
2351

H
hjxilinx 已提交
2352 2353 2354 2355 2356
  } else {
    // find the first position which is bigger than the key
    while (1) {
      if (key <= keyList[firstPos]) return firstPos;
      if (key == keyList[lastPos]) return lastPos;
2357

H
hjxilinx 已提交
2358 2359 2360 2361 2362 2363 2364
      if (key > keyList[lastPos]) {
        lastPos = lastPos + 1;
        if (lastPos >= num)
          return -1;
        else
          return lastPos;
      }
2365

H
hjxilinx 已提交
2366 2367
      numOfPoints = lastPos - firstPos + 1;
      midPos = (numOfPoints >> 1) + firstPos;
2368

H
hjxilinx 已提交
2369 2370 2371 2372 2373 2374 2375 2376 2377
      if (key < keyList[midPos]) {
        lastPos = midPos - 1;
      } else if (key > keyList[midPos]) {
        firstPos = midPos + 1;
      } else {
        break;
      }
    }
  }
2378

H
hjxilinx 已提交
2379 2380 2381
  return midPos;
}

2382 2383
static int64_t doScanAllDataBlocks(SQueryRuntimeEnv *pRuntimeEnv) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
2384
  STableQueryInfo* pTableQueryInfo = pQuery->current;
H
hjxilinx 已提交
2385
  
S
slguan 已提交
2386
  qTrace("QInfo:%p query start, qrange:%" PRId64 "-%" PRId64 ", lastkey:%" PRId64 ", order:%d",
H
hjxilinx 已提交
2387 2388
         GET_QINFO_ADDR(pRuntimeEnv), pTableQueryInfo->win.skey, pTableQueryInfo->win.ekey, pTableQueryInfo->lastKey,
         pQuery->order.order);
2389

2390
  TsdbQueryHandleT pQueryHandle = IS_MASTER_SCAN(pRuntimeEnv)? pRuntimeEnv->pQueryHandle : pRuntimeEnv->pSecQueryHandle;
2391
  while (tsdbNextDataBlock(pQueryHandle)) {
2392
    if (isQueryKilled(GET_QINFO_ADDR(pRuntimeEnv))) {
2393
      return 0;
2394
    }
2395

2396
    SDataBlockInfo blockInfo = tsdbRetrieveDataBlockInfo(pQueryHandle);
2397

2398
    // todo extract methods
H
Haojun Liao 已提交
2399
    if (isIntervalQuery(pQuery) && pRuntimeEnv->windowResInfo.prevSKey == TSKEY_INITIAL_VAL) {
2400
      TSKEY           skey1, ekey1;
H
hjLiao 已提交
2401
      STimeWindow     w = TSWINDOW_INITIALIZER;
2402 2403
      SWindowResInfo *pWindowResInfo = &pRuntimeEnv->windowResInfo;

2404
      if (QUERY_IS_ASC_QUERY(pQuery)) {
2405 2406
        getAlignQueryTimeWindow(pQuery, blockInfo.window.skey, blockInfo.window.skey, pQuery->window.ekey, &skey1,
                                &ekey1, &w);
2407 2408 2409 2410
        pWindowResInfo->startTime = w.skey;
        pWindowResInfo->prevSKey = w.skey;
      } else {
        // the start position of the first time window in the endpoint that spreads beyond the queried last timestamp
2411 2412
        getAlignQueryTimeWindow(pQuery, blockInfo.window.ekey, pQuery->window.ekey, blockInfo.window.ekey, &skey1,
                                &ekey1, &w);
2413

H
hjxilinx 已提交
2414
        pWindowResInfo->startTime = pQuery->window.skey;
2415 2416
        pWindowResInfo->prevSKey = w.skey;
      }
2417 2418 2419 2420
      
      if (pRuntimeEnv->pFillInfo != NULL) {
        pRuntimeEnv->pFillInfo->start = w.skey;
      }
2421
    }
2422

H
hjxilinx 已提交
2423
    // in case of prj/diff query, ensure the output buffer is sufficient to accommodate the results of current block
2424
    if (!isIntervalQuery(pQuery) && !isGroupbyNormalCol(pQuery->pGroupbyExpr) && !isFixedOutputQuery(pQuery)) {
2425 2426
      SResultRec *pRec = &pQuery->rec;

2427 2428 2429
      if (pQuery->rec.capacity - pQuery->rec.rows < blockInfo.rows) {
        int32_t remain = pRec->capacity - pRec->rows;
        int32_t newSize = pRec->capacity + (blockInfo.rows - remain);
2430

2431 2432
        for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
          int32_t bytes = pQuery->pSelectExpr[i].bytes;
2433

2434
          char *tmp = realloc(pQuery->sdata[i], bytes * newSize + sizeof(tFilePage));
2435
          if (tmp == NULL) {  // todo handle the oom
2436
            assert(0);
2437
          } else {
2438
            pQuery->sdata[i] = (tFilePage *)tmp;
2439
          }
2440

2441
          // set the pCtx output buffer position
2442
          pRuntimeEnv->pCtx[i].aOutputBuf = pQuery->sdata[i]->data + pRec->rows * bytes;
H
hjLiao 已提交
2443 2444 2445 2446 2447
          
          int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
          if (functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM || functionId == TSDB_FUNC_DIFF) {
            pRuntimeEnv->pCtx[i].ptsOutputBuf = pRuntimeEnv->pCtx[0].aOutputBuf;
          }
2448
        }
H
hjLiao 已提交
2449
  
2450
        qTrace("QInfo:%p realloc output buffer, new size: %d rows, old:%d, remain:%d", GET_QINFO_ADDR(pRuntimeEnv),
H
hjLiao 已提交
2451 2452
               newSize, pRec->capacity, newSize - pRec->rows);
        
2453 2454 2455
        pRec->capacity = newSize;
      }
    }
2456

2457
    SDataStatis *pStatis = NULL;
H
hjxilinx 已提交
2458
    SArray *     pDataBlock = loadDataBlockOnDemand(pRuntimeEnv, pQueryHandle, &blockInfo, &pStatis);
2459

2460
    pQuery->pos = QUERY_IS_ASC_QUERY(pQuery) ? 0 : blockInfo.rows - 1;
H
hjxilinx 已提交
2461
    int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, &blockInfo, pStatis, binarySearchForKey, pDataBlock);
2462

2463
    qTrace("QInfo:%p check data block, brange:%" PRId64 "-%" PRId64 ", rows:%d, numOfRes:%d", GET_QINFO_ADDR(pRuntimeEnv),
2464
           blockInfo.window.skey, blockInfo.window.ekey, blockInfo.rows, numOfRes);
2465

2466 2467
    // while the output buffer is full or limit/offset is applied, query may be paused here
    if (Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL | QUERY_COMPLETED)) {
H
hjxilinx 已提交
2468
      break;
2469 2470
    }
  }
2471

H
hjxilinx 已提交
2472
  // if the result buffer is not full, set the query complete
2473 2474 2475
  if (!Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL)) {
    setQueryStatus(pQuery, QUERY_COMPLETED);
  }
2476

2477
  if (isIntervalQuery(pQuery) && IS_MASTER_SCAN(pRuntimeEnv)) {
H
hjxilinx 已提交
2478
    if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
2479 2480
      int32_t step = QUERY_IS_ASC_QUERY(pQuery) ? QUERY_ASC_FORWARD_STEP : QUERY_DESC_FORWARD_STEP;

2481
      closeAllTimeWindow(&pRuntimeEnv->windowResInfo);
H
hjxilinx 已提交
2482
      removeRedundantWindow(&pRuntimeEnv->windowResInfo, pTableQueryInfo->lastKey - step, step);
H
hjxilinx 已提交
2483
      pRuntimeEnv->windowResInfo.curIndex = pRuntimeEnv->windowResInfo.size - 1;  // point to the last time window
2484 2485 2486 2487
    } else {
      assert(Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL));
    }
  }
2488

2489
  return 0;
2490 2491 2492 2493 2494 2495
}

/*
 * set tag value in SQLFunctionCtx
 * e.g.,tag information into input buffer
 */
H
hjxilinx 已提交
2496
static void doSetTagValueInParam(void *tsdb, STableId* pTableId, int32_t tagColId, tVariant *param) {
2497
  tVariantDestroy(param);
2498

2499
  char *  val = NULL;
2500
  int16_t bytes = 0;
2501
  int16_t type = 0;
2502

2503
  if (tagColId == TSDB_TBNAME_COLUMN_INDEX) {
H
hjxilinx 已提交
2504
    val = tsdbGetTableName(tsdb, pTableId, &bytes);
2505
    type = TSDB_DATA_TYPE_BINARY;
H
hjxilinx 已提交
2506
    tVariantCreateFromBinary(param, varDataVal(val), varDataLen(val), type);
2507
  } else {
H
hjxilinx 已提交
2508
    tsdbGetTableTagVal(tsdb, pTableId, tagColId, &type, &bytes, &val);
H
hjxilinx 已提交
2509 2510 2511 2512 2513 2514
    
    if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
      tVariantCreateFromBinary(param, varDataVal(val), varDataLen(val), type);
    } else {
      tVariantCreateFromBinary(param, val, bytes, type);
    }
2515
  }
2516 2517
}

H
hjxilinx 已提交
2518
void setTagVal(SQueryRuntimeEnv *pRuntimeEnv, STableId* pTableId, void *tsdb) {
2519
  SQuery *pQuery = pRuntimeEnv->pQuery;
2520

2521
  SSqlFuncMsg *pFuncMsg = &pQuery->pSelectExpr[0].base;
2522
  if (pQuery->numOfOutput == 1 && pFuncMsg->functionId == TSDB_FUNC_TS_COMP) {
2523
    assert(pFuncMsg->numOfParams == 1);
H
hjxilinx 已提交
2524
    doSetTagValueInParam(tsdb, pTableId, pFuncMsg->arg->argValue.i64, &pRuntimeEnv->pCtx[0].tag);
2525 2526
  } else {
    // set tag value, by which the results are aggregated.
2527
    for (int32_t idx = 0; idx < pQuery->numOfOutput; ++idx) {
2528
      SColIndex *pCol = &pQuery->pSelectExpr[idx].base.colInfo;
2529

2530
      // ts_comp column required the tag value for join filter
2531
      if (!TSDB_COL_IS_TAG(pCol->flag)) {
2532 2533
        continue;
      }
2534

2535
      // todo use tag column index to optimize performance
H
hjxilinx 已提交
2536
      doSetTagValueInParam(tsdb, pTableId, pCol->colId, &pRuntimeEnv->pCtx[idx].tag);
2537
    }
2538

2539
    // set the join tag for first column
2540
    if (pFuncMsg->functionId == TSDB_FUNC_TS && pFuncMsg->colInfo.colIndex == PRIMARYKEY_TIMESTAMP_COL_INDEX &&
2541 2542
        pRuntimeEnv->pTSBuf != NULL) {
      assert(pFuncMsg->numOfParams == 1);
2543 2544
      assert(0);  // to do fix me
      //      doSetTagValueInParam(pTagSchema, pFuncMsg->arg->argValue.i64, pMeterSidInfo, &pRuntimeEnv->pCtx[0].tag);
2545 2546 2547 2548 2549 2550 2551
    }
  }
}

static void doMerge(SQueryRuntimeEnv *pRuntimeEnv, int64_t timestamp, SWindowResult *pWindowRes, bool mergeFlag) {
  SQuery *        pQuery = pRuntimeEnv->pQuery;
  SQLFunctionCtx *pCtx = pRuntimeEnv->pCtx;
2552

2553
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
2554
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
2555 2556 2557
    if (!mergeFlag) {
      pCtx[i].aOutputBuf = pCtx[i].aOutputBuf + pCtx[i].outputBytes;
      pCtx[i].currentStage = FIRST_STAGE_MERGE;
2558

2559 2560 2561
      resetResultInfo(pCtx[i].resultInfo);
      aAggs[functionId].init(&pCtx[i]);
    }
2562

2563 2564 2565 2566 2567 2568
    pCtx[i].hasNull = true;
    pCtx[i].nStartQueryTimestamp = timestamp;
    pCtx[i].aInputElemBuf = getPosInResultPage(pRuntimeEnv, i, pWindowRes);
    //    pCtx[i].aInputElemBuf = ((char *)inputSrc->data) +
    //                            ((int32_t)pRuntimeEnv->offset[i] * pRuntimeEnv->numOfRowsPerPage) +
    //                            pCtx[i].outputBytes * inputIdx;
2569

2570 2571 2572 2573 2574 2575
    // in case of tag column, the tag information should be extracted from input buffer
    if (functionId == TSDB_FUNC_TAG_DUMMY || functionId == TSDB_FUNC_TAG) {
      tVariantDestroy(&pCtx[i].tag);
      tVariantCreateFromBinary(&pCtx[i].tag, pCtx[i].aInputElemBuf, pCtx[i].inputBytes, pCtx[i].inputType);
    }
  }
2576

2577
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
2578
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
2579 2580 2581
    if (functionId == TSDB_FUNC_TAG_DUMMY) {
      continue;
    }
2582

2583 2584 2585 2586
    aAggs[functionId].distMergeFunc(&pCtx[i]);
  }
}

2587
static UNUSED_FUNC void printBinaryData(int32_t functionId, char *data, int32_t srcDataType) {
2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655
  if (functionId == TSDB_FUNC_FIRST_DST || functionId == TSDB_FUNC_LAST_DST) {
    switch (srcDataType) {
      case TSDB_DATA_TYPE_BINARY:
        printf("%" PRId64 ",%s\t", *(TSKEY *)data, (data + TSDB_KEYSIZE + 1));
        break;
      case TSDB_DATA_TYPE_TINYINT:
      case TSDB_DATA_TYPE_BOOL:
        printf("%" PRId64 ",%d\t", *(TSKEY *)data, *(int8_t *)(data + TSDB_KEYSIZE + 1));
        break;
      case TSDB_DATA_TYPE_SMALLINT:
        printf("%" PRId64 ",%d\t", *(TSKEY *)data, *(int16_t *)(data + TSDB_KEYSIZE + 1));
        break;
      case TSDB_DATA_TYPE_BIGINT:
      case TSDB_DATA_TYPE_TIMESTAMP:
        printf("%" PRId64 ",%" PRId64 "\t", *(TSKEY *)data, *(TSKEY *)(data + TSDB_KEYSIZE + 1));
        break;
      case TSDB_DATA_TYPE_INT:
        printf("%" PRId64 ",%d\t", *(TSKEY *)data, *(int32_t *)(data + TSDB_KEYSIZE + 1));
        break;
      case TSDB_DATA_TYPE_FLOAT:
        printf("%" PRId64 ",%f\t", *(TSKEY *)data, *(float *)(data + TSDB_KEYSIZE + 1));
        break;
      case TSDB_DATA_TYPE_DOUBLE:
        printf("%" PRId64 ",%lf\t", *(TSKEY *)data, *(double *)(data + TSDB_KEYSIZE + 1));
        break;
    }
  } else if (functionId == TSDB_FUNC_AVG) {
    printf("%lf,%d\t", *(double *)data, *(int32_t *)(data + sizeof(double)));
  } else if (functionId == TSDB_FUNC_SPREAD) {
    printf("%lf,%lf\t", *(double *)data, *(double *)(data + sizeof(double)));
  } else if (functionId == TSDB_FUNC_TWA) {
    data += 1;
    printf("%lf,%" PRId64 ",%" PRId64 ",%" PRId64 "\t", *(double *)data, *(int64_t *)(data + 8),
           *(int64_t *)(data + 16), *(int64_t *)(data + 24));
  } else if (functionId == TSDB_FUNC_MIN || functionId == TSDB_FUNC_MAX) {
    switch (srcDataType) {
      case TSDB_DATA_TYPE_TINYINT:
      case TSDB_DATA_TYPE_BOOL:
        printf("%d\t", *(int8_t *)data);
        break;
      case TSDB_DATA_TYPE_SMALLINT:
        printf("%d\t", *(int16_t *)data);
        break;
      case TSDB_DATA_TYPE_BIGINT:
      case TSDB_DATA_TYPE_TIMESTAMP:
        printf("%" PRId64 "\t", *(int64_t *)data);
        break;
      case TSDB_DATA_TYPE_INT:
        printf("%d\t", *(int *)data);
        break;
      case TSDB_DATA_TYPE_FLOAT:
        printf("%f\t", *(float *)data);
        break;
      case TSDB_DATA_TYPE_DOUBLE:
        printf("%f\t", *(float *)data);
        break;
    }
  } else if (functionId == TSDB_FUNC_SUM) {
    if (srcDataType == TSDB_DATA_TYPE_FLOAT || srcDataType == TSDB_DATA_TYPE_DOUBLE) {
      printf("%lf\t", *(float *)data);
    } else {
      printf("%" PRId64 "\t", *(int64_t *)data);
    }
  } else {
    printf("%s\t", data);
  }
}

2656
void UNUSED_FUNC displayInterResult(tFilePage **pdata, SQueryRuntimeEnv* pRuntimeEnv, int32_t numOfRows) {
2657
  SQuery* pQuery = pRuntimeEnv->pQuery;
2658
  int32_t numOfCols = pQuery->numOfOutput;
2659 2660 2661 2662
  printf("super table query intermediate result, total:%d\n", numOfRows);
  
  for (int32_t j = 0; j < numOfRows; ++j) {
    for (int32_t i = 0; i < numOfCols; ++i) {
2663
      
2664
      switch (pQuery->pSelectExpr[i].type) {
2665
        case TSDB_DATA_TYPE_BINARY: {
2666 2667 2668 2669 2670
//          int32_t colIndex = pQuery->pSelectExpr[i].base.colInfo.colIndex;
          int32_t type = pQuery->pSelectExpr[i].type;
//          } else {
//            type = pMeterObj->schema[colIndex].type;
//          }
2671
          printBinaryData(pQuery->pSelectExpr[i].base.functionId, pdata[i]->data + pQuery->pSelectExpr[i].bytes * j,
2672 2673 2674 2675 2676
                          type);
          break;
        }
        case TSDB_DATA_TYPE_TIMESTAMP:
        case TSDB_DATA_TYPE_BIGINT:
2677
          printf("%" PRId64 "\t", *(int64_t *)(pdata[i]->data + pQuery->pSelectExpr[i].bytes * j));
2678 2679
          break;
        case TSDB_DATA_TYPE_INT:
2680
          printf("%d\t", *(int32_t *)(pdata[i]->data + pQuery->pSelectExpr[i].bytes * j));
2681 2682
          break;
        case TSDB_DATA_TYPE_FLOAT:
2683
          printf("%f\t", *(float *)(pdata[i]->data + pQuery->pSelectExpr[i].bytes * j));
2684 2685
          break;
        case TSDB_DATA_TYPE_DOUBLE:
2686
          printf("%lf\t", *(double *)(pdata[i]->data + pQuery->pSelectExpr[i].bytes * j));
2687 2688 2689 2690 2691 2692 2693 2694
          break;
      }
    }
    printf("\n");
  }
}

typedef struct SCompSupporter {
H
hjxilinx 已提交
2695 2696 2697
  STableQueryInfo **pTableQueryInfo;
  int32_t *         position;
  SQInfo *          pQInfo;
2698 2699 2700 2701 2702
} SCompSupporter;

int32_t tableResultComparFn(const void *pLeft, const void *pRight, void *param) {
  int32_t left = *(int32_t *)pLeft;
  int32_t right = *(int32_t *)pRight;
2703

2704 2705
  SCompSupporter *  supporter = (SCompSupporter *)param;
  SQueryRuntimeEnv *pRuntimeEnv = &supporter->pQInfo->runtimeEnv;
2706

2707 2708
  int32_t leftPos = supporter->position[left];
  int32_t rightPos = supporter->position[right];
2709

2710 2711 2712 2713
  /* left source is exhausted */
  if (leftPos == -1) {
    return 1;
  }
2714

2715 2716 2717 2718
  /* right source is exhausted*/
  if (rightPos == -1) {
    return -1;
  }
2719

H
hjxilinx 已提交
2720
  SWindowResInfo *pWindowResInfo1 = &supporter->pTableQueryInfo[left]->windowResInfo;
2721
  SWindowResult * pWindowRes1 = getWindowResult(pWindowResInfo1, leftPos);
2722

2723 2724
  char *b1 = getPosInResultPage(pRuntimeEnv, PRIMARYKEY_TIMESTAMP_COL_INDEX, pWindowRes1);
  TSKEY leftTimestamp = GET_INT64_VAL(b1);
2725

H
hjxilinx 已提交
2726
  SWindowResInfo *pWindowResInfo2 = &supporter->pTableQueryInfo[right]->windowResInfo;
2727
  SWindowResult * pWindowRes2 = getWindowResult(pWindowResInfo2, rightPos);
2728

2729 2730
  char *b2 = getPosInResultPage(pRuntimeEnv, PRIMARYKEY_TIMESTAMP_COL_INDEX, pWindowRes2);
  TSKEY rightTimestamp = GET_INT64_VAL(b2);
2731

2732 2733 2734
  if (leftTimestamp == rightTimestamp) {
    return 0;
  }
2735

2736 2737 2738
  return leftTimestamp > rightTimestamp ? 1 : -1;
}

2739
int32_t mergeIntoGroupResult(SQInfo *pQInfo) {
2740
  int64_t st = taosGetTimestampMs();
2741
  int32_t ret = TSDB_CODE_SUCCESS;
2742

2743
  int32_t numOfGroups = taosArrayGetSize(pQInfo->groupInfo.pGroupList);
2744

2745
  while (pQInfo->groupIndex < numOfGroups) {
2746
    SArray *group = taosArrayGetP(pQInfo->groupInfo.pGroupList, pQInfo->groupIndex);
2747
    ret = mergeIntoGroupResultImpl(pQInfo, group);
2748 2749 2750 2751
    if (ret < 0) {  // not enough disk space to save the data into disk
      return -1;
    }

2752
    pQInfo->groupIndex += 1;
2753 2754

    // this group generates at least one result, return results
2755 2756 2757
    if (ret > 0) {
      break;
    }
2758 2759

    assert(pQInfo->numOfGroupResultPages == 0);
H
hjxilinx 已提交
2760
    qTrace("QInfo:%p no result in group %d, continue", pQInfo, pQInfo->groupIndex - 1);
2761
  }
2762

2763 2764
  qTrace("QInfo:%p merge res data into group, index:%d, total group:%d, elapsed time:%lldms", pQInfo,
         pQInfo->groupIndex - 1, numOfGroups, taosGetTimestampMs() - st);
2765

2766 2767 2768 2769 2770 2771
  return TSDB_CODE_SUCCESS;
}

void copyResToQueryResultBuf(SQInfo *pQInfo, SQuery *pQuery) {
  if (pQInfo->offset == pQInfo->numOfGroupResultPages) {
    pQInfo->numOfGroupResultPages = 0;
2772

2773
    // current results of group has been sent to client, try next group
2774
    if (mergeIntoGroupResult(pQInfo) != TSDB_CODE_SUCCESS) {
2775 2776
      return;  // failed to save data in the disk
    }
2777

2778 2779 2780 2781 2782 2783
    // check if all results has been sent to client
    int32_t numOfGroup = taosArrayGetSize(pQInfo->groupInfo.pGroupList);
    if (pQInfo->numOfGroupResultPages == 0 && pQInfo->groupIndex == numOfGroup) {
      pQInfo->tableIndex = pQInfo->groupInfo.numOfTables;  // set query completed
      return;
    }
2784
  }
2785 2786

  SQueryRuntimeEnv *   pRuntimeEnv = &pQInfo->runtimeEnv;
2787
  SDiskbasedResultBuf *pResultBuf = pRuntimeEnv->pResultBuf;
2788

2789
  int32_t id = getGroupResultId(pQInfo->groupIndex - 1);
2790
  SIDList list = getDataBufPagesIdList(pResultBuf, pQInfo->offset + id);
2791

2792 2793 2794
  int32_t total = 0;
  for (int32_t i = 0; i < list.size; ++i) {
    tFilePage *pData = getResultBufferPageById(pResultBuf, list.pData[i]);
2795
    total += pData->num;
2796
  }
2797

2798
  int32_t rows = total;
2799

2800 2801 2802
  int32_t offset = 0;
  for (int32_t num = 0; num < list.size; ++num) {
    tFilePage *pData = getResultBufferPageById(pResultBuf, list.pData[num]);
2803

2804
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
2805
      int32_t bytes = pRuntimeEnv->pCtx[i].outputBytes;
2806
      char *  pDest = pQuery->sdata[i]->data;
2807

2808 2809
      memcpy(pDest + offset * bytes, pData->data + pRuntimeEnv->offset[i] * pData->num,
             bytes * pData->num);
2810
    }
2811

2812
    offset += pData->num;
2813
  }
2814

2815
  assert(pQuery->rec.rows == 0);
2816

2817
  pQuery->rec.rows += rows;
2818 2819 2820 2821 2822
  pQInfo->offset += 1;
}

int64_t getNumOfResultWindowRes(SQueryRuntimeEnv *pRuntimeEnv, SWindowResult *pWindowRes) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
2823

2824
  int64_t maxOutput = 0;
2825
  for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
2826
    int32_t functionId = pQuery->pSelectExpr[j].base.functionId;
2827

2828 2829 2830 2831 2832 2833 2834
    /*
     * ts, tag, tagprj function can not decide the output number of current query
     * the number of output result is decided by main output
     */
    if (functionId == TSDB_FUNC_TS || functionId == TSDB_FUNC_TAG || functionId == TSDB_FUNC_TAGPRJ) {
      continue;
    }
2835

2836 2837 2838 2839 2840
    SResultInfo *pResultInfo = &pWindowRes->resultInfo[j];
    if (pResultInfo != NULL && maxOutput < pResultInfo->numOfRes) {
      maxOutput = pResultInfo->numOfRes;
    }
  }
2841

2842 2843 2844
  return maxOutput;
}

2845
int32_t mergeIntoGroupResultImpl(SQInfo *pQInfo, SArray *pGroup) {
2846
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
2847
  SQuery *          pQuery = pRuntimeEnv->pQuery;
2848

2849
  size_t size = taosArrayGetSize(pGroup);
2850

2851
  tFilePage **buffer = (tFilePage **)pQuery->sdata;
2852 2853
  int32_t *   posList = calloc(size, sizeof(int32_t));

H
hjxilinx 已提交
2854
  STableQueryInfo **pTableList = malloc(POINTER_BYTES * size);
2855

2856
  // todo opt for the case of one table per group
2857
  int32_t numOfTables = 0;
2858
  for (int32_t i = 0; i < size; ++i) {
H
hjxilinx 已提交
2859 2860
    SGroupItem *item = taosArrayGet(pGroup, i);
    STableQueryInfo *pInfo = item->info;
2861

H
hjxilinx 已提交
2862 2863
    SIDList list = getDataBufPagesIdList(pRuntimeEnv->pResultBuf, pInfo->id.tid);
    if (list.size > 0 && pInfo->windowResInfo.size > 0) {
2864
      pTableList[numOfTables] = pInfo;
2865
      numOfTables += 1;
2866 2867
    }
  }
2868

2869
  if (numOfTables == 0) {
2870 2871
    tfree(posList);
    tfree(pTableList);
2872

2873 2874 2875
    assert(pQInfo->numOfGroupResultPages == 0);
    return 0;
  }
2876

2877
  SCompSupporter cs = {pTableList, posList, pQInfo};
2878

2879
  SLoserTreeInfo *pTree = NULL;
2880
  tLoserTreeCreate(&pTree, numOfTables, &cs, tableResultComparFn);
2881

2882
  SResultInfo *pResultInfo = calloc(pQuery->numOfOutput, sizeof(SResultInfo));
2883 2884
  setWindowResultInfo(pResultInfo, pQuery, pRuntimeEnv->stableQuery);
  resetMergeResultBuf(pQuery, pRuntimeEnv->pCtx, pResultInfo);
2885

2886 2887
  int64_t lastTimestamp = -1;
  int64_t startt = taosGetTimestampMs();
2888

2889 2890
  while (1) {
    int32_t pos = pTree->pNode[0].index;
2891

H
hjxilinx 已提交
2892
    SWindowResInfo *pWindowResInfo = &pTableList[pos]->windowResInfo;
2893
    SWindowResult * pWindowRes = getWindowResult(pWindowResInfo, cs.position[pos]);
2894

2895 2896
    char *b = getPosInResultPage(pRuntimeEnv, PRIMARYKEY_TIMESTAMP_COL_INDEX, pWindowRes);
    TSKEY ts = GET_INT64_VAL(b);
2897

2898 2899 2900 2901
    assert(ts == pWindowRes->window.skey);
    int64_t num = getNumOfResultWindowRes(pRuntimeEnv, pWindowRes);
    if (num <= 0) {
      cs.position[pos] += 1;
2902

2903 2904
      if (cs.position[pos] >= pWindowResInfo->size) {
        cs.position[pos] = -1;
2905

2906
        // all input sources are exhausted
2907
        if (--numOfTables == 0) {
2908 2909 2910 2911 2912 2913 2914
          break;
        }
      }
    } else {
      if (ts == lastTimestamp) {  // merge with the last one
        doMerge(pRuntimeEnv, ts, pWindowRes, true);
      } else {  // copy data to disk buffer
2915
        if (buffer[0]->num == pQuery->rec.capacity) {
2916 2917 2918
          if (flushFromResultBuf(pQInfo) != TSDB_CODE_SUCCESS) {
            return -1;
          }
2919

2920 2921
          resetMergeResultBuf(pQuery, pRuntimeEnv->pCtx, pResultInfo);
        }
2922

2923
        doMerge(pRuntimeEnv, ts, pWindowRes, false);
2924
        buffer[0]->num += 1;
2925
      }
2926

2927
      lastTimestamp = ts;
2928

2929 2930 2931
      cs.position[pos] += 1;
      if (cs.position[pos] >= pWindowResInfo->size) {
        cs.position[pos] = -1;
2932

2933
        // all input sources are exhausted
2934
        if (--numOfTables == 0) {
2935 2936 2937 2938
          break;
        }
      }
    }
2939

2940 2941
    tLoserTreeAdjust(pTree, pos + pTree->numOfEntries);
  }
2942

2943
  if (buffer[0]->num != 0) {  // there are data in buffer
2944
    if (flushFromResultBuf(pQInfo) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
2945
      qError("QInfo:%p failed to flush data into temp file, abort query", pQInfo);
2946

2947 2948 2949 2950
      tfree(pTree);
      tfree(pTableList);
      tfree(posList);
      tfree(pResultInfo);
2951

2952 2953 2954
      return -1;
    }
  }
2955

2956 2957 2958
  int64_t endt = taosGetTimestampMs();

#ifdef _DEBUG_VIEW
2959
  displayInterResult(pQuery->sdata, pRuntimeEnv, pQuery->sdata[0]->num);
2960
#endif
2961

S
slguan 已提交
2962
  qTrace("QInfo:%p result merge completed, elapsed time:%" PRId64 " ms", GET_QINFO_ADDR(pQuery), endt - startt);
2963 2964 2965
  tfree(pTree);
  tfree(pTableList);
  tfree(posList);
2966

2967
  pQInfo->offset = 0;
2968
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
2969 2970
    tfree(pResultInfo[i].interResultBuf);
  }
2971

2972 2973 2974 2975 2976
  tfree(pResultInfo);
  return pQInfo->numOfGroupResultPages;
}

int32_t flushFromResultBuf(SQInfo *pQInfo) {
2977 2978 2979
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;

2980
  SDiskbasedResultBuf *pResultBuf = pRuntimeEnv->pResultBuf;
2981 2982
  int32_t              capacity = (DEFAULT_INTERN_BUF_SIZE - sizeof(tFilePage)) / pQuery->rowSize;

2983 2984
  // the base value for group result, since the maximum number of table for each vnode will not exceed 100,000.
  int32_t pageId = -1;
2985

2986
  int32_t remain = pQuery->sdata[0]->num;
2987
  int32_t offset = 0;
2988

2989 2990 2991 2992 2993
  while (remain > 0) {
    int32_t r = remain;
    if (r > capacity) {
      r = capacity;
    }
2994

2995
    int32_t    id = getGroupResultId(pQInfo->groupIndex) + pQInfo->numOfGroupResultPages;
2996
    tFilePage *buf = getNewDataBuf(pResultBuf, id, &pageId);
2997

2998
    // pagewise copy to dest buffer
2999
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
3000
      int32_t bytes = pRuntimeEnv->pCtx[i].outputBytes;
3001
      buf->num = r;
3002

3003 3004
      memcpy(buf->data + pRuntimeEnv->offset[i] * buf->num, ((char *)pQuery->sdata[i]->data) + offset * bytes,
             buf->num * bytes);
3005
    }
3006

3007 3008 3009
    offset += r;
    remain -= r;
  }
3010

3011 3012 3013 3014 3015
  pQInfo->numOfGroupResultPages += 1;
  return TSDB_CODE_SUCCESS;
}

void resetMergeResultBuf(SQuery *pQuery, SQLFunctionCtx *pCtx, SResultInfo *pResultInfo) {
3016
  for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
3017
    pCtx[k].aOutputBuf = pQuery->sdata[k]->data - pCtx[k].outputBytes;
3018 3019 3020
    pCtx[k].size = 1;
    pCtx[k].startOffset = 0;
    pCtx[k].resultInfo = &pResultInfo[k];
3021

3022
    pQuery->sdata[k]->num = 0;
3023 3024 3025
  }
}

3026 3027 3028 3029 3030 3031 3032
static void updateTableQueryInfoForReverseScan(SQuery *pQuery, STableQueryInfo *pTableQueryInfo) {
  if (pTableQueryInfo == NULL) {
    return;
  }
  
  // order has change already!
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);
H
Haojun Liao 已提交
3033 3034 3035 3036 3037 3038 3039
  
  // TODO validate the assertion
//  if (!QUERY_IS_ASC_QUERY(pQuery)) {
//    assert(pTableQueryInfo->win.ekey >= pTableQueryInfo->lastKey + step);
//  } else {
//    assert(pTableQueryInfo->win.ekey <= pTableQueryInfo->lastKey + step);
//  }
3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052
  
  pTableQueryInfo->win.ekey = pTableQueryInfo->lastKey + step;
  
  SWAP(pTableQueryInfo->win.skey, pTableQueryInfo->win.ekey, TSKEY);
  pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
  
  SWITCH_ORDER(pTableQueryInfo->cur.order);
  pTableQueryInfo->cur.vgroupIndex = -1;
}

static void disableFuncInReverseScanImpl(SQInfo* pQInfo, SWindowResInfo *pWindowResInfo, int32_t order) {
  SQuery* pQuery = pQInfo->runtimeEnv.pQuery;
  
3053 3054 3055 3056 3057
  for (int32_t i = 0; i < pWindowResInfo->size; ++i) {
    SWindowStatus *pStatus = getTimeWindowResStatus(pWindowResInfo, i);
    if (!pStatus->closed) {
      continue;
    }
3058

3059
    SWindowResult *buf = getWindowResult(pWindowResInfo, i);
3060

3061
    // open/close the specified query for each group result
3062
    for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
3063
      int32_t functId = pQuery->pSelectExpr[j].base.functionId;
3064

3065 3066
      if (((functId == TSDB_FUNC_FIRST || functId == TSDB_FUNC_FIRST_DST) && order == TSDB_ORDER_ASC) ||
          ((functId == TSDB_FUNC_LAST || functId == TSDB_FUNC_LAST_DST) && order == TSDB_ORDER_DESC)) {
3067 3068 3069 3070 3071 3072 3073 3074
        buf->resultInfo[j].complete = false;
      } else if (functId != TSDB_FUNC_TS && functId != TSDB_FUNC_TAG) {
        buf->resultInfo[j].complete = true;
      }
    }
  }
}

3075 3076
void disableFuncInReverseScan(SQInfo *pQInfo) {
  SQueryRuntimeEnv* pRuntimeEnv = &pQInfo->runtimeEnv;
3077
  SQuery *pQuery = pRuntimeEnv->pQuery;
3078
  int32_t order = pQuery->order.order;
3079

3080 3081 3082
  // group by normal columns and interval query on normal table
  SWindowResInfo *pWindowResInfo = &pRuntimeEnv->windowResInfo;
  if (isGroupbyNormalCol(pQuery->pGroupbyExpr) || isIntervalQuery(pQuery)) {
3083
    disableFuncInReverseScanImpl(pQInfo, pWindowResInfo, order);
3084
  } else {  // for simple result of table query,
3085
    for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {  // todo refactor
3086
      int32_t functId = pQuery->pSelectExpr[j].base.functionId;
3087

3088
      SQLFunctionCtx *pCtx = &pRuntimeEnv->pCtx[j];
3089 3090 3091
      if (pCtx->resultInfo == NULL) {
        continue; // resultInfo is NULL, means no data checked in previous scan
      }
3092

3093 3094
      if (((functId == TSDB_FUNC_FIRST || functId == TSDB_FUNC_FIRST_DST) && order == TSDB_ORDER_ASC) ||
          ((functId == TSDB_FUNC_LAST || functId == TSDB_FUNC_LAST_DST) && order == TSDB_ORDER_DESC)) {
3095 3096 3097 3098 3099 3100
        pCtx->resultInfo->complete = false;
      } else if (functId != TSDB_FUNC_TS && functId != TSDB_FUNC_TAG) {
        pCtx->resultInfo->complete = true;
      }
    }
  }
H
hjxilinx 已提交
3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112
  
  int32_t numOfGroups = taosArrayGetSize(pQInfo->groupInfo.pGroupList);
  
  for(int32_t i = 0; i < numOfGroups; ++i) {
    SArray *group = taosArrayGetP(pQInfo->groupInfo.pGroupList, i);
    
    size_t t = taosArrayGetSize(group);
    for (int32_t j = 0; j < t; ++j) {
      SGroupItem *item = taosArrayGet(group, j);
      updateTableQueryInfoForReverseScan(pQuery, item->info);
    }
  }
3113 3114
}

3115
void switchCtxOrder(SQueryRuntimeEnv *pRuntimeEnv) {
3116
  SQuery *pQuery = pRuntimeEnv->pQuery;
3117
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
H
Haojun Liao 已提交
3118
    SWITCH_ORDER(pRuntimeEnv->pCtx[i].order);
3119 3120 3121 3122
  }
}

void createQueryResultInfo(SQuery *pQuery, SWindowResult *pResultRow, bool isSTableQuery, SPosInfo *posInfo) {
3123
  int32_t numOfCols = pQuery->numOfOutput;
3124

3125 3126
  pResultRow->resultInfo = calloc((size_t)numOfCols, sizeof(SResultInfo));
  pResultRow->pos = *posInfo;
3127

3128 3129 3130 3131 3132 3133
  // set the intermediate result output buffer
  setWindowResultInfo(pResultRow->resultInfo, pQuery, isSTableQuery);
}

void resetCtxOutputBuf(SQueryRuntimeEnv *pRuntimeEnv) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
3134

3135
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
3136 3137
    SQLFunctionCtx *pCtx = &pRuntimeEnv->pCtx[i];
    pCtx->aOutputBuf = pQuery->sdata[i]->data;
3138

3139 3140 3141 3142 3143 3144
    /*
     * set the output buffer information and intermediate buffer
     * not all queries require the interResultBuf, such as COUNT/TAGPRJ/PRJ/TAG etc.
     */
    resetResultInfo(&pRuntimeEnv->resultInfo[i]);
    pCtx->resultInfo = &pRuntimeEnv->resultInfo[i];
3145

3146
    // set the timestamp output buffer for top/bottom/diff query
3147
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
3148 3149 3150
    if (functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM || functionId == TSDB_FUNC_DIFF) {
      pCtx->ptsOutputBuf = pRuntimeEnv->pCtx[0].aOutputBuf;
    }
3151

3152
    memset(pQuery->sdata[i]->data, 0, (size_t)pQuery->pSelectExpr[i].bytes * pQuery->rec.capacity);
3153
  }
3154

3155 3156 3157 3158 3159
  initCtxOutputBuf(pRuntimeEnv);
}

void forwardCtxOutputBuf(SQueryRuntimeEnv *pRuntimeEnv, int64_t output) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
3160

3161
  // reset the execution contexts
3162
  for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
3163
    int32_t functionId = pQuery->pSelectExpr[j].base.functionId;
3164
    assert(functionId != TSDB_FUNC_DIFF);
3165

3166 3167 3168 3169
    // set next output position
    if (IS_OUTER_FORWARD(aAggs[functionId].nStatus)) {
      pRuntimeEnv->pCtx[j].aOutputBuf += pRuntimeEnv->pCtx[j].outputBytes * output;
    }
3170

3171 3172 3173 3174 3175 3176 3177 3178 3179 3180
    if (functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM) {
      /*
       * NOTE: for top/bottom query, the value of first column of output (timestamp) are assigned
       * in the procedure of top/bottom routine
       * the output buffer in top/bottom routine is ptsOutputBuf, so we need to forward the output buffer
       *
       * diff function is handled in multi-output function
       */
      pRuntimeEnv->pCtx[j].ptsOutputBuf += TSDB_KEYSIZE * output;
    }
3181

3182 3183 3184 3185 3186 3187
    resetResultInfo(pRuntimeEnv->pCtx[j].resultInfo);
  }
}

void initCtxOutputBuf(SQueryRuntimeEnv *pRuntimeEnv) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
3188

3189
  for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
3190
    int32_t functionId = pQuery->pSelectExpr[j].base.functionId;
3191

3192 3193 3194 3195 3196
    pRuntimeEnv->pCtx[j].currentStage = 0;
    aAggs[functionId].init(&pRuntimeEnv->pCtx[j]);
  }
}

3197
void skipResults(SQueryRuntimeEnv *pRuntimeEnv) {
3198
  SQuery *pQuery = pRuntimeEnv->pQuery;
3199
  if (pQuery->rec.rows == 0 || pQuery->limit.offset == 0) {
3200 3201
    return;
  }
3202

3203
  if (pQuery->rec.rows <= pQuery->limit.offset) {
3204 3205 3206
    qTrace("QInfo:%p skip rows:%d, new offset:%" PRIu64, GET_QINFO_ADDR(pRuntimeEnv), pQuery->rec.rows,
        pQuery->limit.offset - pQuery->rec.rows);
    
3207 3208
    pQuery->limit.offset -= pQuery->rec.rows;
    pQuery->rec.rows = 0;
3209

3210
    resetCtxOutputBuf(pRuntimeEnv);
3211

H
Haojun Liao 已提交
3212
    // clear the buffer full flag if exists
3213
    CLEAR_QUERY_STATUS(pQuery, QUERY_RESBUF_FULL);
3214
  } else {
3215
    int64_t numOfSkip = pQuery->limit.offset;
3216
    pQuery->rec.rows -= numOfSkip;
3217 3218 3219 3220 3221
    pQuery->limit.offset = 0;
  
    qTrace("QInfo:%p skip row:%"PRId64", new offset:%d, numOfRows remain:%" PRIu64, GET_QINFO_ADDR(pRuntimeEnv), numOfSkip,
           0, pQuery->rec.rows);
    
3222
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
3223
      int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
3224
      int32_t bytes = pRuntimeEnv->pCtx[i].outputBytes;
3225
      
H
Haojun Liao 已提交
3226 3227
      memmove(pQuery->sdata[i]->data, (char*) pQuery->sdata[i]->data + bytes * numOfSkip, pQuery->rec.rows * bytes);
      pRuntimeEnv->pCtx[i].aOutputBuf = ((char*) pQuery->sdata[i]->data) + pQuery->rec.rows * bytes;
3228

3229
      if (functionId == TSDB_FUNC_DIFF || functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM) {
3230
        pRuntimeEnv->pCtx[i].ptsOutputBuf = pRuntimeEnv->pCtx[0].aOutputBuf;
3231 3232
      }
    }
3233
  
H
Haojun Liao 已提交
3234
    
3235
    updateNumOfResult(pRuntimeEnv, pQuery->rec.rows);
3236 3237 3238 3239 3240 3241 3242 3243
  }
}

void setQueryStatus(SQuery *pQuery, int8_t status) {
  if (status == QUERY_NOT_COMPLETED) {
    pQuery->status = status;
  } else {
    // QUERY_NOT_COMPLETED is not compatible with any other status, so clear its position first
3244
    CLEAR_QUERY_STATUS(pQuery, QUERY_NOT_COMPLETED);
3245 3246 3247 3248 3249 3250
    pQuery->status |= status;
  }
}

bool needScanDataBlocksAgain(SQueryRuntimeEnv *pRuntimeEnv) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
3251

H
hjxilinx 已提交
3252
  bool toContinue = false;
3253 3254 3255
  if (isGroupbyNormalCol(pQuery->pGroupbyExpr) || isIntervalQuery(pQuery)) {
    // for each group result, call the finalize function for each column
    SWindowResInfo *pWindowResInfo = &pRuntimeEnv->windowResInfo;
3256

3257 3258 3259 3260 3261
    for (int32_t i = 0; i < pWindowResInfo->size; ++i) {
      SWindowResult *pResult = getWindowResult(pWindowResInfo, i);
      if (!pResult->status.closed) {
        continue;
      }
3262

3263
      setWindowResOutputBuf(pRuntimeEnv, pResult);
3264

3265
      for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
3266
        int16_t functId = pQuery->pSelectExpr[j].base.functionId;
3267 3268 3269
        if (functId == TSDB_FUNC_TS) {
          continue;
        }
3270

3271 3272
        aAggs[functId].xNextStep(&pRuntimeEnv->pCtx[j]);
        SResultInfo *pResInfo = GET_RES_INFO(&pRuntimeEnv->pCtx[j]);
3273

3274 3275 3276 3277
        toContinue |= (!pResInfo->complete);
      }
    }
  } else {
3278
    for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
3279
      int16_t functId = pQuery->pSelectExpr[j].base.functionId;
3280 3281 3282
      if (functId == TSDB_FUNC_TS) {
        continue;
      }
3283

3284 3285
      aAggs[functId].xNextStep(&pRuntimeEnv->pCtx[j]);
      SResultInfo *pResInfo = GET_RES_INFO(&pRuntimeEnv->pCtx[j]);
3286

3287 3288 3289
      toContinue |= (!pResInfo->complete);
    }
  }
3290

3291 3292 3293
  return toContinue;
}

H
Haojun Liao 已提交
3294
static SQueryStatusInfo getQueryStatusInfo(SQueryRuntimeEnv *pRuntimeEnv, TSKEY start) {
3295
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
3296 3297
  STableQueryInfo* pTableQueryInfo = pQuery->current;
  
H
Haojun Liao 已提交
3298 3299 3300
  assert((start <= pTableQueryInfo->lastKey && QUERY_IS_ASC_QUERY(pQuery)) ||
      (start >= pTableQueryInfo->lastKey && !QUERY_IS_ASC_QUERY(pQuery)));
  
3301
  SQueryStatusInfo info = {
H
hjxilinx 已提交
3302
      .status      = pQuery->status,
3303
      .windowIndex = pRuntimeEnv->windowResInfo.curIndex,
H
Haojun Liao 已提交
3304
      .lastKey     = start,
H
hjxilinx 已提交
3305
      .w           = pQuery->window,
H
Haojun Liao 已提交
3306
      .curWindow   = {.skey = start, .ekey = pTableQueryInfo->win.ekey},
3307
  };
3308

3309 3310 3311
  return info;
}

3312 3313 3314 3315
static void setEnvBeforeReverseScan(SQueryRuntimeEnv *pRuntimeEnv, SQueryStatusInfo *pStatus) {
  SQInfo *pQInfo = GET_QINFO_ADDR(pRuntimeEnv);
  SQuery *pQuery = pRuntimeEnv->pQuery;

3316 3317 3318 3319 3320
  pStatus->cur = tsBufGetCursor(pRuntimeEnv->pTSBuf);  // save the cursor
  if (pRuntimeEnv->pTSBuf) {
    SWITCH_ORDER(pRuntimeEnv->pTSBuf->cur.order);
    tsBufNextPos(pRuntimeEnv->pTSBuf);
  }
3321

3322
  // reverse order time range
3323 3324 3325
  pQuery->window = pStatus->curWindow;
  SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);

3326
  SWITCH_ORDER(pQuery->order.order);
3327
  SET_REVERSE_SCAN_FLAG(pRuntimeEnv);
3328

3329
  STsdbQueryCond cond = {
3330
      .twindow = pQuery->window,
H
hjxilinx 已提交
3331
      .order   = pQuery->order.order,
3332
      .colList = pQuery->colList,
3333 3334
      .numOfCols = pQuery->numOfCols,
  };
3335

3336 3337 3338 3339
  // clean unused handle
  if (pRuntimeEnv->pSecQueryHandle != NULL) {
    tsdbCleanupQueryHandle(pRuntimeEnv->pSecQueryHandle);
  }
3340

H
hjxilinx 已提交
3341
  pRuntimeEnv->pSecQueryHandle = tsdbQueryTables(pQInfo->tsdb, &cond, &pQInfo->tableIdGroupInfo);
3342

3343 3344
  setQueryStatus(pQuery, QUERY_NOT_COMPLETED);
  switchCtxOrder(pRuntimeEnv);
3345
  disableFuncInReverseScan(pQInfo);
3346 3347
}

3348 3349
static void clearEnvAfterReverseScan(SQueryRuntimeEnv *pRuntimeEnv, SQueryStatusInfo *pStatus) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
3350
  STableQueryInfo* pTableQueryInfo = pQuery->current;
3351

3352 3353
  SWITCH_ORDER(pQuery->order.order);
  switchCtxOrder(pRuntimeEnv);
3354

3355 3356 3357 3358
  tsBufSetCursor(pRuntimeEnv->pTSBuf, &pStatus->cur);
  if (pRuntimeEnv->pTSBuf) {
    pRuntimeEnv->pTSBuf->cur.order = pQuery->order.order;
  }
3359

3360
  SET_MASTER_SCAN_FLAG(pRuntimeEnv);
3361

3362 3363
  // update the pQuery->window.skey and pQuery->window.ekey to limit the scan scope of sliding query
  // during reverse scan
H
hjxilinx 已提交
3364
  pTableQueryInfo->lastKey = pStatus->lastKey;
3365
  pQuery->status = pStatus->status;
H
hjxilinx 已提交
3366
  pTableQueryInfo->win = pStatus->w;
3367 3368
}

H
Haojun Liao 已提交
3369
void scanAllDataBlocks(SQueryRuntimeEnv *pRuntimeEnv, TSKEY start) {
H
hjxilinx 已提交
3370
  SQInfo *pQInfo = (SQInfo *) GET_QINFO_ADDR(pRuntimeEnv);
3371
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
3372 3373
  STableQueryInfo *pTableQueryInfo = pQuery->current;
  
3374
  setQueryStatus(pQuery, QUERY_NOT_COMPLETED);
3375

3376
  // store the start query position
H
Haojun Liao 已提交
3377
  SQueryStatusInfo qstatus = getQueryStatusInfo(pRuntimeEnv, start);
3378

3379 3380
  SET_MASTER_SCAN_FLAG(pRuntimeEnv);
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);
3381

3382 3383
  while (1) {
    doScanAllDataBlocks(pRuntimeEnv);
3384

3385 3386
    if (pRuntimeEnv->scanFlag == MASTER_SCAN) {
      qstatus.status = pQuery->status;
H
hjxilinx 已提交
3387
      qstatus.curWindow.ekey = pTableQueryInfo->lastKey - step;
3388
    }
3389

3390
    if (!needScanDataBlocksAgain(pRuntimeEnv)) {
3391
      // restore the status code and jump out of loop
3392
      if (pRuntimeEnv->scanFlag == REPEAT_SCAN) {
3393
        pQuery->status = qstatus.status;
3394
      }
3395

3396 3397
      break;
    }
3398

3399
    STsdbQueryCond cond = {
3400
        .twindow = qstatus.curWindow,
H
hjxilinx 已提交
3401
        .order   = pQuery->order.order,
3402
        .colList = pQuery->colList,
3403
        .numOfCols = pQuery->numOfCols,
3404
    };
3405

3406 3407
    if (pRuntimeEnv->pSecQueryHandle != NULL) {
      tsdbCleanupQueryHandle(pRuntimeEnv->pSecQueryHandle);
3408
    }
3409

H
hjxilinx 已提交
3410
    pRuntimeEnv->pSecQueryHandle = tsdbQueryTables(pQInfo->tsdb, &cond, &pQInfo->tableIdGroupInfo);
3411
    pRuntimeEnv->windowResInfo.curIndex = qstatus.windowIndex;
3412

3413 3414
    setQueryStatus(pQuery, QUERY_NOT_COMPLETED);
    pRuntimeEnv->scanFlag = REPEAT_SCAN;
3415

3416
    // check if query is killed or not
3417
    if (isQueryKilled(pQInfo)) {
3418 3419 3420
      return;
    }
  }
3421

H
hjxilinx 已提交
3422
  if (!needReverseScan(pQuery)) {
3423 3424
    return;
  }
3425

3426
  setEnvBeforeReverseScan(pRuntimeEnv, &qstatus);
3427

3428
  // reverse scan from current position
3429
  qTrace("QInfo:%p start to reverse scan", pQInfo);
3430
  doScanAllDataBlocks(pRuntimeEnv);
3431 3432

  clearEnvAfterReverseScan(pRuntimeEnv, &qstatus);
3433 3434
}

H
hjxilinx 已提交
3435
void finalizeQueryResult(SQueryRuntimeEnv *pRuntimeEnv) {
3436
  SQuery *pQuery = pRuntimeEnv->pQuery;
3437

3438 3439 3440 3441 3442 3443
  if (isGroupbyNormalCol(pQuery->pGroupbyExpr) || isIntervalQuery(pQuery)) {
    // for each group result, call the finalize function for each column
    SWindowResInfo *pWindowResInfo = &pRuntimeEnv->windowResInfo;
    if (isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
      closeAllTimeWindow(pWindowResInfo);
    }
3444

3445 3446 3447 3448 3449
    for (int32_t i = 0; i < pWindowResInfo->size; ++i) {
      SWindowResult *buf = &pWindowResInfo->pResult[i];
      if (!isWindowResClosed(pWindowResInfo, i)) {
        continue;
      }
3450

3451
      setWindowResOutputBuf(pRuntimeEnv, buf);
3452

3453
      for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
3454
        aAggs[pQuery->pSelectExpr[j].base.functionId].xFinalize(&pRuntimeEnv->pCtx[j]);
3455
      }
3456

3457 3458 3459 3460 3461 3462
      /*
       * set the number of output results for group by normal columns, the number of output rows usually is 1 except
       * the top and bottom query
       */
      buf->numOfRows = getNumOfResult(pRuntimeEnv);
    }
3463

3464
  } else {
3465
    for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
3466
      aAggs[pQuery->pSelectExpr[j].base.functionId].xFinalize(&pRuntimeEnv->pCtx[j]);
3467 3468 3469 3470 3471
    }
  }
}

static bool hasMainOutput(SQuery *pQuery) {
3472
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
3473
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
3474

3475 3476 3477 3478
    if (functionId != TSDB_FUNC_TS && functionId != TSDB_FUNC_TAG && functionId != TSDB_FUNC_TAGPRJ) {
      return true;
    }
  }
3479

3480 3481 3482
  return false;
}

weixin_48148422's avatar
weixin_48148422 已提交
3483 3484 3485 3486 3487
static STableQueryInfo *createTableQueryInfo(
  SQueryRuntimeEnv *pRuntimeEnv,
  STableId tableId,
  STimeWindow win
) {
3488
  STableQueryInfo *pTableQueryInfo = calloc(1, sizeof(STableQueryInfo));
3489

H
hjxilinx 已提交
3490 3491
  pTableQueryInfo->win = win;
  pTableQueryInfo->lastKey = win.skey;
3492

H
hjxilinx 已提交
3493
  pTableQueryInfo->id = tableId;
3494
  pTableQueryInfo->cur.vgroupIndex = -1;
3495

3496 3497 3498 3499
  initWindowResInfo(&pTableQueryInfo->windowResInfo, pRuntimeEnv, 100, 100, TSDB_DATA_TYPE_INT);
  return pTableQueryInfo;
}

3500
void destroyTableQueryInfo(STableQueryInfo *pTableQueryInfo, int32_t numOfCols) {
3501 3502 3503
  if (pTableQueryInfo == NULL) {
    return;
  }
3504

3505 3506 3507 3508 3509 3510
  cleanupTimeWindowInfo(&pTableQueryInfo->windowResInfo, numOfCols);
  free(pTableQueryInfo);
}

void restoreIntervalQueryRange(SQueryRuntimeEnv *pRuntimeEnv, STableQueryInfo *pTableQueryInfo) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
3511 3512 3513 3514
  pQuery->current = pTableQueryInfo;
  
  assert(((pTableQueryInfo->lastKey >= pTableQueryInfo->win.skey) && QUERY_IS_ASC_QUERY(pQuery)) ||
         ((pTableQueryInfo->lastKey <= pTableQueryInfo->win.skey) && !QUERY_IS_ASC_QUERY(pQuery)));
3515 3516 3517 3518 3519
}

/**
 * set output buffer for different group
 * @param pRuntimeEnv
3520
 * @param pDataBlockInfo
3521
 */
H
hjxilinx 已提交
3522
void setExecutionContext(SQInfo *pQInfo, STableId* pTableId, int32_t groupIdx, TSKEY nextKey) {
3523
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
H
hjxilinx 已提交
3524 3525
  STableQueryInfo *pTableQueryInfo = pRuntimeEnv->pQuery->current;
  
3526 3527
  SWindowResInfo *  pWindowResInfo = &pRuntimeEnv->windowResInfo;
  int32_t           GROUPRESULTID = 1;
3528

3529 3530 3531 3532
  SWindowResult *pWindowRes = doSetTimeWindowFromKey(pRuntimeEnv, pWindowResInfo, (char *)&groupIdx, sizeof(groupIdx));
  if (pWindowRes == NULL) {
    return;
  }
3533

3534 3535 3536 3537 3538 3539 3540 3541 3542 3543
  /*
   * not assign result buffer yet, add new result buffer
   * all group belong to one result set, and each group result has different group id so set the id to be one
   */
  if (pWindowRes->pos.pageId == -1) {
    if (addNewWindowResultBuf(pWindowRes, pRuntimeEnv->pResultBuf, GROUPRESULTID, pRuntimeEnv->numOfRowsPerPage) !=
        TSDB_CODE_SUCCESS) {
      return;
    }
  }
3544

3545 3546
  setWindowResOutputBuf(pRuntimeEnv, pWindowRes);
  initCtxOutputBuf(pRuntimeEnv);
3547

3548
  pTableQueryInfo->lastKey = nextKey;
H
hjxilinx 已提交
3549
  setAdditionalInfo(pQInfo, pTableId, pTableQueryInfo);
3550 3551 3552 3553
}

static void setWindowResOutputBuf(SQueryRuntimeEnv *pRuntimeEnv, SWindowResult *pResult) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
3554

3555
  // Note: pResult->pos[i]->num == 0, there is only fixed number of results for each group
3556
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
3557 3558
    SQLFunctionCtx *pCtx = &pRuntimeEnv->pCtx[i];
    pCtx->aOutputBuf = getPosInResultPage(pRuntimeEnv, i, pResult);
3559

3560
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
3561 3562 3563
    if (functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM || functionId == TSDB_FUNC_DIFF) {
      pCtx->ptsOutputBuf = pRuntimeEnv->pCtx[0].aOutputBuf;
    }
3564

3565 3566 3567 3568 3569
    /*
     * set the output buffer information and intermediate buffer
     * not all queries require the interResultBuf, such as COUNT
     */
    pCtx->resultInfo = &pResult->resultInfo[i];
3570

3571 3572 3573 3574 3575 3576
    // set super table query flag
    SResultInfo *pResInfo = GET_RES_INFO(pCtx);
    pResInfo->superTableQ = pRuntimeEnv->stableQuery;
  }
}

H
hjxilinx 已提交
3577
int32_t setAdditionalInfo(SQInfo *pQInfo, STableId* pTableId, STableQueryInfo *pTableQueryInfo) {
3578
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
3579
  assert(pTableQueryInfo->lastKey >= 0);
3580

H
hjxilinx 已提交
3581
  setTagVal(pRuntimeEnv, pTableId, pQInfo->tsdb);
3582

3583 3584
  // both the master and supplement scan needs to set the correct ts comp start position
  if (pRuntimeEnv->pTSBuf != NULL) {
3585
    if (pTableQueryInfo->cur.vgroupIndex == -1) {
3586
      pTableQueryInfo->tag = pRuntimeEnv->pCtx[0].tag.i64Key;
3587

3588
      tsBufGetElemStartPos(pRuntimeEnv->pTSBuf, 0, pTableQueryInfo->tag);
3589

3590 3591 3592 3593 3594 3595
      // keep the cursor info of current meter
      pTableQueryInfo->cur = pRuntimeEnv->pTSBuf->cur;
    } else {
      tsBufSetCursor(pRuntimeEnv->pTSBuf, &pTableQueryInfo->cur);
    }
  }
3596

3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608
  return 0;
}

/*
 * There are two cases to handle:
 *
 * 1. Query range is not set yet (queryRangeSet = 0). we need to set the query range info, including pQuery->lastKey,
 *    pQuery->window.skey, and pQuery->eKey.
 * 2. Query range is set and query is in progress. There may be another result with the same query ranges to be
 *    merged during merge stage. In this case, we need the pTableQueryInfo->lastResRows to decide if there
 *    is a previous result generated or not.
 */
H
hjxilinx 已提交
3609
void setIntervalQueryRange(SQInfo *pQInfo, TSKEY key) {
3610 3611
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
3612 3613
  STableQueryInfo *pTableQueryInfo = pQuery->current;
  
3614 3615 3616
  if (pTableQueryInfo->queryRangeSet) {
    pTableQueryInfo->lastKey = key;
  } else {
3617
    pTableQueryInfo->win.skey = key;
3618
    STimeWindow win = {.skey = key, .ekey = pQuery->window.ekey};
3619

3620 3621 3622 3623 3624
    // for too small query range, no data in this interval.
    if ((QUERY_IS_ASC_QUERY(pQuery) && (pQuery->window.ekey < pQuery->window.skey)) ||
        (!QUERY_IS_ASC_QUERY(pQuery) && (pQuery->window.skey < pQuery->window.ekey))) {
      return;
    }
3625

3626 3627 3628 3629 3630 3631
    /**
     * In handling the both ascending and descending order super table query, we need to find the first qualified
     * timestamp of this table, and then set the first qualified start timestamp.
     * In ascending query, key is the first qualified timestamp. However, in the descending order query, additional
     * operations involve.
     */
3632 3633
    TSKEY           skey1, ekey1;
    STimeWindow     w = {0};
3634
    SWindowResInfo *pWindowResInfo = &pTableQueryInfo->windowResInfo;
3635

3636
    getAlignQueryTimeWindow(pQuery, win.skey, win.skey, win.ekey, &skey1, &ekey1, &w);
3637
    pWindowResInfo->startTime = pTableQueryInfo->win.skey;  // windowSKey may be 0 in case of 1970 timestamp
3638

3639 3640
    if (pWindowResInfo->prevSKey == TSKEY_INITIAL_VAL) {
      if (!QUERY_IS_ASC_QUERY(pQuery)) {
3641 3642
        assert(win.ekey == pQuery->window.skey);
      }
3643 3644
      
      pWindowResInfo->prevSKey = w.skey;
3645
    }
3646

3647
    pTableQueryInfo->queryRangeSet = 1;
3648
    pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
3649 3650 3651 3652
  }
}

bool requireTimestamp(SQuery *pQuery) {
3653
  for (int32_t i = 0; i < pQuery->numOfOutput; i++) {
3654
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667
    if ((aAggs[functionId].nStatus & TSDB_FUNCSTATE_NEED_TS) != 0) {
      return true;
    }
  }
  return false;
}

bool needPrimaryTimestampCol(SQuery *pQuery, SDataBlockInfo *pDataBlockInfo) {
  /*
   * 1. if skey or ekey locates in this block, we need to load the timestamp column to decide the precise position
   * 2. if there are top/bottom, first_dst/last_dst functions, we need to load timestamp column in any cases;
   */
  STimeWindow *w = &pDataBlockInfo->window;
H
hjxilinx 已提交
3668 3669 3670
  STableQueryInfo* pTableQueryInfo = pQuery->current;
  
  bool loadPrimaryTS = (pTableQueryInfo->lastKey >= w->skey && pTableQueryInfo->lastKey <= w->ekey) ||
3671 3672
                       (pQuery->window.ekey >= w->skey && pQuery->window.ekey <= w->ekey) || requireTimestamp(pQuery);

3673 3674 3675 3676 3677 3678 3679 3680 3681
  return loadPrimaryTS;
}

bool onDemandLoadDatablock(SQuery *pQuery, int16_t queryRangeSet) {
  return (pQuery->intervalTime == 0) || ((queryRangeSet == 1) && (isIntervalQuery(pQuery)));
}

static int32_t getNumOfSubset(SQInfo *pQInfo) {
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
3682

3683 3684 3685 3686
  int32_t totalSubset = 0;
  if (isGroupbyNormalCol(pQuery->pGroupbyExpr) || (isIntervalQuery(pQuery))) {
    totalSubset = numOfClosedTimeWindow(&pQInfo->runtimeEnv.windowResInfo);
  } else {
3687
    totalSubset = taosArrayGetSize(pQInfo->groupInfo.pGroupList);
3688
  }
3689

3690 3691 3692 3693 3694 3695
  return totalSubset;
}

static int32_t doCopyToSData(SQInfo *pQInfo, SWindowResult *result, int32_t orderType) {
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;
3696

3697 3698 3699
  int32_t numOfResult = 0;
  int32_t startIdx = 0;
  int32_t step = -1;
3700

S
slguan 已提交
3701
  qTrace("QInfo:%p start to copy data from windowResInfo to query buf", GET_QINFO_ADDR(pQuery));
3702
  int32_t totalSubset = getNumOfSubset(pQInfo);
3703

3704
  if (orderType == TSDB_ORDER_ASC) {
3705
    startIdx = pQInfo->groupIndex;
3706 3707
    step = 1;
  } else {  // desc order copy all data
3708
    startIdx = totalSubset - pQInfo->groupIndex - 1;
3709 3710
    step = -1;
  }
3711

3712 3713 3714
  for (int32_t i = startIdx; (i < totalSubset) && (i >= 0); i += step) {
    if (result[i].numOfRows == 0) {
      pQInfo->offset = 0;
3715
      pQInfo->groupIndex += 1;
3716 3717
      continue;
    }
3718

3719
    assert(result[i].numOfRows >= 0 && pQInfo->offset <= 1);
3720

3721 3722
    int32_t numOfRowsToCopy = result[i].numOfRows - pQInfo->offset;
    int32_t oldOffset = pQInfo->offset;
3723

3724 3725 3726 3727
    /*
     * current output space is not enough to keep all the result data of this group, only copy partial results
     * to SQuery object's result buffer
     */
3728 3729 3730 3731 3732
    if (numOfRowsToCopy > pQuery->rec.capacity - numOfResult) {
      numOfRowsToCopy = pQuery->rec.capacity - numOfResult;
      pQInfo->offset += numOfRowsToCopy;
    } else {
      pQInfo->offset = 0;
3733
      pQInfo->groupIndex += 1;
3734
    }
3735

3736
    for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
3737
      int32_t size = pRuntimeEnv->pCtx[j].outputBytes;
3738

3739 3740 3741 3742
      char *out = pQuery->sdata[j]->data + numOfResult * size;
      char *in = getPosInResultPage(pRuntimeEnv, j, &result[i]);
      memcpy(out, in + oldOffset * size, size * numOfRowsToCopy);
    }
3743

3744
    numOfResult += numOfRowsToCopy;
3745 3746 3747
    if (numOfResult == pQuery->rec.capacity) {
      break;
    }
3748
  }
3749

S
slguan 已提交
3750
  qTrace("QInfo:%p copy data to query buf completed", pQInfo);
3751 3752

#ifdef _DEBUG_VIEW
3753
  displayInterResult(pQuery->sdata, pRuntimeEnv, numOfResult);
3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768
#endif
  return numOfResult;
}

/**
 * copyFromWindowResToSData support copy data in ascending/descending order
 * For interval query of both super table and table, copy the data in ascending order, since the output results are
 * ordered in SWindowResutl already. While handling the group by query for both table and super table,
 * all group result are completed already.
 *
 * @param pQInfo
 * @param result
 */
void copyFromWindowResToSData(SQInfo *pQInfo, SWindowResult *result) {
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
3769

3770
  int32_t orderType = (pQuery->pGroupbyExpr != NULL) ? pQuery->pGroupbyExpr->orderType : TSDB_ORDER_ASC;
3771
  int32_t numOfResult = doCopyToSData(pQInfo, result, orderType);
3772

3773
  pQuery->rec.rows += numOfResult;
3774

3775
  assert(pQuery->rec.rows <= pQuery->rec.capacity);
3776 3777
}

H
hjxilinx 已提交
3778
static void updateWindowResNumOfRes(SQueryRuntimeEnv *pRuntimeEnv, STableQueryInfo *pTableQueryInfo) {
3779
  SQuery *pQuery = pRuntimeEnv->pQuery;
3780

3781 3782
  // update the number of result for each, only update the number of rows for the corresponding window result.
  if (pQuery->intervalTime == 0) {
H
hjxilinx 已提交
3783
    int32_t g = pTableQueryInfo->groupIdx;
3784
    assert(pRuntimeEnv->windowResInfo.size > 0);
3785

3786 3787 3788 3789 3790 3791 3792
    SWindowResult *pWindowRes = doSetTimeWindowFromKey(pRuntimeEnv, &pRuntimeEnv->windowResInfo, (char *)&g, sizeof(g));
    if (pWindowRes->numOfRows == 0) {
      pWindowRes->numOfRows = getNumOfResult(pRuntimeEnv);
    }
  }
}

H
hjxilinx 已提交
3793
void stableApplyFunctionsOnBlock(SQueryRuntimeEnv *pRuntimeEnv, STableQueryInfo *pTableQueryInfo,
3794 3795 3796 3797
                                 SDataBlockInfo *pDataBlockInfo, SDataStatis *pStatis, SArray *pDataBlock,
                                 __block_search_fn_t searchFn) {
  SQuery *         pQuery = pRuntimeEnv->pQuery;
  SWindowResInfo * pWindowResInfo = &pTableQueryInfo->windowResInfo;
H
hjxilinx 已提交
3798 3799
  pQuery->pos = QUERY_IS_ASC_QUERY(pQuery)? 0 : pDataBlockInfo->rows - 1;
  
3800
  if (pQuery->numOfFilterCols > 0 || pRuntimeEnv->pTSBuf != NULL) {
3801
    rowwiseApplyFunctions(pRuntimeEnv, pStatis, pDataBlockInfo, pWindowResInfo, pDataBlock);
3802
  } else {
3803
    blockwiseApplyFunctions(pRuntimeEnv, pStatis, pDataBlockInfo, pWindowResInfo, searchFn, pDataBlock);
3804
  }
3805

H
hjxilinx 已提交
3806
  updateWindowResNumOfRes(pRuntimeEnv, pTableQueryInfo);
3807 3808
}

3809 3810 3811 3812 3813 3814
bool queryHasRemainResults(SQueryRuntimeEnv* pRuntimeEnv) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
  SFillInfo *pFillInfo = pRuntimeEnv->pFillInfo;
  
  if (pQuery->fillType == TSDB_FILL_NONE) {
    assert(pFillInfo == NULL);
3815 3816
    return false;
  }
3817

3818
  if (pQuery->limit.limit > 0 && pQuery->rec.rows >= pQuery->limit.limit) {
3819 3820
    return false;
  }
3821

3822 3823 3824
  // There are results not returned to client, fill operation applied to the remain result set in the
  // first place is required.
  int32_t remain = taosNumOfRemainRows(pFillInfo);
3825 3826 3827 3828
  if (remain > 0) {
    return true;
  }
  
3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842
  /*
   * There are no results returned to client now.
   * If query is not completed yet, the gaps between two results blocks need to be handled after next data block
   * is retrieved from TSDB.
   *
   * NOTE: If the result set is not the first block, the gap in front of the result set will be filled. If the result
   * set is the FIRST result block, the gap between the start time of query time window and the timestamp of the
   * first result row in the actual result set will fill nothing.
   */
  if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
    TSKEY ekey = taosGetRevisedEndKey(pQuery->window.ekey, pQuery->order.order, pQuery->slidingTime,
                                         pQuery->slidingTimeUnit, pQuery->precision);
    int32_t numOfTotal = taosGetNumOfResultWithFill(pFillInfo, remain, ekey, pQuery->rec.capacity);
    return numOfTotal > 0;
3843
  }
3844 3845

  return false;
3846 3847 3848
}

static void doCopyQueryResultToMsg(SQInfo *pQInfo, int32_t numOfRows, char *data) {
3849
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
3850 3851
  for (int32_t col = 0; col < pQuery->numOfOutput; ++col) {
    int32_t bytes = pQuery->pSelectExpr[col].bytes;
3852

3853 3854 3855
    memmove(data, pQuery->sdata[col]->data, bytes * numOfRows);
    data += bytes * numOfRows;
  }
3856

weixin_48148422's avatar
weixin_48148422 已提交
3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868
  int32_t numOfTables = (int32_t)taosArrayGetSize(pQInfo->arrTableIdInfo);
  *(int32_t*)data = htonl(numOfTables);
  data += sizeof(int32_t);
  for(int32_t i = 0; i < numOfTables; i++) {
    STableIdInfo* pSrc = taosArrayGet(pQInfo->arrTableIdInfo, i);
    STableIdInfo* pDst = (STableIdInfo*)data;
    pDst->uid = htobe64(pSrc->uid);
    pDst->tid = htonl(pSrc->tid);
    pDst->key = htobe64(pSrc->key);
    data += sizeof(STableIdInfo);
  }

H
hjxilinx 已提交
3869 3870
  // all data returned, set query over
  if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
3871
    if (pQInfo->runtimeEnv.stableQuery) {
3872 3873 3874 3875
      if (pQInfo->tableIndex >= pQInfo->groupInfo.numOfTables) {
        setQueryStatus(pQuery, QUERY_OVER);
      }
    } else {
3876 3877 3878
      if (!queryHasRemainResults(&pQInfo->runtimeEnv)) {
        setQueryStatus(pQuery, QUERY_OVER);
      }
3879
    }
H
hjxilinx 已提交
3880
  }
3881 3882
}

3883 3884
int32_t doFillGapsInResults(SQueryRuntimeEnv* pRuntimeEnv, tFilePage **pDst, int32_t numOfRows, int32_t *numOfInterpo) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
3885
  while (1) {
3886 3887
    taosGenerateDataBlock(pRuntimeEnv->pFillInfo, (tFilePage**) pQuery->sdata, &pQuery->rec.rows, pQuery->rec.capacity);
    int32_t ret = pQuery->rec.rows;
3888
    
3889
    // todo apply limit output function
3890 3891 3892 3893
    /* reached the start position of according to offset value, return immediately */
    if (pQuery->limit.offset == 0) {
      return ret;
    }
3894

3895 3896 3897 3898
    if (pQuery->limit.offset < ret) {
      ret -= pQuery->limit.offset;
      // todo !!!!there exactly number of interpo is not valid.
      // todo refactor move to the beginning of buffer
3899 3900 3901
      for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
        memmove(pDst[i]->data, pDst[i]->data + pQuery->pSelectExpr[i].bytes * pQuery->limit.offset,
                ret * pQuery->pSelectExpr[i].bytes);
3902 3903 3904 3905 3906 3907 3908
      }
      pQuery->limit.offset = 0;
      return ret;
    } else {
      pQuery->limit.offset -= ret;
      ret = 0;
    }
3909 3910

    if (!queryHasRemainResults(pRuntimeEnv)) {
3911 3912 3913
      return ret;
    }
  }
3914
  
3915
  return 0;
3916 3917 3918
}

void vnodePrintQueryStatistics(SQInfo *pQInfo) {
3919
#if 0
3920
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
3921

3922
  SQuery *pQuery = pRuntimeEnv->pQuery;
3923

3924 3925 3926 3927 3928 3929 3930
  SQueryCostSummary *pSummary = &pRuntimeEnv->summary;
  if (pRuntimeEnv->pResultBuf == NULL) {
    pSummary->tmpBufferInDisk = 0;
  } else {
    pSummary->tmpBufferInDisk = getResBufSize(pRuntimeEnv->pResultBuf);
  }
  
S
slguan 已提交
3931
  qTrace("QInfo:%p statis: comp blocks:%d, size:%d Bytes, elapsed time:%.2f ms", pQInfo, pSummary->readCompInfo,
3932 3933
         pSummary->totalCompInfoSize, pSummary->loadCompInfoUs / 1000.0);
  
S
slguan 已提交
3934
  qTrace("QInfo:%p statis: field info: %d, size:%d Bytes, avg size:%.2f Bytes, elapsed time:%.2f ms", pQInfo,
3935 3936 3937
         pSummary->readField, pSummary->totalFieldSize, (double)pSummary->totalFieldSize / pSummary->readField,
         pSummary->loadFieldUs / 1000.0);
  
S
slguan 已提交
3938
  qTrace(
3939 3940 3941 3942
      "QInfo:%p statis: file blocks:%d, size:%d Bytes, elapsed time:%.2f ms, skipped:%d, in-memory gen null:%d Bytes",
      pQInfo, pSummary->readDiskBlocks, pSummary->totalBlockSize, pSummary->loadBlocksUs / 1000.0,
      pSummary->skippedFileBlocks, pSummary->totalGenData);
  
S
slguan 已提交
3943 3944
  qTrace("QInfo:%p statis: cache blocks:%d", pQInfo, pSummary->blocksInCache, 0);
  qTrace("QInfo:%p statis: temp file:%d Bytes", pQInfo, pSummary->tmpBufferInDisk);
3945
  
S
slguan 已提交
3946 3947
  qTrace("QInfo:%p statis: file:%d, table:%d", pQInfo, pSummary->numOfFiles, pSummary->numOfTables);
  qTrace("QInfo:%p statis: seek ops:%d", pQInfo, pSummary->numOfSeek);
3948 3949 3950 3951 3952 3953 3954
  
  double total = pSummary->fileTimeUs + pSummary->cacheTimeUs;
  double io = pSummary->loadCompInfoUs + pSummary->loadBlocksUs + pSummary->loadFieldUs;
  
  // todo add the intermediate result save cost!!
  double computing = total - io;
  
S
slguan 已提交
3955
  qTrace(
3956 3957 3958 3959 3960 3961 3962 3963
      "QInfo:%p statis: total elapsed time:%.2f ms, file:%.2f ms(%.2f%), cache:%.2f ms(%.2f%). io:%.2f ms(%.2f%),"
      "comput:%.2fms(%.2f%)",
      pQInfo, total / 1000.0, pSummary->fileTimeUs / 1000.0, pSummary->fileTimeUs * 100 / total,
      pSummary->cacheTimeUs / 1000.0, pSummary->cacheTimeUs * 100 / total, io / 1000.0, io * 100 / total,
      computing / 1000.0, computing * 100 / total);
#endif
}

3964 3965
static void updateOffsetVal(SQueryRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
3966 3967
  STableQueryInfo* pTableQueryInfo = pQuery->current;
  
3968
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);
3969

3970
  if (pQuery->limit.offset == pBlockInfo->rows) {  // current block will ignore completed
H
hjxilinx 已提交
3971
    pTableQueryInfo->lastKey = QUERY_IS_ASC_QUERY(pQuery) ? pBlockInfo->window.ekey + step : pBlockInfo->window.skey + step;
3972 3973 3974
    pQuery->limit.offset = 0;
    return;
  }
3975

3976 3977 3978 3979 3980
  if (QUERY_IS_ASC_QUERY(pQuery)) {
    pQuery->pos = pQuery->limit.offset;
  } else {
    pQuery->pos = pBlockInfo->rows - pQuery->limit.offset - 1;
  }
3981

3982
  assert(pQuery->pos >= 0 && pQuery->pos <= pBlockInfo->rows - 1);
3983

3984
  SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pQueryHandle, NULL);
3985
  SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
3986

3987 3988 3989 3990
  // update the pQuery->limit.offset value, and pQuery->pos value
  TSKEY *keys = (TSKEY *)pColInfoData->pData;

  // update the offset value
H
hjxilinx 已提交
3991
  pTableQueryInfo->lastKey = keys[pQuery->pos];
3992
  pQuery->limit.offset = 0;
3993

H
hjxilinx 已提交
3994
  int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, pBlockInfo, NULL, binarySearchForKey, pDataBlock);
3995

3996
  qTrace("QInfo:%p check data block, brange:%" PRId64 "-%" PRId64 ", rows:%d, numOfRes:%d", GET_QINFO_ADDR(pRuntimeEnv),
3997 3998
         pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows, numOfRes);
}
3999

4000 4001 4002 4003 4004
void skipBlocks(SQueryRuntimeEnv *pRuntimeEnv) {
  SQuery *pQuery = pRuntimeEnv->pQuery;

  if (pQuery->limit.offset <= 0 || pQuery->numOfFilterCols > 0) {
    return;
4005
  }
4006

4007 4008 4009
  pQuery->pos = 0;
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);

H
hjxilinx 已提交
4010
  STableQueryInfo* pTableQueryInfo = pQuery->current;
4011
  TsdbQueryHandleT pQueryHandle = pRuntimeEnv->pQueryHandle;
4012

4013 4014 4015
  while (tsdbNextDataBlock(pQueryHandle)) {
    if (isQueryKilled(GET_QINFO_ADDR(pRuntimeEnv))) {
      return;
4016
    }
4017

4018
    SDataBlockInfo blockInfo = tsdbRetrieveDataBlockInfo(pQueryHandle);
4019

4020 4021
    if (pQuery->limit.offset > blockInfo.rows) {
      pQuery->limit.offset -= blockInfo.rows;
H
hjxilinx 已提交
4022 4023
      pTableQueryInfo->lastKey = (QUERY_IS_ASC_QUERY(pQuery)) ? blockInfo.window.ekey : blockInfo.window.skey;
      pTableQueryInfo->lastKey += step;
4024

4025
      qTrace("QInfo:%p skip rows:%d, offset:%" PRId64, GET_QINFO_ADDR(pRuntimeEnv), blockInfo.rows,
4026 4027
             pQuery->limit.offset);
    } else {  // find the appropriated start position in current block
4028 4029 4030
      updateOffsetVal(pRuntimeEnv, &blockInfo);
      break;
    }
4031
  }
4032
}
4033

H
Haojun Liao 已提交
4034
static bool skipTimeInterval(SQueryRuntimeEnv *pRuntimeEnv, TSKEY* start) {
4035
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
Haojun Liao 已提交
4036
  *start = pQuery->current->lastKey;
4037

4038
  // if queried with value filter, do NOT forward query start position
4039
  if (pQuery->limit.offset <= 0 || pQuery->numOfFilterCols > 0 || pRuntimeEnv->pTSBuf != NULL || pRuntimeEnv->pFillInfo != NULL) {
4040
    return true;
4041
  }
4042

4043 4044 4045 4046 4047
  /*
   * 1. for interval without interpolation query we forward pQuery->intervalTime at a time for
   *    pQuery->limit.offset times. Since hole exists, pQuery->intervalTime*pQuery->limit.offset value is
   *    not valid. otherwise, we only forward pQuery->limit.offset number of points
   */
4048
  assert(pRuntimeEnv->windowResInfo.prevSKey == TSKEY_INITIAL_VAL);
4049

4050 4051 4052
  TSKEY       skey1, ekey1;
  STimeWindow w = TSWINDOW_INITIALIZER;
  
4053
  SWindowResInfo *pWindowResInfo = &pRuntimeEnv->windowResInfo;
H
hjxilinx 已提交
4054
  STableQueryInfo *pTableQueryInfo = pQuery->current;
4055

4056 4057
  while (tsdbNextDataBlock(pRuntimeEnv->pQueryHandle)) {
    SDataBlockInfo blockInfo = tsdbRetrieveDataBlockInfo(pRuntimeEnv->pQueryHandle);
4058

H
Haojun Liao 已提交
4059 4060 4061 4062 4063 4064 4065
    if (QUERY_IS_ASC_QUERY(pQuery)) {
      if (pWindowResInfo->prevSKey == TSKEY_INITIAL_VAL) {
        getAlignQueryTimeWindow(pQuery, blockInfo.window.skey, blockInfo.window.skey, pQuery->window.ekey, &skey1,
                                &ekey1, &w);
        pWindowResInfo->startTime = w.skey;
        pWindowResInfo->prevSKey = w.skey;
      }
4066 4067 4068
    } else {
      getAlignQueryTimeWindow(pQuery, blockInfo.window.ekey, pQuery->window.ekey, blockInfo.window.ekey, &skey1, &ekey1,
                              &w);
4069

4070 4071 4072
      pWindowResInfo->startTime = pQuery->window.skey;
      pWindowResInfo->prevSKey = w.skey;
    }
4073

4074 4075
    // the first time window
    STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQuery);
4076

4077 4078 4079 4080 4081 4082
    while (pQuery->limit.offset > 0) {
      if ((win.ekey <= blockInfo.window.ekey && QUERY_IS_ASC_QUERY(pQuery)) ||
          (win.ekey >= blockInfo.window.skey && !QUERY_IS_ASC_QUERY(pQuery))) {
        pQuery->limit.offset -= 1;
        pWindowResInfo->prevSKey = win.skey;
      }
4083

4084 4085
      STimeWindow tw = win;
      getNextTimeWindow(pQuery, &tw);
4086

4087
      if (pQuery->limit.offset == 0) {
4088 4089
        if ((tw.skey <= blockInfo.window.ekey && QUERY_IS_ASC_QUERY(pQuery)) ||
            (tw.ekey >= blockInfo.window.skey && !QUERY_IS_ASC_QUERY(pQuery))) {
H
Haojun Liao 已提交
4090 4091
          // load the data block and check data remaining in current data block
          // TODO optimize performance
4092 4093 4094
          SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pQueryHandle, NULL);
          SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);

4095 4096 4097
          tw = win;
          int32_t startPos =
              getNextQualifiedWindow(pRuntimeEnv, &tw, &blockInfo, pColInfoData->pData, binarySearchForKey);
4098 4099 4100 4101
          assert(startPos >= 0);

          // set the abort info
          pQuery->pos = startPos;
H
Haojun Liao 已提交
4102 4103 4104 4105 4106 4107
          
          // reset the query start timestamp
          pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
          pQuery->window.skey = pTableQueryInfo->win.skey;
          *start = pTableQueryInfo->win.skey;
          
4108
          pWindowResInfo->prevSKey = tw.skey;
H
Haojun Liao 已提交
4109 4110
          int32_t index = pRuntimeEnv->windowResInfo.curIndex;
          
H
hjxilinx 已提交
4111
          int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, &blockInfo, NULL, binarySearchForKey, pDataBlock);
H
Haojun Liao 已提交
4112 4113
          pRuntimeEnv->windowResInfo.curIndex = index;  // restore the window index
          
4114
          qTrace("QInfo:%p check data block, brange:%" PRId64 "-%" PRId64 ", rows:%d, numOfRes:%d",
4115 4116
                 GET_QINFO_ADDR(pRuntimeEnv), blockInfo.window.skey, blockInfo.window.ekey, blockInfo.rows, numOfRes);
          return true;
H
Haojun Liao 已提交
4117 4118 4119 4120
        } else { // do nothing
          *start = tw.skey;
          pQuery->window.skey = tw.skey;
          pWindowResInfo->prevSKey = tw.skey;
4121
          return true;
4122 4123 4124
        }
      }

H
Haojun Liao 已提交
4125 4126 4127 4128 4129 4130 4131
      /*
       * If the next time window still starts from current data block,
       * load the primary timestamp column first, and then find the start position for the next queried time window.
       * Note that only the primary timestamp column is required.
       * TODO: Optimize for this cases. All data blocks are not needed to be loaded, only if the first actually required
       * time window resides in current data block.
       */
4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143
      if ((tw.skey <= blockInfo.window.ekey && QUERY_IS_ASC_QUERY(pQuery)) ||
          (tw.ekey >= blockInfo.window.skey && !QUERY_IS_ASC_QUERY(pQuery))) {
        SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pQueryHandle, NULL);
        SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);

        tw = win;
        int32_t startPos =
            getNextQualifiedWindow(pRuntimeEnv, &tw, &blockInfo, pColInfoData->pData, binarySearchForKey);
        assert(startPos >= 0);

        // set the abort info
        pQuery->pos = startPos;
H
hjxilinx 已提交
4144
        pTableQueryInfo->lastKey = ((TSKEY *)pColInfoData->pData)[startPos];
4145 4146
        pWindowResInfo->prevSKey = tw.skey;
        win = tw;
4147
      } else {
H
Haojun Liao 已提交
4148
        break;  // offset is not 0, and next time window begins or ends in the next block.
4149 4150 4151
      }
    }
  }
4152

4153 4154 4155 4156
  return true;
}


B
Bomin Zhang 已提交
4157 4158
static void setupQueryHandle(void* tsdb, SQInfo* pQInfo, bool isSTableQuery) {
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
4159 4160
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;

B
Bomin Zhang 已提交
4161 4162 4163 4164 4165 4166 4167
  if (onlyQueryTags(pQuery)) {
    return;
  }

  if (isSTableQuery && (!isIntervalQuery(pQuery)) && (!isFixedOutputQuery(pQuery))) {
    return;
  }
4168 4169

  STsdbQueryCond cond = {
B
Bomin Zhang 已提交
4170 4171 4172 4173
    .twindow = pQuery->window,
    .order   = pQuery->order.order,
    .colList = pQuery->colList,
    .numOfCols = pQuery->numOfCols,
4174
  };
weixin_48148422's avatar
weixin_48148422 已提交
4175

B
Bomin Zhang 已提交
4176 4177 4178 4179 4180 4181 4182 4183 4184 4185
  if (!isSTableQuery
    && (pQInfo->groupInfo.numOfTables == 1)
    && (cond.order == TSDB_ORDER_ASC) 
    && (!isIntervalQuery(pQuery))
    && (!isGroupbyNormalCol(pQuery->pGroupbyExpr))
    && (!isFixedOutputQuery(pQuery))
  ) {
    SArray* pa = taosArrayGetP(pQInfo->groupInfo.pGroupList, 0);
    SGroupItem* pItem = taosArrayGet(pa, 0);
    cond.twindow = pItem->info->win;
4186
  }
B
Bomin Zhang 已提交
4187

H
Haojun Liao 已提交
4188 4189 4190 4191 4192
  if (isFirstLastRowQuery(pQuery)) {
    pRuntimeEnv->pQueryHandle = tsdbQueryLastRow(tsdb, &cond, &pQInfo->tableIdGroupInfo);
  } else {
    pRuntimeEnv->pQueryHandle = tsdbQueryTables(tsdb, &cond, &pQInfo->tableIdGroupInfo);
  }
B
Bomin Zhang 已提交
4193 4194 4195
}


4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216
static SFillColInfo* taosCreateFillColInfo(SQuery* pQuery) {
  int32_t numOfCols = pQuery->numOfOutput;
  int32_t offset = 0;
  
  SFillColInfo* pFillCol = calloc(numOfCols, sizeof(SFillColInfo));
  for(int32_t i = 0; i < numOfCols; ++i) {
    SExprInfo* pExprInfo = &pQuery->pSelectExpr[i];
    
    pFillCol[i].col.bytes  = pExprInfo->bytes;
    pFillCol[i].col.type   = pExprInfo->type;
    pFillCol[i].col.offset = offset;
    pFillCol[i].flag       = TSDB_COL_NORMAL;    // always be ta normal column for table query
    pFillCol[i].functionId = pExprInfo->base.functionId;
    pFillCol[i].defaultVal.i = pQuery->defaultVal[i];
    
    offset += pExprInfo->bytes;
  }
  
  return pFillCol;
}

4217
int32_t doInitQInfo(SQInfo *pQInfo, void *param, void *tsdb, int32_t vgId, bool isSTableQuery) {
4218 4219 4220 4221 4222 4223 4224
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;

  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
  int32_t code = TSDB_CODE_SUCCESS;

  setScanLimitationByResultBuffer(pQuery);
  changeExecuteScanOrder(pQuery, false);
B
Bomin Zhang 已提交
4225
  setupQueryHandle(tsdb, pQInfo, isSTableQuery);
4226
  
4227
  pQInfo->tsdb = tsdb;
4228
  pQInfo->vgId = vgId;
4229 4230 4231

  pRuntimeEnv->pQuery = pQuery;
  pRuntimeEnv->pTSBuf = param;
4232
  pRuntimeEnv->cur.vgroupIndex = -1;
4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249
  pRuntimeEnv->stableQuery = isSTableQuery;

  if (param != NULL) {
    int16_t order = (pQuery->order.order == pRuntimeEnv->pTSBuf->tsOrder) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
    tsBufSetTraverseOrder(pRuntimeEnv->pTSBuf, order);
  }

  // create runtime environment
  code = setupQueryRuntimeEnv(pRuntimeEnv, pQuery->order.order);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  pRuntimeEnv->numOfRowsPerPage = getNumOfRowsInResultPage(pQuery, isSTableQuery);

  if (isSTableQuery) {
    int32_t rows = getInitialPageNum(pQInfo);
4250
    code = createDiskbasedResultBuffer(&pRuntimeEnv->pResultBuf, rows, pQuery->rowSize, pQInfo);
4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    if (pQuery->intervalTime == 0) {
      int16_t type = TSDB_DATA_TYPE_NULL;

      if (isGroupbyNormalCol(pQuery->pGroupbyExpr)) {  // group by columns not tags;
        type = getGroupbyColumnType(pQuery, pQuery->pGroupbyExpr);
      } else {
        type = TSDB_DATA_TYPE_INT;  // group id
      }

      initWindowResInfo(&pRuntimeEnv->windowResInfo, pRuntimeEnv, 512, 4096, type);
    }

  } else if (isGroupbyNormalCol(pQuery->pGroupbyExpr) || isIntervalQuery(pQuery)) {
    int32_t rows = getInitialPageNum(pQInfo);
4269
    code = createDiskbasedResultBuffer(&pRuntimeEnv->pResultBuf, rows, pQuery->rowSize, pQInfo);
4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    int16_t type = TSDB_DATA_TYPE_NULL;
    if (isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
      type = getGroupbyColumnType(pQuery, pQuery->pGroupbyExpr);
    } else {
      type = TSDB_DATA_TYPE_TIMESTAMP;
    }

    initWindowResInfo(&pRuntimeEnv->windowResInfo, pRuntimeEnv, rows, 4096, type);
  }

  setQueryStatus(pQuery, QUERY_NOT_COMPLETED);

H
hjxilinx 已提交
4286 4287
//  SPointInterpoSupporter interpInfo = {0};
//  pointInterpSupporterInit(pQuery, &interpInfo);
4288 4289

  /*
H
hjxilinx 已提交
4290 4291
   * in case of last_row query without query range, we set the query timestamp to be
   * STable->lastKey. Otherwise, keep the initial query time range unchanged.
4292
   */
H
hjxilinx 已提交
4293 4294 4295 4296 4297 4298 4299
//  if (isFirstLastRowQuery(pQuery)) {
//    if (!normalizeUnBoundLastRowQuery(pQInfo, &interpInfo)) {
//      sem_post(&pQInfo->dataReady);
//      pointInterpSupporterDestroy(&interpInfo);
//      return TSDB_CODE_SUCCESS;
//    }
//  }
4300 4301 4302 4303 4304

  /*
   * here we set the value for before and after the specified time into the
   * parameter for interpolation query
   */
H
hjxilinx 已提交
4305 4306
//  pointInterpSupporterSetData(pQInfo, &interpInfo);
//  pointInterpSupporterDestroy(&interpInfo);
4307

4308 4309 4310 4311 4312 4313
  if (pQuery->fillType != TSDB_FILL_NONE) {
    SFillColInfo* pColInfo = taosCreateFillColInfo(pQuery);
    pRuntimeEnv->pFillInfo = taosInitFillInfo(pQuery->order.order, 0, 0, pQuery->rec.capacity, pQuery->numOfOutput,
                                              pQuery->slidingTime, pQuery->fillType, pColInfo);
  }
  
4314 4315 4316
  return TSDB_CODE_SUCCESS;
}

4317
static UNUSED_FUNC bool isGroupbyEachTable(SSqlGroupbyExpr *pGroupbyExpr, STableGroupInfo *pSidset) {
4318 4319 4320
  if (pGroupbyExpr == NULL || pGroupbyExpr->numOfGroupCols == 0) {
    return false;
  }
4321

4322
  for (int32_t i = 0; i < pGroupbyExpr->numOfGroupCols; ++i) {
4323
    SColIndex* pColIndex = taosArrayGet(pGroupbyExpr->columnInfo, i);
4324 4325 4326 4327
    if (pColIndex->flag == TSDB_COL_TAG) {
      return true;
    }
  }
4328

4329 4330 4331
  return false;
}

4332
static void enableExecutionForNextTable(SQueryRuntimeEnv *pRuntimeEnv) {
4333
  SQuery *pQuery = pRuntimeEnv->pQuery;
4334

4335
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
4336 4337 4338 4339 4340 4341 4342
    SResultInfo *pResInfo = GET_RES_INFO(&pRuntimeEnv->pCtx[i]);
    if (pResInfo != NULL) {
      pResInfo->complete = false;
    }
  }
}

H
hjxilinx 已提交
4343
static int64_t queryOnDataBlocks(SQInfo *pQInfo) {
4344 4345
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;
4346

H
hjxilinx 已提交
4347
  int64_t st = taosGetTimestampMs();
4348

4349 4350
  TsdbQueryHandleT pQueryHandle = IS_MASTER_SCAN(pRuntimeEnv)? pRuntimeEnv->pQueryHandle : pRuntimeEnv->pSecQueryHandle;
  
4351
  while (tsdbNextDataBlock(pQueryHandle)) {
4352
    if (isQueryKilled(pQInfo)) {
4353 4354
      break;
    }
4355

4356
    SDataBlockInfo  blockInfo = tsdbRetrieveDataBlockInfo(pQueryHandle);
H
hjxilinx 已提交
4357
    STableQueryInfo *pTableQueryInfo = NULL;
4358

4359 4360
    // todo opt performance using hash table
    size_t numOfGroup = taosArrayGetSize(pQInfo->groupInfo.pGroupList);
4361 4362 4363
    for (int32_t i = 0; i < numOfGroup; ++i) {
      SArray *group = taosArrayGetP(pQInfo->groupInfo.pGroupList, i);

4364
      size_t num = taosArrayGetSize(group);
4365
      for (int32_t j = 0; j < num; ++j) {
H
hjxilinx 已提交
4366 4367
        SGroupItem *item = taosArrayGet(group, j);
        STableQueryInfo *pInfo = item->info;
4368

H
hjxilinx 已提交
4369 4370 4371 4372
        if (pInfo->id.tid == blockInfo.tid) {
          assert(pInfo->id.uid == blockInfo.uid);
          pTableQueryInfo = item->info;
          
4373 4374
          break;
        }
H
hjxilinx 已提交
4375
      }
H
hjxilinx 已提交
4376 4377 4378 4379
      
      if (pTableQueryInfo != NULL) {
        break;
      }
H
hjxilinx 已提交
4380
    }
H
hjxilinx 已提交
4381
  
4382
    assert(pTableQueryInfo != NULL);
4383
    restoreIntervalQueryRange(pRuntimeEnv, pTableQueryInfo);
4384

4385
    SDataStatis *pStatis = NULL;
H
hjxilinx 已提交
4386 4387
    
    SArray *pDataBlock = loadDataBlockOnDemand(pRuntimeEnv, pQueryHandle, &blockInfo, &pStatis);
4388

4389
    if (!isIntervalQuery(pQuery)) {
H
Haojun Liao 已提交
4390 4391
      int32_t step = QUERY_IS_ASC_QUERY(pQuery)? 1:-1;
      setExecutionContext(pQInfo, &pTableQueryInfo->id, pTableQueryInfo->groupIdx, blockInfo.window.ekey + step);
4392
    } else {  // interval query
H
Haojun Liao 已提交
4393
      TSKEY nextKey = blockInfo.window.skey;
H
hjxilinx 已提交
4394
      setIntervalQueryRange(pQInfo, nextKey);
H
hjxilinx 已提交
4395
      int32_t ret = setAdditionalInfo(pQInfo, &pTableQueryInfo->id, pTableQueryInfo);
4396

4397
      if (ret != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
4398 4399
        pQInfo->code = ret;
        return taosGetTimestampMs() - st;
4400 4401
      }
    }
4402

H
hjxilinx 已提交
4403
    stableApplyFunctionsOnBlock(pRuntimeEnv, pTableQueryInfo, &blockInfo, pStatis, pDataBlock, binarySearchForKey);
4404
  }
4405

H
hjxilinx 已提交
4406 4407
  int64_t et = taosGetTimestampMs();
  return et - st;
4408 4409
}

4410 4411
static bool multiTableMultioutputHelper(SQInfo *pQInfo, int32_t index) {
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
4412
  SQuery *          pQuery = pRuntimeEnv->pQuery;
4413

4414
  setQueryStatus(pQuery, QUERY_NOT_COMPLETED);
4415
  SArray *group = taosArrayGetP(pQInfo->groupInfo.pGroupList, 0);
H
hjxilinx 已提交
4416
  SGroupItem* item = taosArrayGet(group, index);
4417

H
hjxilinx 已提交
4418
  setTagVal(pRuntimeEnv, &item->id, pQInfo->tsdb);
4419

S
slguan 已提交
4420
  qTrace("QInfo:%p query on (%d): uid:%" PRIu64 ", tid:%d, qrange:%" PRId64 "-%" PRId64, pQInfo, index,
H
hjxilinx 已提交
4421
         item->id.uid, item->id.tid, item->info->lastKey, item->info->win.ekey);
4422

4423
  STsdbQueryCond cond = {
H
hjxilinx 已提交
4424 4425 4426
      .twindow   = {item->info->lastKey, item->info->win.ekey},
      .order     = pQuery->order.order,
      .colList   = pQuery->colList,
4427
      .numOfCols = pQuery->numOfCols,
4428
  };
4429

H
hjxilinx 已提交
4430
  // todo refactor
4431
  SArray *g1 = taosArrayInit(1, POINTER_BYTES);
H
hjxilinx 已提交
4432
  SArray *tx = taosArrayInit(1, sizeof(STableId));
4433

H
hjxilinx 已提交
4434
  taosArrayPush(tx, &item->info->id);
4435
  taosArrayPush(g1, &tx);
4436
  STableGroupInfo gp = {.numOfTables = 1, .pGroupList = g1};
4437

4438
  // include only current table
4439 4440 4441 4442 4443
  if (pRuntimeEnv->pQueryHandle != NULL) {
    tsdbCleanupQueryHandle(pRuntimeEnv->pQueryHandle);
    pRuntimeEnv->pQueryHandle = NULL;
  }
  
4444
  pRuntimeEnv->pQueryHandle = tsdbQueryTables(pQInfo->tsdb, &cond, &gp);
4445 4446 4447
  taosArrayDestroy(tx);
  taosArrayDestroy(g1);
  
4448
  if (pRuntimeEnv->pTSBuf != NULL) {
4449
    if (pRuntimeEnv->cur.vgroupIndex == -1) {
4450 4451
      int64_t tag = pRuntimeEnv->pCtx[0].tag.i64Key;
      STSElem elem = tsBufGetElemStartPos(pRuntimeEnv->pTSBuf, 0, tag);
4452

4453 4454 4455 4456 4457 4458 4459 4460
      // failed to find data with the specified tag value
      if (elem.vnode < 0) {
        return false;
      }
    } else {
      tsBufSetCursor(pRuntimeEnv->pTSBuf, &pRuntimeEnv->cur);
    }
  }
4461

4462
  initCtxOutputBuf(pRuntimeEnv);
4463 4464 4465 4466 4467 4468 4469 4470 4471 4472
  return true;
}

/**
 * super table query handler
 * 1. super table projection query, group-by on normal columns query, ts-comp query
 * 2. point interpolation query, last row query
 *
 * @param pQInfo
 */
4473
static void sequentialTableProcess(SQInfo *pQInfo) {
4474
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
4475
  SQuery *          pQuery = pRuntimeEnv->pQuery;
4476
  setQueryStatus(pQuery, QUERY_COMPLETED);
4477

4478
  size_t numOfGroups = taosArrayGetSize(pQInfo->groupInfo.pGroupList);
4479

4480 4481 4482
  if (isPointInterpoQuery(pQuery)) {
    resetCtxOutputBuf(pRuntimeEnv);
    assert(pQuery->limit.offset == 0 && pQuery->limit.limit != 0);
4483

4484 4485
    while (pQInfo->groupIndex < numOfGroups) {
      SArray* group = taosArrayGetP(pQInfo->groupInfo.pGroupList, pQInfo->groupIndex);
4486

4487
      if (isFirstLastRowQuery(pQuery)) {
4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500
        qTrace("QInfo:%p last_row query on group:%d, total group:%d, current group:%d", pQInfo, pQInfo->groupIndex,
               numOfGroups);
  
        STsdbQueryCond cond = {
            .twindow = pQuery->window,
            .colList = pQuery->colList,
            .order   = pQuery->order.order,
            .numOfCols = pQuery->numOfCols,
        };
  
        SArray *g1 = taosArrayInit(1, POINTER_BYTES);
        SArray *tx = taosArrayClone(group);
        taosArrayPush(g1, &tx);
4501
        
4502 4503 4504 4505 4506 4507
        STableGroupInfo gp = {.numOfTables = taosArrayGetSize(tx), .pGroupList = g1};
  
        // include only current table
        if (pRuntimeEnv->pQueryHandle != NULL) {
          tsdbCleanupQueryHandle(pRuntimeEnv->pQueryHandle);
          pRuntimeEnv->pQueryHandle = NULL;
4508 4509
        }
        
4510
        pRuntimeEnv->pQueryHandle = tsdbQueryLastRow(pQInfo->tsdb, &cond, &gp);
4511
        
4512 4513
        initCtxOutputBuf(pRuntimeEnv);
        setTagVal(pRuntimeEnv, (STableId*) taosArrayGet(tx, 0), pQInfo->tsdb);
H
hjxilinx 已提交
4514 4515
        
        // here we simply set the first table as current table
H
Haojun Liao 已提交
4516 4517
        pQuery->current = ((SGroupItem*) taosArrayGet(group, 0))->info;
        scanAllDataBlocks(pRuntimeEnv, pQuery->current->lastKey);
4518
        
4519 4520 4521 4522
        int64_t numOfRes = getNumOfResult(pRuntimeEnv);
        if (numOfRes > 0) {
          pQuery->rec.rows += numOfRes;
          forwardCtxOutputBuf(pRuntimeEnv, numOfRes);
4523
        }
4524 4525 4526 4527 4528 4529
        
        skipResults(pRuntimeEnv);
        pQInfo->groupIndex += 1;
  
        // enable execution for next table, when handling the projection query
        enableExecutionForNextTable(pRuntimeEnv);
4530 4531 4532 4533
      }
    }
  } else {
    /*
4534
     * 1. super table projection query, 2. group-by on normal columns query, 3. ts-comp query
4535 4536 4537
     * if the subgroup index is larger than 0, results generated by group by tbname,k is existed.
     * we need to return it to client in the first place.
     */
4538
    if (pQInfo->groupIndex > 0) {
4539
      copyFromWindowResToSData(pQInfo, pRuntimeEnv->windowResInfo.pResult);
4540
      pQuery->rec.total += pQuery->rec.rows;
4541

4542
      if (pQuery->rec.rows > 0) {
4543 4544 4545
        return;
      }
    }
4546

4547 4548
    // all data have returned already
    if (pQInfo->tableIndex >= pQInfo->groupInfo.numOfTables) {
4549 4550
      return;
    }
4551

4552 4553
    resetCtxOutputBuf(pRuntimeEnv);
    resetTimeWindowInfo(pRuntimeEnv, &pRuntimeEnv->windowResInfo);
4554 4555 4556 4557 4558

    SArray *group = taosArrayGetP(pQInfo->groupInfo.pGroupList, 0);
    assert(taosArrayGetSize(group) == pQInfo->groupInfo.numOfTables &&
           1 == taosArrayGetSize(pQInfo->groupInfo.pGroupList));

4559
    while (pQInfo->tableIndex < pQInfo->groupInfo.numOfTables) {
4560
      if (isQueryKilled(pQInfo)) {
4561 4562
        return;
      }
4563

H
hjxilinx 已提交
4564
      SGroupItem *item = taosArrayGet(group, pQInfo->tableIndex);
H
hjxilinx 已提交
4565
      pQuery->current = item->info;
H
hjxilinx 已提交
4566
      
4567
      if (!multiTableMultioutputHelper(pQInfo, pQInfo->tableIndex)) {
4568
        pQInfo->tableIndex++;
4569 4570
        continue;
      }
4571

H
hjxilinx 已提交
4572
      // TODO handle the limit offset problem
4573
      if (pQuery->numOfFilterCols == 0 && pQuery->limit.offset > 0) {
4574
        //        skipBlocks(pRuntimeEnv);
4575 4576
        if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
          pQInfo->tableIndex++;
4577 4578 4579
          continue;
        }
      }
4580

H
Haojun Liao 已提交
4581
      scanAllDataBlocks(pRuntimeEnv, pQuery->current->lastKey);
4582
      skipResults(pRuntimeEnv);
4583

4584
      // the limitation of output result is reached, set the query completed
4585
      if (limitResults(pQuery)) {
4586
        pQInfo->tableIndex = pQInfo->groupInfo.numOfTables;
4587 4588
        break;
      }
4589

4590 4591
      // enable execution for next table, when handling the projection query
      enableExecutionForNextTable(pRuntimeEnv);
4592

4593
      if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
4594 4595 4596 4597 4598 4599
        /*
         * query range is identical in terms of all meters involved in query,
         * so we need to restore them at the *beginning* of query on each meter,
         * not the consecutive query on meter on which is aborted due to buffer limitation
         * to ensure that, we can reset the query range once query on a meter is completed.
         */
4600
        pQInfo->tableIndex++;
weixin_48148422's avatar
weixin_48148422 已提交
4601 4602 4603 4604

        STableIdInfo tidInfo;
        tidInfo.uid = item->id.uid;
        tidInfo.tid = item->id.tid;
weixin_48148422's avatar
weixin_48148422 已提交
4605
        tidInfo.key = pQuery->current->lastKey;
weixin_48148422's avatar
weixin_48148422 已提交
4606 4607
        taosArrayPush(pQInfo->arrTableIdInfo, &tidInfo);

4608
        // if the buffer is full or group by each table, we need to jump out of the loop
4609 4610
        if (Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL) /*||
            isGroupbyEachTable(pQuery->pGroupbyExpr, pSupporter->pSidSet)*/) {
4611 4612
          break;
        }
4613

4614
      } else {
4615
        // all data in the result buffer are skipped due to the offset, continue to retrieve data from current meter
4616 4617
        if (pQuery->rec.rows == 0) {
          assert(!Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL));
4618 4619
          continue;
        } else {
4620 4621 4622
          // buffer is full, wait for the next round to retrieve data from current meter
          assert(Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL));
          break;
4623 4624 4625 4626
        }
      }
    }
  }
4627

4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639
  /*
   * 1. super table projection query, group-by on normal columns query, ts-comp query
   * 2. point interpolation query, last row query
   *
   * group-by on normal columns query and last_row query do NOT invoke the finalizer here,
   * since the finalize stage will be done at the client side.
   *
   * projection query, point interpolation query do not need the finalizer.
   *
   * Only the ts-comp query requires the finalizer function to be executed here.
   */
  if (isTSCompQuery(pQuery)) {
H
hjxilinx 已提交
4640
    finalizeQueryResult(pRuntimeEnv);
4641
  }
4642

4643 4644 4645
  if (pRuntimeEnv->pTSBuf != NULL) {
    pRuntimeEnv->cur = pRuntimeEnv->pTSBuf->cur;
  }
4646

4647 4648 4649
  // todo refactor
  if (isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
    SWindowResInfo *pWindowResInfo = &pRuntimeEnv->windowResInfo;
4650

4651 4652 4653
    for (int32_t i = 0; i < pWindowResInfo->size; ++i) {
      SWindowStatus *pStatus = &pWindowResInfo->pResult[i].status;
      pStatus->closed = true;  // enable return all results for group by normal columns
4654

4655
      SWindowResult *pResult = &pWindowResInfo->pResult[i];
4656
      for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
4657 4658 4659
        pResult->numOfRows = MAX(pResult->numOfRows, pResult->resultInfo[j].numOfRes);
      }
    }
4660

4661
    pQInfo->groupIndex = 0;
4662
    pQuery->rec.rows = 0;
4663 4664
    copyFromWindowResToSData(pQInfo, pWindowResInfo->pResult);
  }
4665 4666

  qTrace(
H
Haojun Liao 已提交
4667
      "QInfo %p numOfTables:%d, index:%d, numOfGroups:%d, %d points returned, total:%"PRId64", offset:%" PRId64,
4668 4669
      pQInfo, pQInfo->groupInfo.numOfTables, pQInfo->tableIndex, numOfGroups, pQuery->rec.rows, pQuery->rec.total,
      pQuery->limit.offset);
4670 4671
}

4672 4673 4674 4675
static void doSaveContext(SQInfo *pQInfo) {
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;

4676 4677 4678 4679
  SET_REVERSE_SCAN_FLAG(pRuntimeEnv);
  SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);
  SWITCH_ORDER(pQuery->order.order);
  
4680
  if (pRuntimeEnv->pTSBuf != NULL) {
4681
    pRuntimeEnv->pTSBuf->cur.order = pQuery->order.order;
4682
  }
4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700
  
  STsdbQueryCond cond = {
      .twindow = pQuery->window,
      .order   = pQuery->order.order,
      .colList = pQuery->colList,
      .numOfCols = pQuery->numOfCols,
  };
  
  // clean unused handle
  if (pRuntimeEnv->pSecQueryHandle != NULL) {
    tsdbCleanupQueryHandle(pRuntimeEnv->pSecQueryHandle);
  }
  
  pRuntimeEnv->pSecQueryHandle = tsdbQueryTables(pQInfo->tsdb, &cond, &pQInfo->tableIdGroupInfo);
  
  setQueryStatus(pQuery, QUERY_NOT_COMPLETED);
  switchCtxOrder(pRuntimeEnv);
  disableFuncInReverseScan(pQInfo);
H
hjxilinx 已提交
4701 4702
}

4703 4704 4705 4706
static void doRestoreContext(SQInfo *pQInfo) {
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;

H
hjxilinx 已提交
4707
  SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);
4708

4709
  if (pRuntimeEnv->pTSBuf != NULL) {
4710
    SWITCH_ORDER(pRuntimeEnv->pTSBuf->cur.order);
4711
  }
4712

4713
  switchCtxOrder(pRuntimeEnv);
4714 4715 4716
  SET_MASTER_SCAN_FLAG(pRuntimeEnv);
}

4717 4718 4719
static void doCloseAllTimeWindowAfterScan(SQInfo *pQInfo) {
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;

H
hjxilinx 已提交
4720
  if (isIntervalQuery(pQuery)) {
4721
    size_t numOfGroup = taosArrayGetSize(pQInfo->groupInfo.pGroupList);
4722 4723 4724
    for (int32_t i = 0; i < numOfGroup; ++i) {
      SArray *group = taosArrayGetP(pQInfo->groupInfo.pGroupList, i);

4725
      size_t num = taosArrayGetSize(group);
4726
      for (int32_t j = 0; j < num; ++j) {
H
hjxilinx 已提交
4727 4728
        SGroupItem* item = taosArrayGet(group, j);
        closeAllTimeWindow(&item->info->windowResInfo);
4729
      }
H
hjxilinx 已提交
4730 4731 4732 4733 4734 4735 4736
    }
  } else {  // close results for group result
    closeAllTimeWindow(&pQInfo->runtimeEnv.windowResInfo);
  }
}

static void multiTableQueryProcess(SQInfo *pQInfo) {
4737 4738 4739
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;

4740
  if (pQInfo->groupIndex > 0) {
4741
    /*
4742
     * if the groupIndex > 0, the query process must be completed yet, we only need to
4743 4744
     * copy the data into output buffer
     */
H
hjxilinx 已提交
4745
    if (isIntervalQuery(pQuery)) {
4746 4747 4748
      copyResToQueryResultBuf(pQInfo, pQuery);

#ifdef _DEBUG_VIEW
4749
      displayInterResult(pQuery->sdata, pRuntimeEnv, pQuery->sdata[0]->num);
4750 4751 4752 4753
#endif
    } else {
      copyFromWindowResToSData(pQInfo, pRuntimeEnv->windowResInfo.pResult);
    }
4754

4755
    if (pQuery->rec.rows == 0) {
4756
      //      vnodePrintQueryStatistics(pSupporter);
4757
    }
4758

S
slguan 已提交
4759
    qTrace("QInfo:%p current:%lld, total:%lld", pQInfo, pQuery->rec.rows, pQuery->rec.total);
4760 4761
    return;
  }
4762 4763 4764 4765

  qTrace("QInfo:%p query start, qrange:%" PRId64 "-%" PRId64 ", order:%d, forward scan start", pQInfo,
         pQuery->window.skey, pQuery->window.ekey, pQuery->order.order);

H
hjxilinx 已提交
4766 4767
  // do check all qualified data blocks
  int64_t el = queryOnDataBlocks(pQInfo);
H
hjxilinx 已提交
4768
  qTrace("QInfo:%p master scan completed, elapsed time: %lldms, reverse scan start", pQInfo, el);
4769

H
hjxilinx 已提交
4770 4771
  // query error occurred or query is killed, abort current execution
  if (pQInfo->code != TSDB_CODE_SUCCESS || isQueryKilled(pQInfo)) {
S
slguan 已提交
4772
    qTrace("QInfo:%p query killed or error occurred, code:%d, abort", pQInfo, pQInfo->code);
H
hjxilinx 已提交
4773
    return;
4774
  }
4775

H
hjxilinx 已提交
4776 4777
  // close all time window results
  doCloseAllTimeWindowAfterScan(pQInfo);
4778

H
hjxilinx 已提交
4779 4780
  if (needReverseScan(pQuery)) {
    doSaveContext(pQInfo);
4781

H
hjxilinx 已提交
4782
    el = queryOnDataBlocks(pQInfo);
S
slguan 已提交
4783
    qTrace("QInfo:%p reversed scan completed, elapsed time: %lldms", pQInfo, el);
4784

H
hjxilinx 已提交
4785 4786
    doRestoreContext(pQInfo);
  } else {
S
slguan 已提交
4787
    qTrace("QInfo:%p no need to do reversed scan, query completed", pQInfo);
4788
  }
4789

4790
  setQueryStatus(pQuery, QUERY_COMPLETED);
4791

H
hjxilinx 已提交
4792
  if (pQInfo->code != TSDB_CODE_SUCCESS || isQueryKilled(pQInfo)) {
S
slguan 已提交
4793
    qTrace("QInfo:%p query killed or error occurred, code:%d, abort", pQInfo, pQInfo->code);
H
hjxilinx 已提交
4794 4795
    return;
  }
4796

H
hjxilinx 已提交
4797
  if (isIntervalQuery(pQuery) || isSumAvgRateQuery(pQuery)) {
4798
    if (mergeIntoGroupResult(pQInfo) == TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
4799
      copyResToQueryResultBuf(pQInfo, pQuery);
4800 4801

#ifdef _DEBUG_VIEW
4802
      displayInterResult(pQuery->sdata, pRuntimeEnv, pQuery->sdata[0]->num);
4803 4804 4805 4806 4807
#endif
    }
  } else {  // not a interval query
    copyFromWindowResToSData(pQInfo, pRuntimeEnv->windowResInfo.pResult);
  }
4808

4809
  // handle the limitation of output buffer
S
slguan 已提交
4810
  qTrace("QInfo:%p points returned:%d, total:%d", pQInfo, pQuery->rec.rows, pQuery->rec.total + pQuery->rec.rows);
4811 4812 4813 4814 4815 4816 4817 4818
}

/*
 * in each query, this function will be called only once, no retry for further result.
 *
 * select count(*)/top(field,k)/avg(field name) from table_name [where ts>now-1a];
 * select count(*) from table_name group by status_column;
 */
H
hjxilinx 已提交
4819
static void tableFixedOutputProcess(SQInfo *pQInfo, STableQueryInfo* pTableInfo) {
4820
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
H
hjxilinx 已提交
4821 4822
  
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
Haojun Liao 已提交
4823 4824 4825 4826
  if (!isTopBottomQuery(pQuery) && pQuery->limit.offset > 0) {  // no need to execute, since the output will be ignore.
    return;
  }
  
H
hjxilinx 已提交
4827 4828
  pQuery->current = pTableInfo;  // set current query table info
  
H
Haojun Liao 已提交
4829
  scanAllDataBlocks(pRuntimeEnv, pTableInfo->lastKey);
H
hjxilinx 已提交
4830
  finalizeQueryResult(pRuntimeEnv);
4831

4832
  if (isQueryKilled(pQInfo)) {
4833 4834
    return;
  }
4835

H
Haojun Liao 已提交
4836
  // since the numOfRows must be identical for all sql functions that are allowed to be executed simutaneously.
4837
  pQuery->rec.rows = getNumOfResult(pRuntimeEnv);
4838

4839
  skipResults(pRuntimeEnv);
4840
  limitResults(pQuery);
4841 4842
}

H
hjxilinx 已提交
4843
static void tableMultiOutputProcess(SQInfo *pQInfo, STableQueryInfo* pTableInfo) {
4844
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
H
hjxilinx 已提交
4845 4846 4847 4848
  
  SQuery *pQuery = pRuntimeEnv->pQuery;
  pQuery->current = pTableInfo;
  
4849 4850 4851 4852
  // for ts_comp query, re-initialized is not allowed
  if (!isTSCompQuery(pQuery)) {
    resetCtxOutputBuf(pRuntimeEnv);
  }
4853

4854 4855 4856 4857 4858 4859
  // skip blocks without load the actual data block from file if no filter condition present
  skipBlocks(&pQInfo->runtimeEnv);
  if (pQuery->limit.offset > 0 && pQuery->numOfFilterCols == 0) {
    setQueryStatus(pQuery, QUERY_COMPLETED);
    return;
  }
4860 4861

  while (1) {
H
Haojun Liao 已提交
4862
    scanAllDataBlocks(pRuntimeEnv, pQuery->current->lastKey);
H
hjxilinx 已提交
4863
    finalizeQueryResult(pRuntimeEnv);
4864

4865
    if (isQueryKilled(pQInfo)) {
4866 4867 4868
      return;
    }

4869 4870
    pQuery->rec.rows = getNumOfResult(pRuntimeEnv);
    if (pQuery->limit.offset > 0 && pQuery->numOfFilterCols > 0 && pQuery->rec.rows > 0) {
4871
      skipResults(pRuntimeEnv);
4872 4873 4874
    }

    /*
H
hjxilinx 已提交
4875 4876
     * 1. if pQuery->size == 0, pQuery->limit.offset >= 0, still need to check data
     * 2. if pQuery->size > 0, pQuery->limit.offset must be 0
4877
     */
4878
    if (pQuery->rec.rows > 0 || Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
4879 4880 4881
      break;
    }

S
slguan 已提交
4882
    qTrace("QInfo:%p vid:%d sid:%d id:%s, skip current result, offset:%" PRId64 ", next qrange:%" PRId64 "-%" PRId64,
H
hjxilinx 已提交
4883
           pQInfo, pQuery->limit.offset, pQuery->current->lastKey);
4884 4885 4886 4887

    resetCtxOutputBuf(pRuntimeEnv);
  }

4888
  limitResults(pQuery);
4889
  if (Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL)) {
H
hjxilinx 已提交
4890 4891
    qTrace("QInfo:%p query paused due to output limitation, next qrange:%" PRId64 "-%" PRId64, pQInfo,
        pQuery->current->lastKey, pQuery->window.ekey);
weixin_48148422's avatar
weixin_48148422 已提交
4892 4893 4894 4895 4896 4897
  } else if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
    STableIdInfo tidInfo;
    tidInfo.uid = pQuery->current->id.uid;
    tidInfo.tid = pQuery->current->id.tid;
    tidInfo.key = pQuery->current->lastKey;
    taosArrayPush(pQInfo->arrTableIdInfo, &tidInfo);
4898 4899
  }

4900 4901 4902
  if (!isTSCompQuery(pQuery)) {
    assert(pQuery->rec.rows <= pQuery->rec.capacity);
  }
4903 4904
}

H
Haojun Liao 已提交
4905
static void tableIntervalProcessImpl(SQueryRuntimeEnv *pRuntimeEnv, TSKEY start) {
4906
  SQuery *pQuery = pRuntimeEnv->pQuery;
4907

4908
  while (1) {
H
Haojun Liao 已提交
4909
    scanAllDataBlocks(pRuntimeEnv, start);
4910

4911
    if (isQueryKilled(GET_QINFO_ADDR(pRuntimeEnv))) {
4912 4913
      return;
    }
4914

4915
    assert(!Q_STATUS_EQUAL(pQuery->status, QUERY_NOT_COMPLETED));
H
hjxilinx 已提交
4916
    finalizeQueryResult(pRuntimeEnv);
4917

4918 4919 4920
    // here we can ignore the records in case of no interpolation
    // todo handle offset, in case of top/bottom interval query
    if ((pQuery->numOfFilterCols > 0 || pRuntimeEnv->pTSBuf != NULL) && pQuery->limit.offset > 0 &&
4921
        pQuery->fillType == TSDB_FILL_NONE) {
4922 4923
      // maxOutput <= 0, means current query does not generate any results
      int32_t numOfClosed = numOfClosedTimeWindow(&pRuntimeEnv->windowResInfo);
4924

4925 4926 4927 4928
      int32_t c = MIN(numOfClosed, pQuery->limit.offset);
      clearFirstNTimeWindow(pRuntimeEnv, c);
      pQuery->limit.offset -= c;
    }
4929

4930
    if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED | QUERY_RESBUF_FULL)) {
4931 4932 4933 4934 4935
      break;
    }
  }
}

4936
// handle time interval query on table
H
hjxilinx 已提交
4937
static void tableIntervalProcess(SQInfo *pQInfo, STableQueryInfo* pTableInfo) {
4938 4939
  SQueryRuntimeEnv *pRuntimeEnv = &(pQInfo->runtimeEnv);

H
hjxilinx 已提交
4940 4941
  SQuery *pQuery = pRuntimeEnv->pQuery;
  pQuery->current = pTableInfo;
4942

H
Haojun Liao 已提交
4943 4944 4945
  int32_t numOfInterpo = 0;
  TSKEY newStartKey = TSKEY_INITIAL_VAL;
  
4946
  // skip blocks without load the actual data block from file if no filter condition present
H
Haojun Liao 已提交
4947
  skipTimeInterval(pRuntimeEnv, &newStartKey);
4948
  if (pQuery->limit.offset > 0 && pQuery->numOfFilterCols == 0 && pRuntimeEnv->pFillInfo == NULL) {
4949 4950 4951 4952
    setQueryStatus(pQuery, QUERY_COMPLETED);
    return;
  }

4953
  while (1) {
H
Haojun Liao 已提交
4954
    tableIntervalProcessImpl(pRuntimeEnv, newStartKey);
4955

H
hjxilinx 已提交
4956
    if (isIntervalQuery(pQuery)) {
4957
      pQInfo->groupIndex = 0;  // always start from 0
4958
      pQuery->rec.rows = 0;
4959
      copyFromWindowResToSData(pQInfo, pRuntimeEnv->windowResInfo.pResult);
4960

4961
      clearFirstNTimeWindow(pRuntimeEnv, pQInfo->groupIndex);
4962
    }
4963

4964
    // the offset is handled at prepare stage if no interpolation involved
4965
    if (pQuery->fillType == TSDB_FILL_NONE || pQuery->rec.rows == 0) {
4966
      limitResults(pQuery);
4967 4968
      break;
    } else {
4969 4970 4971 4972
      TSKEY ekey = taosGetRevisedEndKey(pQuery->window.ekey, pQuery->order.order, pQuery->slidingTime,
                                        pQuery->slidingTimeUnit, pQuery->precision);
      taosFillSetStartInfo(pRuntimeEnv->pFillInfo, pQuery->rec.rows, ekey);
      taosFillCopyInputDataFromFilePage(pRuntimeEnv->pFillInfo, (tFilePage**) pQuery->sdata);
4973
      numOfInterpo = 0;
4974
      pQuery->rec.rows = doFillGapsInResults(pRuntimeEnv, (tFilePage **)pQuery->sdata, pQuery->rec.rows, &numOfInterpo);
4975

4976
      qTrace("QInfo: %p fill results completed, final:%d", pQInfo, pQuery->rec.rows);
4977
      if (pQuery->rec.rows > 0 || Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
4978
        limitResults(pQuery);
4979 4980
        break;
      }
4981

4982
      // no result generated yet, continue retrieve data
4983
      pQuery->rec.rows = 0;
4984 4985
    }
  }
4986

4987 4988
  // all data scanned, the group by normal column can return
  if (isGroupbyNormalCol(pQuery->pGroupbyExpr)) {  // todo refactor with merge interval time result
4989
    pQInfo->groupIndex = 0;
4990
    pQuery->rec.rows = 0;
4991
    copyFromWindowResToSData(pQInfo, pRuntimeEnv->windowResInfo.pResult);
4992
    clearFirstNTimeWindow(pRuntimeEnv, pQInfo->groupIndex);
4993
  }
4994

4995 4996 4997
  pQInfo->pointsInterpo += numOfInterpo;
}

4998 4999 5000 5001
static void tableQueryImpl(SQInfo *pQInfo) {
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;

5002
  if (queryHasRemainResults(pRuntimeEnv)) {
5003 5004 5005 5006 5007
    /*
     * There are remain results that are not returned due to result interpolation
     * So, we do keep in this procedure instead of launching retrieve procedure for next results.
     */
    int32_t numOfInterpo = 0;
5008 5009 5010 5011 5012
    int32_t remain = taosNumOfRemainRows(pRuntimeEnv->pFillInfo);
    pQuery->rec.rows = doFillGapsInResults(pRuntimeEnv, (tFilePage **)pQuery->sdata, remain, &numOfInterpo);
  
    qTrace("QInfo: %p fill results completed, final:%d", pQInfo, pQuery->rec.rows);
    if (pQuery->rec.rows > 0) {
5013
      limitResults(pQuery);
5014 5015
    }
    
S
slguan 已提交
5016
    qTrace("QInfo:%p current:%d returned, total:%d", pQInfo, pQuery->rec.rows, pQuery->rec.total);
5017 5018
    return;
  }
5019

5020
  // here we have scan all qualified data in both data file and cache
H
hjxilinx 已提交
5021
  if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
5022 5023
    // continue to get push data from the group result
    if (isGroupbyNormalCol(pQuery->pGroupbyExpr) ||
5024
        ((isIntervalQuery(pQuery) && pQuery->rec.total < pQuery->limit.limit))) {
5025
      // todo limit the output for interval query?
5026
      pQuery->rec.rows = 0;
5027
      pQInfo->groupIndex = 0;  // always start from 0
5028

5029 5030
      if (pRuntimeEnv->windowResInfo.size > 0) {
        copyFromWindowResToSData(pQInfo, pRuntimeEnv->windowResInfo.pResult);
5031
        pQuery->rec.rows += pQuery->rec.rows;
5032

5033
        clearFirstNTimeWindow(pRuntimeEnv, pQInfo->groupIndex);
5034

5035
        if (pQuery->rec.rows > 0) {
S
slguan 已提交
5036
          qTrace("QInfo:%p %d rows returned from group results, total:%d", pQInfo, pQuery->rec.rows, pQuery->rec.total);
5037 5038 5039 5040
          return;
        }
      }
    }
5041

S
slguan 已提交
5042
    qTrace("QInfo:%p query over, %d rows are returned", pQInfo, pQuery->rec.total);
5043
    //    vnodePrintQueryStatistics(pSupporter);
5044 5045
    return;
  }
5046

H
hjxilinx 已提交
5047
  // number of points returned during this query
5048
  pQuery->rec.rows = 0;
5049
  int64_t st = taosGetTimestampUs();
H
hjxilinx 已提交
5050 5051 5052 5053 5054
  
  assert(pQInfo->groupInfo.numOfTables == 1);
  SArray* g = taosArrayGetP(pQInfo->groupInfo.pGroupList, 0);
  SGroupItem* item = taosArrayGet(g, 0);
  
5055
  // group by normal column, sliding window query, interval query are handled by interval query processor
H
[td-98]  
hjxilinx 已提交
5056
  if (isIntervalQuery(pQuery) || isGroupbyNormalCol(pQuery->pGroupbyExpr)) {  // interval (down sampling operation)
H
hjxilinx 已提交
5057
    tableIntervalProcess(pQInfo, item->info);
5058
  } else if (isFixedOutputQuery(pQuery)) {
H
hjxilinx 已提交
5059
    tableFixedOutputProcess(pQInfo, item->info);
5060 5061
  } else {  // diff/add/multiply/subtract/division
    assert(pQuery->checkBuffer == 1);
H
hjxilinx 已提交
5062
    tableMultiOutputProcess(pQInfo, item->info);
5063
  }
5064

5065 5066
  // record the total elapsed time
  pQInfo->elapsedTime += (taosGetTimestampUs() - st);
5067
  assert(pQInfo->groupInfo.numOfTables == 1);
5068

5069
  /* check if query is killed or not */
5070
  if (isQueryKilled(pQInfo)) {
S
slguan 已提交
5071
    qTrace("QInfo:%p query is killed", pQInfo);
H
hjxilinx 已提交
5072 5073 5074
  } else {// todo set the table uid and tid in log
    qTrace("QInfo:%p query paused, %" PRId64 " rows returned, numOfTotal:%" PRId64 " rows",
        pQInfo, pQuery->rec.rows, pQuery->rec.total + pQuery->rec.rows);
5075 5076 5077
  }
}

5078 5079
static void stableQueryImpl(SQInfo *pQInfo) {
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
5080
  pQuery->rec.rows = 0;
5081

5082
  int64_t st = taosGetTimestampUs();
5083

H
hjxilinx 已提交
5084
  if (isIntervalQuery(pQuery) ||
5085
      (isFixedOutputQuery(pQuery) && (!isPointInterpoQuery(pQuery)) && !isGroupbyNormalCol(pQuery->pGroupbyExpr))) {
H
hjxilinx 已提交
5086
    multiTableQueryProcess(pQInfo);
5087
  } else {
5088
    assert((pQuery->checkBuffer == 1 && pQuery->intervalTime == 0) || isPointInterpoQuery(pQuery) ||
5089 5090
           isGroupbyNormalCol(pQuery->pGroupbyExpr));

5091
    sequentialTableProcess(pQInfo);
5092
  }
5093

H
hjxilinx 已提交
5094
  // record the total elapsed time
5095
  pQInfo->elapsedTime += (taosGetTimestampUs() - st);
5096
  //  taosFillSetStartInfo(&pQInfo->runtimeEnv.pFillInfo, pQuery->size, pQInfo->query.fillType);
5097

5098
  if (pQuery->rec.rows == 0) {
5099 5100 5101
    qTrace("QInfo:%p over, %d tables queried, %d points are returned", pQInfo, pQInfo->groupInfo.numOfTables,
           pQuery->rec.total);
    //    vnodePrintQueryStatistics(pSupporter);
5102
  }
H
hjxilinx 已提交
5103 5104
}

5105
static int32_t getColumnIndexInSource(SQueryTableMsg *pQueryMsg, SSqlFuncMsg *pExprMsg, SColumnInfo* pTagCols) {
5106
  int32_t j = 0;
5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123
  
  if (TSDB_COL_IS_TAG(pExprMsg->colInfo.flag)) {
    while(j < pQueryMsg->numOfTags) {
      if (pExprMsg->colInfo.colId == pTagCols[j].colId) {
        return j;
      }
      
      j += 1;
    }
    
  } else {
    while (j < pQueryMsg->numOfCols) {
      if (pExprMsg->colInfo.colId == pQueryMsg->colList[j].colId) {
        return j;
      }
    
      j += 1;
5124 5125 5126
    }
  }

5127
  assert(0);
5128 5129
}

5130 5131 5132
bool validateExprColumnInfo(SQueryTableMsg *pQueryMsg, SSqlFuncMsg *pExprMsg, SColumnInfo* pTagCols) {
  int32_t j = getColumnIndexInSource(pQueryMsg, pExprMsg, pTagCols);
  return j < pQueryMsg->numOfCols || j < pQueryMsg->numOfTags;
5133 5134
}

5135
static bool validateQueryMsg(SQueryTableMsg *pQueryMsg) {
H
hjxilinx 已提交
5136
  if (pQueryMsg->intervalTime < 0) {
5137
    qError("qmsg:%p illegal value of interval time %" PRId64, pQueryMsg, pQueryMsg->intervalTime);
5138
    return false;
5139 5140
  }

H
hjxilinx 已提交
5141
  if (pQueryMsg->numOfTables <= 0) {
S
slguan 已提交
5142
    qError("qmsg:%p illegal value of numOfTables %d", pQueryMsg, pQueryMsg->numOfTables);
5143
    return false;
5144 5145
  }

H
hjxilinx 已提交
5146
  if (pQueryMsg->numOfGroupCols < 0) {
S
slguan 已提交
5147
    qError("qmsg:%p illegal value of numOfGroupbyCols %d", pQueryMsg, pQueryMsg->numOfGroupCols);
5148
    return false;
5149 5150
  }

5151 5152
  if (pQueryMsg->numOfOutput > TSDB_MAX_COLUMNS || pQueryMsg->numOfOutput <= 0) {
    qError("qmsg:%p illegal value of output columns %d", pQueryMsg, pQueryMsg->numOfOutput);
5153
    return false;
5154 5155
  }

5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172
  return true;
}

static bool validateQuerySourceCols(SQueryTableMsg *pQueryMsg, SSqlFuncMsg** pExprMsg) {
  int32_t numOfTotal = pQueryMsg->numOfCols + pQueryMsg->numOfTags;
  if (pQueryMsg->numOfCols < 0 || pQueryMsg->numOfTags < 0 || numOfTotal > TSDB_MAX_COLUMNS) {
    qError("qmsg:%p illegal value of numOfCols %d numOfTags:%d", pQueryMsg, pQueryMsg->numOfCols, pQueryMsg->numOfTags);
    return false;
  } else if (numOfTotal == 0) {
    for(int32_t i = 0; i < pQueryMsg->numOfOutput; ++i) {
      if (pExprMsg[i]->functionId != TSDB_FUNC_TAGPRJ) {
        return false;
      }
    }
  }
  
  return true;
5173 5174
}

5175
static char *createTableIdList(SQueryTableMsg *pQueryMsg, char *pMsg, SArray **pTableIdList) {
H
hjxilinx 已提交
5176
  assert(pQueryMsg->numOfTables > 0);
5177

weixin_48148422's avatar
weixin_48148422 已提交
5178
  *pTableIdList = taosArrayInit(pQueryMsg->numOfTables, sizeof(STableIdInfo));
5179

weixin_48148422's avatar
weixin_48148422 已提交
5180 5181
  for (int32_t j = 0; j < pQueryMsg->numOfTables; ++j) {
    STableIdInfo* pTableIdInfo = (STableIdInfo *)pMsg;
5182

5183
    pTableIdInfo->tid = htonl(pTableIdInfo->tid);
H
hjxilinx 已提交
5184 5185
    pTableIdInfo->uid = htobe64(pTableIdInfo->uid);
    pTableIdInfo->key = htobe64(pTableIdInfo->key);
5186

H
hjxilinx 已提交
5187 5188 5189
    taosArrayPush(*pTableIdList, pTableIdInfo);
    pMsg += sizeof(STableIdInfo);
  }
5190

H
hjxilinx 已提交
5191 5192
  return pMsg;
}
5193

5194
/**
H
hjxilinx 已提交
5195
 * pQueryMsg->head has been converted before this function is called.
5196
 *
H
hjxilinx 已提交
5197
 * @param pQueryMsg
5198 5199 5200 5201
 * @param pTableIdList
 * @param pExpr
 * @return
 */
5202
static int32_t convertQueryMsg(SQueryTableMsg *pQueryMsg, SArray **pTableIdList, SSqlFuncMsg ***pExpr,
weixin_48148422's avatar
weixin_48148422 已提交
5203
                               char **tagCond, char** tbnameCond, SColIndex **groupbyCols, SColumnInfo** tagCols) {
5204 5205 5206 5207 5208 5209 5210 5211
  pQueryMsg->numOfTables = htonl(pQueryMsg->numOfTables);

  pQueryMsg->window.skey = htobe64(pQueryMsg->window.skey);
  pQueryMsg->window.ekey = htobe64(pQueryMsg->window.ekey);
  pQueryMsg->intervalTime = htobe64(pQueryMsg->intervalTime);
  pQueryMsg->slidingTime = htobe64(pQueryMsg->slidingTime);
  pQueryMsg->limit = htobe64(pQueryMsg->limit);
  pQueryMsg->offset = htobe64(pQueryMsg->offset);
H
hjxilinx 已提交
5212

5213 5214 5215
  pQueryMsg->order = htons(pQueryMsg->order);
  pQueryMsg->orderColId = htons(pQueryMsg->orderColId);
  pQueryMsg->queryType = htons(pQueryMsg->queryType);
weixin_48148422's avatar
weixin_48148422 已提交
5216
  pQueryMsg->tagNameRelType = htons(pQueryMsg->tagNameRelType);
5217 5218

  pQueryMsg->numOfCols = htons(pQueryMsg->numOfCols);
5219
  pQueryMsg->numOfOutput = htons(pQueryMsg->numOfOutput);
H
hjxilinx 已提交
5220
  pQueryMsg->numOfGroupCols = htons(pQueryMsg->numOfGroupCols);
5221 5222 5223
  pQueryMsg->tagCondLen = htons(pQueryMsg->tagCondLen);
  pQueryMsg->tsOffset = htonl(pQueryMsg->tsOffset);
  pQueryMsg->tsLen = htonl(pQueryMsg->tsLen);
H
hjxilinx 已提交
5224
  pQueryMsg->tsNumOfBlocks = htonl(pQueryMsg->tsNumOfBlocks);
5225
  pQueryMsg->tsOrder = htonl(pQueryMsg->tsOrder);
5226
  pQueryMsg->numOfTags = htonl(pQueryMsg->numOfTags);
5227

5228
  // query msg safety check
5229
  if (!validateQueryMsg(pQueryMsg)) {
5230 5231 5232
    return TSDB_CODE_INVALID_QUERY_MSG;
  }

H
hjxilinx 已提交
5233
  char *pMsg = (char *)(pQueryMsg->colList) + sizeof(SColumnInfo) * pQueryMsg->numOfCols;
5234

H
hjxilinx 已提交
5235
  for (int32_t col = 0; col < pQueryMsg->numOfCols; ++col) {
5236 5237
    SColumnInfo *pColInfo = &pQueryMsg->colList[col];

H
hjxilinx 已提交
5238
    pColInfo->colId = htons(pColInfo->colId);
5239
    pColInfo->type = htons(pColInfo->type);
H
hjxilinx 已提交
5240 5241
    pColInfo->bytes = htons(pColInfo->bytes);
    pColInfo->numOfFilters = htons(pColInfo->numOfFilters);
5242

H
hjxilinx 已提交
5243
    assert(pColInfo->type >= TSDB_DATA_TYPE_BOOL && pColInfo->type <= TSDB_DATA_TYPE_NCHAR);
5244

H
hjxilinx 已提交
5245
    int32_t numOfFilters = pColInfo->numOfFilters;
5246
    if (numOfFilters > 0) {
H
hjxilinx 已提交
5247
      pColInfo->filters = calloc(numOfFilters, sizeof(SColumnFilterInfo));
5248 5249 5250
    }

    for (int32_t f = 0; f < numOfFilters; ++f) {
5251 5252 5253 5254
      SColumnFilterInfo *pFilterMsg = (SColumnFilterInfo *)pMsg;
      
      SColumnFilterInfo *pColFilter = &pColInfo->filters[f];
      pColFilter->filterstr = htons(pFilterMsg->filterstr);
5255 5256 5257

      pMsg += sizeof(SColumnFilterInfo);

5258 5259
      if (pColFilter->filterstr) {
        pColFilter->len = htobe64(pFilterMsg->len);
5260

5261 5262 5263
        pColFilter->pz = (int64_t) calloc(1, pColFilter->len);
        memcpy((void *)pColFilter->pz, pMsg, pColFilter->len);
        pMsg += (pColFilter->len + 1);
5264
      } else {
5265 5266
        pColFilter->lowerBndi = htobe64(pFilterMsg->lowerBndi);
        pColFilter->upperBndi = htobe64(pFilterMsg->upperBndi);
5267 5268
      }

5269 5270
      pColFilter->lowerRelOptr = htons(pFilterMsg->lowerRelOptr);
      pColFilter->upperRelOptr = htons(pFilterMsg->upperRelOptr);
5271 5272 5273
    }
  }

5274 5275
  *pExpr = calloc(pQueryMsg->numOfOutput, POINTER_BYTES);
  SSqlFuncMsg *pExprMsg = (SSqlFuncMsg *)pMsg;
5276

5277
  for (int32_t i = 0; i < pQueryMsg->numOfOutput; ++i) {
5278
    (*pExpr)[i] = pExprMsg;
5279

5280
    pExprMsg->colInfo.colIndex = htons(pExprMsg->colInfo.colIndex);
5281 5282 5283 5284
    pExprMsg->colInfo.colId = htons(pExprMsg->colInfo.colId);
    pExprMsg->colInfo.flag = htons(pExprMsg->colInfo.flag);
    pExprMsg->functionId = htons(pExprMsg->functionId);
    pExprMsg->numOfParams = htons(pExprMsg->numOfParams);
5285

5286
    pMsg += sizeof(SSqlFuncMsg);
5287 5288

    for (int32_t j = 0; j < pExprMsg->numOfParams; ++j) {
5289
      pExprMsg->arg[j].argType = htons(pExprMsg->arg[j].argType);
5290 5291 5292 5293
      pExprMsg->arg[j].argBytes = htons(pExprMsg->arg[j].argBytes);

      if (pExprMsg->arg[j].argType == TSDB_DATA_TYPE_BINARY) {
        pExprMsg->arg[j].argValue.pz = pMsg;
5294
        pMsg += pExprMsg->arg[j].argBytes;  // one more for the string terminated char.
5295 5296 5297 5298 5299
      } else {
        pExprMsg->arg[j].argValue.i64 = htobe64(pExprMsg->arg[j].argValue.i64);
      }
    }

5300
    if (pExprMsg->functionId == TSDB_FUNC_TAG || pExprMsg->functionId == TSDB_FUNC_TAGPRJ ||
5301 5302 5303 5304 5305
               pExprMsg->functionId == TSDB_FUNC_TAG_DUMMY) {
      if (pExprMsg->colInfo.flag != TSDB_COL_TAG) {  // ignore the column  index check for arithmetic expression.
        return TSDB_CODE_INVALID_QUERY_MSG;
      }
    } else {
5306 5307 5308
//      if (!validateExprColumnInfo(pQueryMsg, pExprMsg)) {
//        return TSDB_CODE_INVALID_QUERY_MSG;
//      }
5309 5310
    }

5311
    pExprMsg = (SSqlFuncMsg *)pMsg;
5312
  }
5313 5314 5315 5316 5317 5318
  
  if (!validateQuerySourceCols(pQueryMsg, *pExpr)) {
    tfree(*pExpr);
    
    return TSDB_CODE_INVALID_QUERY_MSG;
  }
5319

H
hjxilinx 已提交
5320
  pMsg = createTableIdList(pQueryMsg, pMsg, pTableIdList);
5321

H
hjxilinx 已提交
5322
  if (pQueryMsg->numOfGroupCols > 0) {  // group by tag columns
5323 5324 5325 5326
    *groupbyCols = malloc(pQueryMsg->numOfGroupCols * sizeof(SColIndex));

    for (int32_t i = 0; i < pQueryMsg->numOfGroupCols; ++i) {
      (*groupbyCols)[i].colId = *(int16_t *)pMsg;
5327
      pMsg += sizeof((*groupbyCols)[i].colId);
5328 5329

      (*groupbyCols)[i].colIndex = *(int16_t *)pMsg;
5330 5331
      pMsg += sizeof((*groupbyCols)[i].colIndex);

5332
      (*groupbyCols)[i].flag = *(int16_t *)pMsg;
5333 5334 5335 5336 5337
      pMsg += sizeof((*groupbyCols)[i].flag);

      memcpy((*groupbyCols)[i].name, pMsg, tListLen(groupbyCols[i]->name));
      pMsg += tListLen((*groupbyCols)[i].name);
    }
5338

H
hjxilinx 已提交
5339 5340
    pQueryMsg->orderByIdx = htons(pQueryMsg->orderByIdx);
    pQueryMsg->orderType = htons(pQueryMsg->orderType);
5341 5342
  }

5343 5344
  pQueryMsg->fillType = htons(pQueryMsg->fillType);
  if (pQueryMsg->fillType != TSDB_FILL_NONE) {
H
hjxilinx 已提交
5345
    pQueryMsg->defaultVal = (uint64_t)(pMsg);
5346 5347

    int64_t *v = (int64_t *)pMsg;
5348
    for (int32_t i = 0; i < pQueryMsg->numOfOutput; ++i) {
5349 5350
      v[i] = htobe64(v[i]);
    }
5351

5352
    pMsg += sizeof(int64_t) * pQueryMsg->numOfOutput;
5353
  }
5354

5355 5356 5357 5358
  if (pQueryMsg->numOfTags > 0) {
    (*tagCols) = calloc(1, sizeof(SColumnInfo) * pQueryMsg->numOfTags);
    for (int32_t i = 0; i < pQueryMsg->numOfTags; ++i) {
      SColumnInfo* pTagCol = (SColumnInfo*) pMsg;
5359
      
5360 5361 5362 5363 5364 5365
      pTagCol->colId = htons(pTagCol->colId);
      pTagCol->bytes = htons(pTagCol->bytes);
      pTagCol->type  = htons(pTagCol->type);
      pTagCol->numOfFilters = 0;
      
      (*tagCols)[i] = *pTagCol;
5366
      pMsg += sizeof(SColumnInfo);
5367
    }
H
hjxilinx 已提交
5368
  }
5369

5370 5371 5372 5373 5374 5375
  // the tag query condition expression string is located at the end of query msg
  if (pQueryMsg->tagCondLen > 0) {
    *tagCond = calloc(1, pQueryMsg->tagCondLen);
    memcpy(*tagCond, pMsg, pQueryMsg->tagCondLen);
    pMsg += pQueryMsg->tagCondLen;
  }
5376
  
weixin_48148422's avatar
weixin_48148422 已提交
5377
  if (*pMsg != 0) {
5378 5379
    size_t len = strlen(pMsg) + 1;
    *tbnameCond = malloc(len);
weixin_48148422's avatar
weixin_48148422 已提交
5380
    strcpy(*tbnameCond, pMsg);
5381
    pMsg += len;
weixin_48148422's avatar
weixin_48148422 已提交
5382
  }
5383 5384 5385
  
  qTrace("qmsg:%p query %d tables, qrange:%" PRId64 "-%" PRId64 ", numOfGroupbyTagCols:%d, order:%d, "
         "outputCols:%d, numOfCols:%d, interval:%" PRId64 ", fillType:%d, comptsLen:%d, limit:%" PRId64 ", offset:%" PRId64,
5386
         pQueryMsg, pQueryMsg->numOfTables, pQueryMsg->window.skey, pQueryMsg->window.ekey, pQueryMsg->numOfGroupCols,
5387
         pQueryMsg->order, pQueryMsg->numOfOutput, pQueryMsg->numOfCols, pQueryMsg->intervalTime,
5388
         pQueryMsg->fillType, pQueryMsg->tsLen, pQueryMsg->limit, pQueryMsg->offset);
5389 5390 5391 5392

  return 0;
}

H
hjxilinx 已提交
5393
static int32_t buildAirthmeticExprFromMsg(SExprInfo *pArithExprInfo, SQueryTableMsg *pQueryMsg) {
5394
  qTrace("qmsg:%p create arithmetic expr from binary string", pQueryMsg, pArithExprInfo->base.arg[0].argValue.pz);
weixin_48148422's avatar
weixin_48148422 已提交
5395 5396 5397 5398 5399 5400 5401 5402 5403

  tExprNode* pExprNode = NULL;
  TRY(32) {
    pExprNode = exprTreeFromBinary(pArithExprInfo->base.arg[0].argValue.pz, pArithExprInfo->base.arg[0].argBytes);
  } CATCH( code ) {
    CLEANUP_EXECUTE();
    return code;
  } END_TRY

H
hjxilinx 已提交
5404
  if (pExprNode == NULL) {
5405
    qError("qmsg:%p failed to create arithmetic expression string from:%s", pQueryMsg, pArithExprInfo->base.arg[0].argValue.pz);
5406 5407 5408
    return TSDB_CODE_APP_ERROR;
  }
  
5409
  pArithExprInfo->pExpr = pExprNode;
5410 5411 5412
  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
5413
static int32_t createSqlFunctionExprFromMsg(SQueryTableMsg *pQueryMsg, SExprInfo **pSqlFuncExpr,
5414
                                            SSqlFuncMsg **pExprMsg, SColumnInfo* pTagCols) {
5415
  *pSqlFuncExpr = NULL;
H
hjxilinx 已提交
5416
  int32_t code = TSDB_CODE_SUCCESS;
5417

H
hjxilinx 已提交
5418
  SExprInfo *pExprs = (SExprInfo *)calloc(1, sizeof(SExprInfo) * pQueryMsg->numOfOutput);
5419 5420 5421 5422 5423 5424 5425
  if (pExprs == NULL) {
    return TSDB_CODE_SERV_OUT_OF_MEMORY;
  }

  bool    isSuperTable = QUERY_IS_STABLE_QUERY(pQueryMsg->queryType);
  int16_t tagLen = 0;

5426
  for (int32_t i = 0; i < pQueryMsg->numOfOutput; ++i) {
5427
    pExprs[i].base = *pExprMsg[i];
5428
    pExprs[i].bytes = 0;
5429 5430 5431 5432

    int16_t type = 0;
    int16_t bytes = 0;

5433
    // parse the arithmetic expression
5434
    if (pExprs[i].base.functionId == TSDB_FUNC_ARITHM) {
5435
      code = buildAirthmeticExprFromMsg(&pExprs[i], pQueryMsg);
5436

5437 5438 5439
      if (code != TSDB_CODE_SUCCESS) {
        tfree(pExprs);
        return code;
5440 5441
      }

5442
      type  = TSDB_DATA_TYPE_DOUBLE;
5443
      bytes = tDataTypeDesc[type].nSize;
5444
    } else if (pExprs[i].base.colInfo.colId == TSDB_TBNAME_COLUMN_INDEX) {  // parse the normal column
5445
      type  = TSDB_DATA_TYPE_BINARY;
H
hjxilinx 已提交
5446
      bytes = TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE;
5447
    } else{
5448
      int32_t j = getColumnIndexInSource(pQueryMsg, &pExprs[i].base, pTagCols);
H
hjxilinx 已提交
5449
      assert(j < pQueryMsg->numOfCols || j < pQueryMsg->numOfTags);
H
hjxilinx 已提交
5450

5451
      SColumnInfo* pCol = (TSDB_COL_IS_TAG(pExprs[i].base.colInfo.flag))? &pTagCols[j]:&pQueryMsg->colList[j];
5452 5453
      type = pCol->type;
      bytes = pCol->bytes;
5454 5455
    }

5456 5457
    int32_t param = pExprs[i].base.arg[0].argValue.i64;
    if (getResultDataInfo(type, bytes, pExprs[i].base.functionId, param, &pExprs[i].type, &pExprs[i].bytes,
5458
                          &pExprs[i].interBytes, 0, isSuperTable) != TSDB_CODE_SUCCESS) {
5459 5460 5461 5462
      tfree(pExprs);
      return TSDB_CODE_INVALID_QUERY_MSG;
    }

5463
    if (pExprs[i].base.functionId == TSDB_FUNC_TAG_DUMMY || pExprs[i].base.functionId == TSDB_FUNC_TS_DUMMY) {
5464
      tagLen += pExprs[i].bytes;
5465
    }
5466
    assert(isValidDataType(pExprs[i].type, pExprs[i].bytes));
5467 5468 5469 5470 5471
  }

  // get the correct result size for top/bottom query, according to the number of tags columns in selection clause

  // TODO refactor
5472
  for (int32_t i = 0; i < pQueryMsg->numOfOutput; ++i) {
5473 5474
    pExprs[i].base = *pExprMsg[i];
    int16_t functId = pExprs[i].base.functionId;
5475
    
5476
    if (functId == TSDB_FUNC_TOP || functId == TSDB_FUNC_BOTTOM) {
5477
      int32_t j = getColumnIndexInSource(pQueryMsg, &pExprs[i].base, pTagCols);
5478 5479 5480 5481 5482
      assert(j < pQueryMsg->numOfCols);

      SColumnInfo *pCol = &pQueryMsg->colList[j];

      int32_t ret =
5483
          getResultDataInfo(pCol->type, pCol->bytes, functId, pExprs[i].base.arg[0].argValue.i64,
5484
                            &pExprs[i].type, &pExprs[i].bytes, &pExprs[i].interBytes, tagLen, isSuperTable);
5485 5486 5487 5488
      assert(ret == TSDB_CODE_SUCCESS);
    }
  }

5489
  tfree(pExprMsg);
5490 5491 5492 5493 5494
  *pSqlFuncExpr = pExprs;

  return TSDB_CODE_SUCCESS;
}

5495
static SSqlGroupbyExpr *createGroupbyExprFromMsg(SQueryTableMsg *pQueryMsg, SColIndex *pColIndex, int32_t *code) {
5496 5497 5498 5499 5500
  if (pQueryMsg->numOfGroupCols == 0) {
    return NULL;
  }

  // using group by tag columns
5501
  SSqlGroupbyExpr *pGroupbyExpr = (SSqlGroupbyExpr *)calloc(1, sizeof(SSqlGroupbyExpr));
5502 5503 5504 5505 5506 5507 5508 5509 5510
  if (pGroupbyExpr == NULL) {
    *code = TSDB_CODE_SERV_OUT_OF_MEMORY;
    return NULL;
  }

  pGroupbyExpr->numOfGroupCols = pQueryMsg->numOfGroupCols;
  pGroupbyExpr->orderType = pQueryMsg->orderType;
  pGroupbyExpr->orderIndex = pQueryMsg->orderByIdx;

5511 5512 5513 5514 5515
  pGroupbyExpr->columnInfo = taosArrayInit(pQueryMsg->numOfGroupCols, sizeof(SColIndex));
  for(int32_t i = 0; i < pQueryMsg->numOfGroupCols; ++i) {
    taosArrayPush(pGroupbyExpr->columnInfo, &pColIndex[i]);
  }
  
5516 5517 5518
  return pGroupbyExpr;
}

5519
static int32_t createFilterInfo(void *pQInfo, SQuery *pQuery) {
5520
  for (int32_t i = 0; i < pQuery->numOfCols; ++i) {
5521
    if (pQuery->colList[i].numOfFilters > 0) {
5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532
      pQuery->numOfFilterCols++;
    }
  }

  if (pQuery->numOfFilterCols == 0) {
    return TSDB_CODE_SUCCESS;
  }

  pQuery->pFilterInfo = calloc(1, sizeof(SSingleColumnFilterInfo) * pQuery->numOfFilterCols);

  for (int32_t i = 0, j = 0; i < pQuery->numOfCols; ++i) {
5533
    if (pQuery->colList[i].numOfFilters > 0) {
5534 5535
      SSingleColumnFilterInfo *pFilterInfo = &pQuery->pFilterInfo[j];

H
hjxilinx 已提交
5536
      memcpy(&pFilterInfo->info, &pQuery->colList[i], sizeof(SColumnInfoData));
5537 5538 5539
      pFilterInfo->info = pQuery->colList[i];
      
      pFilterInfo->numOfFilters = pQuery->colList[i].numOfFilters;
5540 5541 5542 5543
      pFilterInfo->pFilters = calloc(pFilterInfo->numOfFilters, sizeof(SColumnFilterElem));

      for (int32_t f = 0; f < pFilterInfo->numOfFilters; ++f) {
        SColumnFilterElem *pSingleColFilter = &pFilterInfo->pFilters[f];
5544
        pSingleColFilter->filterInfo = pQuery->colList[i].filters[f];
5545 5546 5547 5548 5549

        int32_t lower = pSingleColFilter->filterInfo.lowerRelOptr;
        int32_t upper = pSingleColFilter->filterInfo.upperRelOptr;

        if (lower == TSDB_RELATION_INVALID && upper == TSDB_RELATION_INVALID) {
S
slguan 已提交
5550
          qError("QInfo:%p invalid filter info", pQInfo);
5551 5552 5553
          return TSDB_CODE_INVALID_QUERY_MSG;
        }

5554 5555
        int16_t type  = pQuery->colList[i].type;
        int16_t bytes = pQuery->colList[i].bytes;
5556

5557 5558 5559
        // todo refactor
        __filter_func_t *rangeFilterArray = getRangeFilterFuncArray(type);
        __filter_func_t *filterArray = getValueFilterFuncArray(type);
5560 5561

        if (rangeFilterArray == NULL && filterArray == NULL) {
S
slguan 已提交
5562
          qError("QInfo:%p failed to get filter function, invalid data type:%d", pQInfo, type);
5563 5564 5565
          return TSDB_CODE_INVALID_QUERY_MSG;
        }

5566
        if ((lower == TSDB_RELATION_GREATER_EQUAL || lower == TSDB_RELATION_GREATER) &&
5567
            (upper == TSDB_RELATION_LESS_EQUAL || upper == TSDB_RELATION_LESS)) {
5568
          if (lower == TSDB_RELATION_GREATER_EQUAL) {
5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585
            if (upper == TSDB_RELATION_LESS_EQUAL) {
              pSingleColFilter->fp = rangeFilterArray[4];
            } else {
              pSingleColFilter->fp = rangeFilterArray[2];
            }
          } else {
            if (upper == TSDB_RELATION_LESS_EQUAL) {
              pSingleColFilter->fp = rangeFilterArray[3];
            } else {
              pSingleColFilter->fp = rangeFilterArray[1];
            }
          }
        } else {  // set callback filter function
          if (lower != TSDB_RELATION_INVALID) {
            pSingleColFilter->fp = filterArray[lower];

            if (upper != TSDB_RELATION_INVALID) {
S
slguan 已提交
5586
              qError("pQInfo:%p failed to get filter function, invalid filter condition", pQInfo, type);
5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603
              return TSDB_CODE_INVALID_QUERY_MSG;
            }
          } else {
            pSingleColFilter->fp = filterArray[upper];
          }
        }
        assert(pSingleColFilter->fp != NULL);
        pSingleColFilter->bytes = bytes;
      }

      j++;
    }
  }

  return TSDB_CODE_SUCCESS;
}

5604
static void doUpdateExprColumnIndex(SQuery *pQuery) {
5605
  assert(pQuery->pSelectExpr != NULL && pQuery != NULL);
5606

5607
  for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
5608
    SSqlFuncMsg *pSqlExprMsg = &pQuery->pSelectExpr[k].base;
5609 5610 5611
    if (pSqlExprMsg->functionId == TSDB_FUNC_ARITHM || pSqlExprMsg->colInfo.flag == TSDB_COL_TAG) {
      continue;
    }
5612 5613

    SColIndex *pColIndexEx = &pSqlExprMsg->colInfo;
5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626
    if (!TSDB_COL_IS_TAG(pColIndexEx->flag)) {
      for (int32_t f = 0; f < pQuery->numOfCols; ++f) {
        if (pColIndexEx->colId == pQuery->colList[f].colId) {
          pColIndexEx->colIndex = f;
          break;
        }
      }
    } else {
      for (int32_t f = 0; f < pQuery->numOfTags; ++f) {
        if (pColIndexEx->colId == pQuery->tagColList[f].colId) {
          pColIndexEx->colIndex = f;
          break;
        }
5627 5628 5629 5630 5631
      }
    }
  }
}

weixin_48148422's avatar
weixin_48148422 已提交
5632 5633 5634 5635 5636 5637 5638 5639 5640 5641

static int compareTableIdInfo( const void* a, const void* b ) {
  const STableIdInfo* x = (const STableIdInfo*)a;
  const STableIdInfo* y = (const STableIdInfo*)b;
  if (x->uid > y->uid) return 1;
  if (x->uid < y->uid) return -1;
  return 0;
}

static SQInfo *createQInfoImpl(SQueryTableMsg *pQueryMsg, SArray* pTableIdList, SSqlGroupbyExpr *pGroupbyExpr, SExprInfo *pExprs,
5642
                               STableGroupInfo *groupInfo, SColumnInfo* pTagCols) {
5643 5644
  SQInfo *pQInfo = (SQInfo *)calloc(1, sizeof(SQInfo));
  if (pQInfo == NULL) {
5645
    return NULL;
5646 5647 5648 5649 5650 5651
  }

  SQuery *pQuery = calloc(1, sizeof(SQuery));
  pQInfo->runtimeEnv.pQuery = pQuery;

  int16_t numOfCols = pQueryMsg->numOfCols;
5652
  int16_t numOfOutput = pQueryMsg->numOfOutput;
5653

5654
  pQuery->numOfCols       = numOfCols;
H
hjxilinx 已提交
5655
  pQuery->numOfOutput     = numOfOutput;
5656 5657 5658
  pQuery->limit.limit     = pQueryMsg->limit;
  pQuery->limit.offset    = pQueryMsg->offset;
  pQuery->order.order     = pQueryMsg->order;
5659
  pQuery->order.orderColId = pQueryMsg->orderColId;
5660 5661 5662 5663
  pQuery->pSelectExpr     = pExprs;
  pQuery->pGroupbyExpr    = pGroupbyExpr;
  pQuery->intervalTime    = pQueryMsg->intervalTime;
  pQuery->slidingTime     = pQueryMsg->slidingTime;
5664
  pQuery->slidingTimeUnit = pQueryMsg->slidingTimeUnit;
5665
  pQuery->fillType     = pQueryMsg->fillType;
5666
  pQuery->numOfTags       = pQueryMsg->numOfTags;
5667

5668
  // todo do not allocate ??
5669
  pQuery->colList = calloc(numOfCols, sizeof(SSingleColumnFilterInfo));
5670
  if (pQuery->colList == NULL) {
5671
    goto _cleanup;
5672
  }
5673

H
hjxilinx 已提交
5674
  for (int16_t i = 0; i < numOfCols; ++i) {
5675
    pQuery->colList[i] = pQueryMsg->colList[i];
5676
    pQuery->colList[i].filters = tscFilterInfoClone(pQueryMsg->colList[i].filters, pQuery->colList[i].numOfFilters);
H
hjxilinx 已提交
5677
  }
5678
  
5679
  pQuery->tagColList = pTagCols;
5680
  
5681
  // calculate the result row size
5682 5683 5684
  for (int16_t col = 0; col < numOfOutput; ++col) {
    assert(pExprs[col].bytes > 0);
    pQuery->rowSize += pExprs[col].bytes;
5685
  }
5686

5687
  doUpdateExprColumnIndex(pQuery);
5688

5689
  int32_t ret = createFilterInfo(pQInfo, pQuery);
5690
  if (ret != TSDB_CODE_SUCCESS) {
5691
    goto _cleanup;
5692 5693 5694
  }

  // prepare the result buffer
5695
  pQuery->sdata = (tFilePage **)calloc(pQuery->numOfOutput, POINTER_BYTES);
5696
  if (pQuery->sdata == NULL) {
5697
    goto _cleanup;
5698 5699
  }

H
hjxilinx 已提交
5700
  // set the output buffer capacity
H
hjxilinx 已提交
5701
  pQuery->rec.capacity = 4096;
5702
  pQuery->rec.threshold = 4000;
5703

5704
  for (int32_t col = 0; col < pQuery->numOfOutput; ++col) {
5705
    assert(pExprs[col].interBytes >= pExprs[col].bytes);
5706 5707

    // allocate additional memory for interResults that are usually larger then final results
5708 5709
    size_t size = (pQuery->rec.capacity + 1) * pExprs[col].bytes + pExprs[col].interBytes + sizeof(tFilePage);
    pQuery->sdata[col] = (tFilePage *)calloc(1, size);
5710
    if (pQuery->sdata[col] == NULL) {
5711
      goto _cleanup;
5712 5713 5714
    }
  }

5715
  if (pQuery->fillType != TSDB_FILL_NONE) {
5716
    pQuery->defaultVal = malloc(sizeof(int64_t) * pQuery->numOfOutput);
5717
    if (pQuery->defaultVal == NULL) {
5718
      goto _cleanup;
5719 5720 5721
    }

    // the first column is the timestamp
5722
    memcpy(pQuery->defaultVal, (char *)pQueryMsg->defaultVal, pQuery->numOfOutput * sizeof(int64_t));
5723 5724 5725
  }

  // to make sure third party won't overwrite this structure
5726
  pQInfo->signature = pQInfo;
H
hjxilinx 已提交
5727 5728 5729 5730 5731 5732 5733
  
  pQInfo->tableIdGroupInfo = *groupInfo;
  size_t numOfGroups = taosArrayGetSize(groupInfo->pGroupList);
  
  pQInfo->groupInfo.pGroupList = taosArrayInit(numOfGroups, POINTER_BYTES);
  pQInfo->groupInfo.numOfTables = groupInfo->numOfTables;
  
weixin_48148422's avatar
weixin_48148422 已提交
5734 5735 5736
  int tableIndex = 0;
  STimeWindow window = pQueryMsg->window;
  taosArraySort( pTableIdList, compareTableIdInfo );
H
hjxilinx 已提交
5737 5738 5739 5740 5741 5742 5743
  for(int32_t i = 0; i < numOfGroups; ++i) {
    SArray* pa = taosArrayGetP(groupInfo->pGroupList, i);
    size_t s = taosArrayGetSize(pa);
    
    SArray* p1 = taosArrayInit(s, sizeof(SGroupItem));
    
    for(int32_t j = 0; j < s; ++j) {
weixin_48148422's avatar
weixin_48148422 已提交
5744 5745 5746 5747 5748 5749 5750 5751
      STableId id = *(STableId*) taosArrayGet(pa, j);
      SGroupItem item = { .id = id };
      // NOTE: compare STableIdInfo with STableId
      // not a problem at present because we only use their 1st int64_t field
      STableIdInfo* pTableId = taosArraySearch( pTableIdList, compareTableIdInfo, &id );
      if (pTableId != NULL ) {
        window.skey = pTableId->key;
      } else {
B
Bomin Zhang 已提交
5752
        window.skey = pQueryMsg->window.skey;
weixin_48148422's avatar
weixin_48148422 已提交
5753 5754 5755 5756
      }
      item.info = createTableQueryInfo(&pQInfo->runtimeEnv, item.id, window);
      item.info->groupIdx = i;
      item.info->tableIndex = tableIndex++;
H
hjxilinx 已提交
5757 5758 5759 5760
      taosArrayPush(p1, &item);
    }
    taosArrayPush(pQInfo->groupInfo.pGroupList, &p1);
  }
5761

weixin_48148422's avatar
weixin_48148422 已提交
5762 5763
  pQInfo->arrTableIdInfo = taosArrayInit(tableIndex, sizeof(STableIdInfo));

5764
  pQuery->pos = -1;
5765

5766
  pQuery->window = pQueryMsg->window;
5767

5768
  if (sem_init(&pQInfo->dataReady, 0, 0) != 0) {
S
slguan 已提交
5769
    qError("QInfo:%p init dataReady sem failed, reason:%s", pQInfo, strerror(errno));
5770
    goto _cleanup;
5771
  }
5772

5773
  vnodeParametersSafetyCheck(pQuery);
5774

S
slguan 已提交
5775
  qTrace("qmsg:%p QInfo:%p created", pQueryMsg, pQInfo);
5776 5777
  return pQInfo;

5778
_cleanup:
5779 5780 5781
  tfree(pQuery->defaultVal);

  if (pQuery->sdata != NULL) {
5782
    for (int16_t col = 0; col < pQuery->numOfOutput; ++col) {
5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798
      tfree(pQuery->sdata[col]);
    }
  }

  tfree(pQuery->sdata);
  tfree(pQuery->pFilterInfo);
  tfree(pQuery->colList);

  tfree(pExprs);
  tfree(pGroupbyExpr);

  tfree(pQInfo);

  return NULL;
}

H
hjxilinx 已提交
5799
static bool isValidQInfo(void *param) {
H
hjxilinx 已提交
5800 5801 5802 5803
  SQInfo *pQInfo = (SQInfo *)param;
  if (pQInfo == NULL) {
    return false;
  }
5804

H
hjxilinx 已提交
5805 5806 5807 5808
  /*
   * pQInfo->signature may be changed by another thread, so we assign value of signature
   * into local variable, then compare by using local variable
   */
5809
  uint64_t sig = (uint64_t)pQInfo->signature;
H
hjxilinx 已提交
5810 5811 5812
  return (sig == (uint64_t)pQInfo);
}

H
hjxilinx 已提交
5813 5814
static void freeQInfo(SQInfo *pQInfo);

5815
static int32_t initQInfo(SQueryTableMsg *pQueryMsg, void *tsdb, int32_t vgId, SQInfo *pQInfo, bool isSTable) {
H
hjxilinx 已提交
5816
  int32_t code = TSDB_CODE_SUCCESS;
5817
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
5818

H
hjxilinx 已提交
5819 5820 5821 5822
  STSBuf *pTSBuf = NULL;
  if (pQueryMsg->tsLen > 0) {  // open new file to save the result
    char *tsBlock = (char *)pQueryMsg + pQueryMsg->tsOffset;
    pTSBuf = tsBufCreateFromCompBlocks(tsBlock, pQueryMsg->tsNumOfBlocks, pQueryMsg->tsLen, pQueryMsg->tsOrder);
5823

H
hjxilinx 已提交
5824 5825 5826
    tsBufResetPos(pTSBuf);
    tsBufNextPos(pTSBuf);
  }
5827

5828 5829 5830
  // only the successful complete requries the sem_post/over = 1 operations.
  if ((QUERY_IS_ASC_QUERY(pQuery) && (pQuery->window.skey > pQuery->window.ekey)) ||
      (!QUERY_IS_ASC_QUERY(pQuery) && (pQuery->window.ekey > pQuery->window.skey))) {
S
slguan 已提交
5831
    qTrace("QInfo:%p no result in time range %" PRId64 "-%" PRId64 ", order %d", pQInfo, pQuery->window.skey,
5832
           pQuery->window.ekey, pQuery->order.order);
5833
    setQueryStatus(pQuery, QUERY_COMPLETED);
5834

5835 5836 5837
    sem_post(&pQInfo->dataReady);
    return TSDB_CODE_SUCCESS;
  }
H
hjxilinx 已提交
5838 5839

  // filter the qualified
5840
  if ((code = doInitQInfo(pQInfo, pTSBuf, tsdb, vgId, isSTable)) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
5841 5842
    goto _error;
  }
H
hjxilinx 已提交
5843
  
H
hjxilinx 已提交
5844 5845 5846 5847
  return code;

_error:
  // table query ref will be decrease during error handling
5848
  freeQInfo(pQInfo);
H
hjxilinx 已提交
5849 5850 5851 5852 5853 5854 5855
  return code;
}

static void freeQInfo(SQInfo *pQInfo) {
  if (!isValidQInfo(pQInfo)) {
    return;
  }
5856 5857

  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
H
hjxilinx 已提交
5858
  setQueryKilled(pQInfo);
5859

S
slguan 已提交
5860
  qTrace("QInfo:%p start to free QInfo", pQInfo);
5861
  for (int32_t col = 0; col < pQuery->numOfOutput; ++col) {
H
hjxilinx 已提交
5862 5863
    tfree(pQuery->sdata[col]);
  }
5864

H
hjxilinx 已提交
5865
  sem_destroy(&(pQInfo->dataReady));
5866
  teardownQueryRuntimeEnv(&pQInfo->runtimeEnv);
5867

H
hjxilinx 已提交
5868 5869 5870 5871 5872 5873
  for (int32_t i = 0; i < pQuery->numOfFilterCols; ++i) {
    SSingleColumnFilterInfo *pColFilter = &pQuery->pFilterInfo[i];
    if (pColFilter->numOfFilters > 0) {
      tfree(pColFilter->pFilters);
    }
  }
5874

H
hjxilinx 已提交
5875
  if (pQuery->pSelectExpr != NULL) {
5876
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
H
hjxilinx 已提交
5877
      SExprInfo* pExprInfo = &pQuery->pSelectExpr[i];
5878

H
hjxilinx 已提交
5879 5880 5881
      if (pExprInfo->pExpr != NULL) {
        tExprTreeDestroy(&pExprInfo->pExpr, NULL);
      }
H
hjxilinx 已提交
5882
    }
5883

H
hjxilinx 已提交
5884 5885
    tfree(pQuery->pSelectExpr);
  }
5886

H
hjxilinx 已提交
5887 5888 5889
  if (pQuery->defaultVal != NULL) {
    tfree(pQuery->defaultVal);
  }
5890

5891
  // todo refactor, extract method to destroytableDataInfo
H
hjxilinx 已提交
5892
  int32_t numOfGroups = taosArrayGetSize(pQInfo->groupInfo.pGroupList);
5893 5894
  for (int32_t i = 0; i < numOfGroups; ++i) {
    SArray *p = taosArrayGetP(pQInfo->groupInfo.pGroupList, i);
5895 5896 5897
    
    size_t num = taosArrayGetSize(p);
    for(int32_t j = 0; j < num; ++j) {
H
hjxilinx 已提交
5898 5899 5900
      SGroupItem* item = taosArrayGet(p, j);
      if (item->info != NULL) {
        destroyTableQueryInfo(item->info, pQuery->numOfOutput);
5901 5902
      }
    }
H
hjxilinx 已提交
5903
    
H
hjxilinx 已提交
5904 5905
    taosArrayDestroy(p);
  }
5906
  
H
hjxilinx 已提交
5907 5908 5909 5910 5911 5912 5913 5914
  taosArrayDestroy(pQInfo->groupInfo.pGroupList);
  
  for(int32_t i = 0; i < numOfGroups; ++i) {
    SArray* p = taosArrayGetP(pQInfo->tableIdGroupInfo.pGroupList, i);
    taosArrayDestroy(p);
  }
  
  taosArrayDestroy(pQInfo->tableIdGroupInfo.pGroupList);
weixin_48148422's avatar
weixin_48148422 已提交
5915
  taosArrayDestroy(pQInfo->arrTableIdInfo);
H
hjxilinx 已提交
5916
  
5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928
  if (pQuery->pGroupbyExpr != NULL) {
    taosArrayDestroy(pQuery->pGroupbyExpr->columnInfo);
    tfree(pQuery->pGroupbyExpr);
  }
  
  tfree(pQuery->tagColList);
  tfree(pQuery->pFilterInfo);
  tfree(pQuery->colList);
  tfree(pQuery->sdata);
  
  tfree(pQuery);
  
S
slguan 已提交
5929
  qTrace("QInfo:%p QInfo is freed", pQInfo);
5930

5931
  // destroy signature, in order to avoid the query process pass the object safety check
H
hjxilinx 已提交
5932 5933 5934 5935
  memset(pQInfo, 0, sizeof(SQInfo));
  tfree(pQInfo);
}

H
hjxilinx 已提交
5936
static size_t getResultSize(SQInfo *pQInfo, int64_t *numOfRows) {
5937 5938
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;

H
hjxilinx 已提交
5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949
  /*
   * get the file size and set the numOfRows to be the file size, since for tsComp query,
   * the returned row size is equalled to 1
   * TODO handle the case that the file is too large to send back one time
   */
  if (isTSCompQuery(pQuery) && (*numOfRows) > 0) {
    struct stat fstat;
    if (stat(pQuery->sdata[0]->data, &fstat) == 0) {
      *numOfRows = fstat.st_size;
      return fstat.st_size;
    } else {
S
slguan 已提交
5950
      qError("QInfo:%p failed to get file info, path:%s, reason:%s", pQInfo, pQuery->sdata[0]->data, strerror(errno));
H
hjxilinx 已提交
5951 5952 5953 5954
      return 0;
    }
  } else {
    return pQuery->rowSize * (*numOfRows);
5955
  }
H
hjxilinx 已提交
5956
}
5957

H
hjxilinx 已提交
5958 5959 5960
static int32_t doDumpQueryResult(SQInfo *pQInfo, char *data) {
  // the remained number of retrieved rows, not the interpolated result
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
5961

H
hjxilinx 已提交
5962 5963 5964
  // load data from file to msg buffer
  if (isTSCompQuery(pQuery)) {
    int32_t fd = open(pQuery->sdata[0]->data, O_RDONLY, 0666);
5965

H
hjxilinx 已提交
5966 5967 5968
    // make sure file exist
    if (FD_VALID(fd)) {
      size_t s = lseek(fd, 0, SEEK_END);
S
slguan 已提交
5969
      qTrace("QInfo:%p ts comp data return, file:%s, size:%zu", pQInfo, pQuery->sdata[0]->data, s);
5970

H
hjxilinx 已提交
5971 5972 5973
      lseek(fd, 0, SEEK_SET);
      read(fd, data, s);
      close(fd);
5974

H
hjxilinx 已提交
5975 5976
      unlink(pQuery->sdata[0]->data);
    } else {
H
hjxilinx 已提交
5977
      // todo return the error code to client
S
slguan 已提交
5978
      qError("QInfo:%p failed to open tmp file to send ts-comp data to client, path:%s, reason:%s", pQInfo,
H
hjxilinx 已提交
5979 5980
             pQuery->sdata[0]->data, strerror(errno));
    }
H
hjxilinx 已提交
5981 5982 5983 5984 5985
  
    // all data returned, set query over
    if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
      setQueryStatus(pQuery, QUERY_OVER);
    }
H
hjxilinx 已提交
5986
  } else {
5987
    doCopyQueryResultToMsg(pQInfo, pQuery->rec.rows, data);
5988
  }
5989

5990
  pQuery->rec.total += pQuery->rec.rows;
S
slguan 已提交
5991
  qTrace("QInfo:%p current:%d, total:%d", pQInfo, pQuery->rec.rows, pQuery->rec.total);
5992

H
hjxilinx 已提交
5993
  return TSDB_CODE_SUCCESS;
5994

H
hjxilinx 已提交
5995
  // todo if interpolation exists, the result may be dump to client by several rounds
5996 5997
}

5998
int32_t qCreateQueryInfo(void *tsdb, int32_t vgId, SQueryTableMsg *pQueryMsg, qinfo_t *pQInfo) {
H
hjxilinx 已提交
5999
  assert(pQueryMsg != NULL);
6000 6001

  int32_t code = TSDB_CODE_SUCCESS;
6002

weixin_48148422's avatar
weixin_48148422 已提交
6003
  char *        tagCond = NULL, *tbnameCond = NULL;
6004
  SArray *      pTableIdList = NULL;
6005
  SSqlFuncMsg **pExprMsg = NULL;
6006 6007
  SColIndex *   pGroupColIndex = NULL;
  SColumnInfo*  pTagColumnInfo = NULL;
6008

weixin_48148422's avatar
weixin_48148422 已提交
6009
  if ((code = convertQueryMsg(pQueryMsg, &pTableIdList, &pExprMsg, &tagCond, &tbnameCond, &pGroupColIndex, &pTagColumnInfo)) !=
6010
         TSDB_CODE_SUCCESS) {
6011 6012 6013
    return code;
  }

H
hjxilinx 已提交
6014
  if (pQueryMsg->numOfTables <= 0) {
S
slguan 已提交
6015
    qError("Invalid number of tables to query, numOfTables:%d", pQueryMsg->numOfTables);
6016
    code = TSDB_CODE_INVALID_QUERY_MSG;
H
hjxilinx 已提交
6017
    goto _over;
6018 6019
  }

H
hjxilinx 已提交
6020
  if (pTableIdList == NULL || taosArrayGetSize(pTableIdList) == 0) {
S
slguan 已提交
6021
    qError("qmsg:%p, SQueryTableMsg wrong format", pQueryMsg);
6022
    code = TSDB_CODE_INVALID_QUERY_MSG;
H
hjxilinx 已提交
6023
    goto _over;
6024 6025
  }

H
hjxilinx 已提交
6026
  SExprInfo *pExprs = NULL;
6027
  if ((code = createSqlFunctionExprFromMsg(pQueryMsg, &pExprs, pExprMsg, pTagColumnInfo)) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
6028
    goto _over;
6029 6030
  }

6031
  SSqlGroupbyExpr *pGroupbyExpr = createGroupbyExprFromMsg(pQueryMsg, pGroupColIndex, &code);
H
hjxilinx 已提交
6032
  if ((pGroupbyExpr == NULL && pQueryMsg->numOfGroupCols != 0) || code != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
6033
    goto _over;
6034
  }
6035

H
hjxilinx 已提交
6036
  bool isSTableQuery = false;
H
hjxilinx 已提交
6037
  STableGroupInfo groupInfo = {0};
6038
  
H
hjxilinx 已提交
6039
  //todo multitable_query??
6040 6041 6042
  if (TSDB_QUERY_HAS_TYPE(pQueryMsg->queryType, TSDB_QUERY_TYPE_MULTITABLE_QUERY|TSDB_QUERY_TYPE_TABLE_QUERY)) {
    isSTableQuery = TSDB_QUERY_HAS_TYPE(pQueryMsg->queryType, TSDB_QUERY_TYPE_MULTITABLE_QUERY);
    
weixin_48148422's avatar
weixin_48148422 已提交
6043
    STableIdInfo *id = taosArrayGet(pTableIdList, 0);
H
Haojun Liao 已提交
6044 6045
    qTrace("qmsg:%p query table, uid:%"PRId64", tid:%d", pQueryMsg, id->uid, id->tid);
    
6046
    if ((code = tsdbGetOneTableGroup(tsdb, id->uid, &groupInfo)) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
6047
      goto _over;
6048 6049
    }
  } else if (TSDB_QUERY_HAS_TYPE(pQueryMsg->queryType, TSDB_QUERY_TYPE_STABLE_QUERY)) {
6050
    isSTableQuery = true;
weixin_48148422's avatar
weixin_48148422 已提交
6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080
    // TODO: need a macro from TSDB to check if table is super table,
    // also note there's possiblity that only one table in the super table
    if (taosArrayGetSize(pTableIdList) == 1) {
      STableIdInfo *id = taosArrayGet(pTableIdList, 0);
      // if array size is 1 and assert super table

      // group by normal column, do not pass the group by condition to tsdb to group table into different group
      int32_t numOfGroupByCols = pQueryMsg->numOfGroupCols;
      if (pQueryMsg->numOfGroupCols == 1 && !TSDB_COL_IS_TAG(pGroupColIndex->flag)) {
        numOfGroupByCols = 0;
      }
      
      // todo handle the error
      /*int32_t ret =*/tsdbQuerySTableByTagCond(tsdb, id->uid, tagCond, pQueryMsg->tagCondLen, pQueryMsg->tagNameRelType, tbnameCond, &groupInfo, pGroupColIndex,
                                          numOfGroupByCols);
      if (groupInfo.numOfTables == 0) {  // no qualified tables no need to do query
        code = TSDB_CODE_SUCCESS;
        goto _over;
      }
    } else {
      groupInfo.numOfTables = taosArrayGetSize(pTableIdList);
      SArray* pTableGroup = taosArrayInit(1, POINTER_BYTES);

      SArray* sa = taosArrayInit(groupInfo.numOfTables, sizeof(STableId));
      for(int32_t i = 0; i < groupInfo.numOfTables; ++i) {
        STableIdInfo* tableId = taosArrayGet(pTableIdList, i);
        taosArrayPush(sa, tableId);
      }
      taosArrayPush(pTableGroup, &sa);
      groupInfo.pGroupList = pTableGroup;
6081
    }
H
hjxilinx 已提交
6082
  } else {
6083
    assert(0);
6084
  }
6085

weixin_48148422's avatar
weixin_48148422 已提交
6086
  (*pQInfo) = createQInfoImpl(pQueryMsg, pTableIdList, pGroupbyExpr, pExprs, &groupInfo, pTagColumnInfo);
6087 6088
  if ((*pQInfo) == NULL) {
    code = TSDB_CODE_SERV_OUT_OF_MEMORY;
H
hjxilinx 已提交
6089
    goto _over;
6090
  }
6091

6092
  code = initQInfo(pQueryMsg, tsdb, vgId, *pQInfo, isSTableQuery);
6093

H
hjxilinx 已提交
6094
_over:
weixin_48148422's avatar
weixin_48148422 已提交
6095 6096
  tfree(tagCond);
  tfree(tbnameCond);
H
hjxilinx 已提交
6097
  taosArrayDestroy(pTableIdList);
6098
  
6099 6100
  // if failed to add ref for all meters in this query, abort current query
  //  atomic_fetch_add_32(&vnodeSelectReqNum, 1);
6101
  return code;
H
hjxilinx 已提交
6102 6103
}

H
hjxilinx 已提交
6104
void qDestroyQueryInfo(qinfo_t pQInfo) {
S
slguan 已提交
6105
  qTrace("QInfo:%p query completed", pQInfo);
6106 6107 6108
  freeQInfo(pQInfo);
}

H
hjxilinx 已提交
6109
void qTableQuery(qinfo_t qinfo) {
6110 6111
  SQInfo *pQInfo = (SQInfo *)qinfo;

H
hjxilinx 已提交
6112
  if (pQInfo == NULL || pQInfo->signature != pQInfo) {
S
slguan 已提交
6113
    qTrace("%p freed abort query", pQInfo);
H
hjxilinx 已提交
6114 6115
    return;
  }
6116

H
hjxilinx 已提交
6117
  if (isQueryKilled(pQInfo)) {
S
slguan 已提交
6118
    qTrace("QInfo:%p it is already killed, abort", pQInfo);
H
hjxilinx 已提交
6119 6120
    return;
  }
6121

S
slguan 已提交
6122
  qTrace("QInfo:%p query task is launched", pQInfo);
H
hjxilinx 已提交
6123 6124
  
  if (onlyQueryTags(pQInfo->runtimeEnv.pQuery)) {
H
hjxilinx 已提交
6125
    buildTagQueryResult(pQInfo);   // todo support the limit/offset
H
hjxilinx 已提交
6126
  } else if (pQInfo->runtimeEnv.stableQuery) {
6127
    stableQueryImpl(pQInfo);
H
hjxilinx 已提交
6128
  } else {
6129
    tableQueryImpl(pQInfo);
H
hjxilinx 已提交
6130
  }
H
hjxilinx 已提交
6131 6132
  
  sem_post(&pQInfo->dataReady);
H
hjxilinx 已提交
6133 6134 6135
  //  vnodeDecRefCount(pQInfo);
}

H
hjxilinx 已提交
6136
int32_t qRetrieveQueryResultInfo(qinfo_t qinfo) {
6137 6138
  SQInfo *pQInfo = (SQInfo *)qinfo;

H
hjxilinx 已提交
6139
  if (pQInfo == NULL || !isValidQInfo(pQInfo)) {
H
hjxilinx 已提交
6140 6141
    return TSDB_CODE_INVALID_QHANDLE;
  }
6142

H
hjxilinx 已提交
6143
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
6144
  if (isQueryKilled(pQInfo)) {
S
slguan 已提交
6145
    qTrace("QInfo:%p query is killed, code:%d", pQInfo, pQInfo->code);
H
hjxilinx 已提交
6146
    return pQInfo->code;
H
hjxilinx 已提交
6147
  }
6148

H
hjxilinx 已提交
6149
  sem_wait(&pQInfo->dataReady);
S
slguan 已提交
6150
  qTrace("QInfo:%p retrieve result info, rowsize:%d, rows:%d, code:%d", pQInfo, pQuery->rowSize, pQuery->rec.rows,
6151 6152
         pQInfo->code);

H
hjxilinx 已提交
6153
  return pQInfo->code;
H
hjxilinx 已提交
6154
}
6155

H
hjxilinx 已提交
6156
bool qHasMoreResultsToRetrieve(qinfo_t qinfo) {
6157 6158
  SQInfo *pQInfo = (SQInfo *)qinfo;

H
hjxilinx 已提交
6159 6160 6161
  if (pQInfo == NULL || pQInfo->signature != pQInfo || pQInfo->code != TSDB_CODE_SUCCESS) {
    return false;
  }
6162 6163

  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
H
hjxilinx 已提交
6164 6165 6166 6167 6168 6169 6170 6171
  if (Q_STATUS_EQUAL(pQuery->status, QUERY_OVER)) {
    return false;
  } else if (Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL)) {
    return true;
  } else if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
    return true;
  } else {
    assert(0);
6172 6173 6174
  }
}

6175 6176 6177
int32_t qDumpRetrieveResult(qinfo_t qinfo, SRetrieveTableRsp **pRsp, int32_t *contLen) {
  SQInfo *pQInfo = (SQInfo *)qinfo;

H
hjxilinx 已提交
6178
  if (pQInfo == NULL || !isValidQInfo(pQInfo)) {
6179 6180
    return TSDB_CODE_INVALID_QHANDLE;
  }
6181 6182 6183

  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
  size_t  size = getResultSize(pQInfo, &pQuery->rec.rows);
weixin_48148422's avatar
weixin_48148422 已提交
6184 6185
  size += sizeof(int32_t);
  size += sizeof(STableIdInfo) * taosArrayGetSize(pQInfo->arrTableIdInfo);
6186
  *contLen = size + sizeof(SRetrieveTableRsp);
6187

6188 6189
  // todo handle failed to allocate memory
  *pRsp = (SRetrieveTableRsp *)rpcMallocCont(*contLen);
6190
  (*pRsp)->numOfRows = htonl(pQuery->rec.rows);
6191

6192 6193 6194 6195 6196 6197 6198 6199
  int32_t code = pQInfo->code;
  if (code == TSDB_CODE_SUCCESS) {
    (*pRsp)->offset = htobe64(pQuery->limit.offset);
    (*pRsp)->useconds = htobe64(pQInfo->elapsedTime);
  } else {
    (*pRsp)->offset = 0;
    (*pRsp)->useconds = 0;
  }
6200

6201
  if (pQuery->rec.rows > 0 && code == TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
6202
    code = doDumpQueryResult(pQInfo, (*pRsp)->data);
6203
  } else {
H
hjxilinx 已提交
6204
    setQueryStatus(pQuery, QUERY_OVER);
6205
    code = pQInfo->code;
6206
  }
6207

H
hjxilinx 已提交
6208
  if (isQueryKilled(pQInfo) || Q_STATUS_EQUAL(pQuery->status, QUERY_OVER)) {
6209
    (*pRsp)->completed = 1;  // notify no more result to client
H
hjxilinx 已提交
6210
  }
6211

H
hjxilinx 已提交
6212
  return code;
6213 6214 6215 6216 6217 6218

  //  if (numOfRows == 0 && (pRetrieve->qhandle == (uint64_t)pObj->qhandle) && (code != TSDB_CODE_ACTION_IN_PROGRESS)) {
  //    qTrace("QInfo:%p %s free qhandle code:%d", pObj->qhandle, __FUNCTION__, code);
  //    vnodeDecRefCount(pObj->qhandle);
  //    pObj->qhandle = NULL;
  //  }
6219
}
H
hjxilinx 已提交
6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230

static void buildTagQueryResult(SQInfo* pQInfo) {
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;
  
  size_t num = taosArrayGetSize(pQInfo->groupInfo.pGroupList);
  assert(num == 1);   // only one group
  
  SArray* pa = taosArrayGetP(pQInfo->groupInfo.pGroupList, 0);
  num = taosArrayGetSize(pa);
  
6231
  assert(num == pQInfo->groupInfo.numOfTables);
H
hjxilinx 已提交
6232 6233
  int16_t type, bytes;
  
6234 6235 6236 6237 6238 6239
  int32_t functionId = pQuery->pSelectExpr[0].base.functionId;
  if (functionId == TSDB_FUNC_TID_TAG) { // return the tags & table Id
    assert(pQuery->numOfOutput == 1);
    SExprInfo* pExprInfo = &pQuery->pSelectExpr[0];
  
    int32_t rsize = pExprInfo->bytes;
H
hjxilinx 已提交
6240
    char* data = NULL;
6241 6242 6243 6244 6245
    
    for(int32_t i = 0; i < num; ++i) {
      SGroupItem* item = taosArrayGet(pa, i);
    
      char* output = pQuery->sdata[0]->data + i * rsize;
6246 6247 6248 6249
      varDataSetLen(output, rsize - VARSTR_HEADER_SIZE);
      
      output = varDataVal(output);
      *(int64_t*) output = item->id.uid;  // memory align problem, todo serialize
6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260
      output += sizeof(item->id.uid);
      
      *(int32_t*) output = item->id.tid;
      output += sizeof(item->id.tid);
      
      *(int32_t*) output = pQInfo->vgId;
      output += sizeof(pQInfo->vgId);
      
      tsdbGetTableTagVal(pQInfo->tsdb, &item->id, pExprInfo->base.colInfo.colId, &type, &bytes, &data);
      memcpy(output, data, bytes);
    }
H
hjxilinx 已提交
6261
  
H
hjxilinx 已提交
6262
    qTrace("QInfo:%p create (tableId, tag) info completed, rows:%d", pQInfo, num);
6263 6264 6265 6266 6267 6268 6269
  } else {  // return only the tags|table name etc.
    for(int32_t i = 0; i < num; ++i) {
      SExprInfo* pExprInfo = pQuery->pSelectExpr;
      SGroupItem* item = taosArrayGet(pa, i);
    
      char* data = NULL;
      for(int32_t j = 0; j < pQuery->numOfOutput; ++j) {
H
hjxilinx 已提交
6270
        // todo check the return value, refactor codes
6271
        if (pExprInfo[j].base.colInfo.colId == TSDB_TBNAME_COLUMN_INDEX) {
H
hjxilinx 已提交
6272
          data = tsdbGetTableName(pQInfo->tsdb, &item->id, &bytes);
H
hjxilinx 已提交
6273
          
6274
          char* dst = pQuery->sdata[j]->data + i * (TSDB_TABLE_NAME_LEN + VARSTR_HEADER_SIZE);
H
hjxilinx 已提交
6275
          memcpy(dst, data, varDataTLen(data));
H
hjxilinx 已提交
6276
        } else {// todo refactor, return the true length of binary|nchar data
6277 6278
          tsdbGetTableTagVal(pQInfo->tsdb, &item->id, pExprInfo[j].base.colInfo.colId, &type, &bytes, &data);
          assert(bytes == pExprInfo[j].bytes && type == pExprInfo[j].type);
H
hjxilinx 已提交
6279 6280 6281 6282 6283 6284 6285
          
          char* dst = pQuery->sdata[j]->data + i * bytes;
          if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
            memcpy(dst, data, varDataTLen(data));
          } else {
            memcpy(dst, data, bytes);
          }
6286
        }
H
hjxilinx 已提交
6287
      }
H
hjxilinx 已提交
6288
    }
6289
  
H
Haojun Liao 已提交
6290
    pQInfo->tableIndex = pQInfo->groupInfo.numOfTables;
H
hjxilinx 已提交
6291
    qTrace("QInfo:%p create tag values results completed, rows:%d", pQInfo, num);
H
hjxilinx 已提交
6292
  }
H
hjxilinx 已提交
6293 6294 6295
  
  pQuery->rec.rows = num;
  setQueryStatus(pQuery, QUERY_COMPLETED);
H
hjxilinx 已提交
6296 6297
}