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

#include "hash.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 "tlosertree.h"
H
Haojun Liao 已提交
27
#include "exception.h"
28 29
#include "tscompression.h"
#include "ttime.h"
30 31 32 33 34 35 36 37 38

/**
 * 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)

39
#define IS_MASTER_SCAN(runtime)        ((runtime)->scanFlag == MASTER_SCAN)
H
hjxilinx 已提交
40
#define IS_REVERSE_SCAN(runtime)       ((runtime)->scanFlag == REVERSE_SCAN)
41
#define SET_MASTER_SCAN_FLAG(runtime)  ((runtime)->scanFlag = MASTER_SCAN)
H
hjxilinx 已提交
42
#define SET_REVERSE_SCAN_FLAG(runtime) ((runtime)->scanFlag = REVERSE_SCAN)
43

44
#define GET_QINFO_ADDR(x) ((void *)((char *)(x)-offsetof(SQInfo, runtimeEnv)))
45

46
#define GET_COL_DATA_POS(query, index, step) ((query)->pos + (index) * (step))
47
#define SWITCH_ORDER(n) (((n) = ((n) == TSDB_ORDER_ASC) ? TSDB_ORDER_DESC : TSDB_ORDER_ASC))
48 49 50

/* get the qinfo struct address from the query struct address */
#define GET_COLUMN_BYTES(query, colidx) \
51 52
  ((query)->colList[(query)->pSelectExpr[colidx].base.colInfo.colIndex].bytes)
#define GET_COLUMN_TYPE(query, colidx) ((query)->colList[(query)->pSelectExpr[colidx].base.colInfo.colIndex].type)
53

54
enum {
H
hjxilinx 已提交
55
  // when query starts to execute, this status will set
56 57
  QUERY_NOT_COMPLETED = 0x1u,

H
hjxilinx 已提交
58 59
  /* result output buffer is full, current query is paused.
   * this status is only exist in group-by clause and diff/add/division/multiply/ query.
60
   */
61 62
  QUERY_RESBUF_FULL = 0x2u,

H
hjxilinx 已提交
63 64 65
  /* 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
66
   */
67
  QUERY_COMPLETED = 0x4u,
68

H
hjxilinx 已提交
69 70
  /* when the result is not completed return to client, this status will be
   * usually used in case of interval query with interpolation option
71
   */
72
  QUERY_OVER = 0x8u,
73
};
74 75

enum {
76 77
  TS_JOIN_TS_EQUAL       = 0,
  TS_JOIN_TS_NOT_EQUALS  = 1,
78 79 80
  TS_JOIN_TAG_NOT_EQUALS = 2,
};

81
typedef struct {
82 83 84 85 86 87
  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;
88 89
} SQueryStatusInfo;

H
Haojun Liao 已提交
90 91 92 93 94 95 96 97 98 99 100
static UNUSED_FUNC void *u_malloc (size_t __size) {
//  uint32_t v = rand();
//  if (v % 5 <= 1) {
//    return NULL;
//  } else {
    return malloc(__size);
//  }
}

#define malloc  u_malloc

101
#define CLEAR_QUERY_STATUS(q, st)   ((q)->status &= (~(st)))
H
Haojun Liao 已提交
102 103 104
#define GET_NUM_OF_TABLEGROUP(q)    taosArrayGetSize((q)->tableqinfoGroupInfo.pGroupList)
#define GET_TABLEGROUP(q, _index)   ((SArray*) taosArrayGetP((q)->tableqinfoGroupInfo.pGroupList, (_index)))

105
static void setQueryStatus(SQuery *pQuery, int8_t status);
106

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

H
hjxilinx 已提交
109
// todo move to utility
110
static int32_t mergeIntoGroupResultImpl(SQInfo *pQInfo, SArray *group);
111

H
hjxilinx 已提交
112
static void setWindowResOutputBuf(SQueryRuntimeEnv *pRuntimeEnv, SWindowResult *pResult);
H
Haojun Liao 已提交
113
static void setWindowResOutputBufInitCtx(SQueryRuntimeEnv *pRuntimeEnv, SWindowResult *pResult);
114 115 116
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);
117

118 119 120
static void setExecParams(SQuery *pQuery, SQLFunctionCtx *pCtx, void* inputData, TSKEY *tsCol, SDataBlockInfo* pBlockInfo,
                          SDataStatis *pStatis, void *param, int32_t colIndex);

121
static void initCtxOutputBuf(SQueryRuntimeEnv *pRuntimeEnv);
122
static void destroyTableQueryInfo(STableQueryInfo *pTableQueryInfo, int32_t numOfCols);
123 124
static void resetCtxOutputBuf(SQueryRuntimeEnv *pRuntimeEnv);
static bool hasMainOutput(SQuery *pQuery);
H
hjxilinx 已提交
125
static void buildTagQueryResult(SQInfo *pQInfo);
126

127
static int32_t setAdditionalInfo(SQInfo *pQInfo, void *pTable, STableQueryInfo *pTableQueryInfo);
128
static int32_t flushFromResultBuf(SQInfo *pQInfo);
129

130
bool doFilterData(SQuery *pQuery, int32_t elemPos) {
131 132
  for (int32_t k = 0; k < pQuery->numOfFilterCols; ++k) {
    SSingleColumnFilterInfo *pFilterInfo = &pQuery->pFilterInfo[k];
133

134 135
    char *pElem = pFilterInfo->pData + pFilterInfo->info.bytes * elemPos;
    if (isNull(pElem, pFilterInfo->info.type)) {
136 137
      return false;
    }
138

139 140
    bool qualified = false;
    for (int32_t j = 0; j < pFilterInfo->numOfFilters; ++j) {
141
      SColumnFilterElem *pFilterElem = &pFilterInfo->pFilters[j];
142

143 144 145 146 147
      if (pFilterElem->fp(pFilterElem, pElem, pElem)) {
        qualified = true;
        break;
      }
    }
148

149 150 151 152
    if (!qualified) {
      return false;
    }
  }
153

154 155 156 157 158 159
  return true;
}

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

161
  int64_t maxOutput = 0;
162
  for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
163
    int32_t functionId = pQuery->pSelectExpr[j].base.functionId;
164

165 166 167 168 169 170 171 172
    /*
     * 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;
    }
173

174 175 176 177 178
    SResultInfo *pResInfo = GET_RES_INFO(&pRuntimeEnv->pCtx[j]);
    if (pResInfo != NULL && maxOutput < pResInfo->numOfRes) {
      maxOutput = pResInfo->numOfRes;
    }
  }
179

180
  assert(maxOutput >= 0);
181 182 183
  return maxOutput;
}

184 185 186 187 188 189 190 191 192
/*
 * 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 已提交
193 194 195 196 197 198 199
    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);
200 201 202 203
    pResInfo->numOfRes = numOfRes;
  }
}

204 205 206 207 208 209 210 211 212
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;
  }
213

214
  for (int32_t i = 0; i < pGroupbyExpr->numOfGroupCols; ++i) {
215
    SColIndex *pColIndex = taosArrayGet(pGroupbyExpr->columnInfo, i);
216 217 218 219 220
    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) {
221
        assert(pColIndex->colIndex > 0);
222
      }
223

224 225 226
      return true;
    }
  }
227

228 229 230 231 232
  return false;
}

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

234 235
  int32_t colId = -2;
  int16_t type = TSDB_DATA_TYPE_NULL;
236

237
  for (int32_t i = 0; i < pGroupbyExpr->numOfGroupCols; ++i) {
238
    SColIndex *pColIndex = taosArrayGet(pGroupbyExpr->columnInfo, i);
239 240 241 242 243
    if (pColIndex->flag == TSDB_COL_NORMAL) {
      colId = pColIndex->colId;
      break;
    }
  }
244

245
  for (int32_t i = 0; i < pQuery->numOfCols; ++i) {
246 247
    if (colId == pQuery->colList[i].colId) {
      type = pQuery->colList[i].type;
248 249 250
      break;
    }
  }
251

252 253 254 255 256 257
  return type;
}

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

259
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
260
    int32_t functId = pQuery->pSelectExpr[i].base.functionId;
261 262 263 264
    if (functId == TSDB_FUNC_TAG_DUMMY || functId == TSDB_FUNC_TS_DUMMY) {
      hasTags = true;
      continue;
    }
265

266 267 268 269
    if ((aAggs[functId].nStatus & TSDB_FUNCSTATE_SELECTIVITY) != 0) {
      numOfSelectivity++;
    }
  }
270

271 272 273
  if (numOfSelectivity > 0 && hasTags) {
    return true;
  }
274

275 276 277
  return false;
}

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

280 281 282 283
static bool limitResults(SQueryRuntimeEnv* pRuntimeEnv) {
  SQInfo* pQInfo = GET_QINFO_ADDR(pRuntimeEnv);
  SQuery* pQuery = pRuntimeEnv->pQuery;
  
284 285
  if ((pQuery->limit.limit > 0) && (pQuery->rec.total + pQuery->rec.rows > pQuery->limit.limit)) {
    pQuery->rec.rows = pQuery->limit.limit - pQuery->rec.total;
286
    
287
    qDebug("QInfo:%p discard remain data due to result limitation, limit:%"PRId64", current return:%" PRId64 ", total:%"PRId64,
288 289
        pQInfo, pQuery->limit.limit, pQuery->rec.rows, pQuery->rec.total + pQuery->rec.rows);
    assert(pQuery->rec.rows >= 0);
290 291 292
    setQueryStatus(pQuery, QUERY_COMPLETED);
    return true;
  }
293

294 295 296 297
  return false;
}

static bool isTopBottomQuery(SQuery *pQuery) {
298
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
299
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
300 301 302
    if (functionId == TSDB_FUNC_TS) {
      continue;
    }
303

304 305 306 307
    if (functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM) {
      return true;
    }
  }
308

309 310 311
  return false;
}

H
Haojun Liao 已提交
312
static SDataStatis *getStatisInfo(SQuery *pQuery, SDataStatis *pStatis, int32_t numOfCols, int32_t index) {
313
  // for a tag column, no corresponding field info
H
Haojun Liao 已提交
314 315
  SColIndex *pColIndex = &pQuery->pSelectExpr[index].base.colInfo;
  if (TSDB_COL_IS_TAG(pColIndex->flag)) {
316 317
    return NULL;
  }
H
Haojun Liao 已提交
318
  
319 320 321
  /*
   * 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.
H
Haojun Liao 已提交
322
   * TODO: speedup by using bsearch
323
   */
H
Haojun Liao 已提交
324 325
  for (int32_t i = 0; i < numOfCols; ++i) {
    if (pColIndex->colId == pStatis[i].colId) {
326 327 328
      return &pStatis[i];
    }
  }
H
Haojun Liao 已提交
329
  
330 331 332
  return NULL;
}

333 334 335 336 337 338 339 340
/**
 * @param pQuery
 * @param col
 * @param pDataBlockInfo
 * @param pStatis
 * @param pColStatis
 * @return
 */
H
Haojun Liao 已提交
341
static bool hasNullValue(SQuery *pQuery, int32_t col, int32_t numOfCols, SDataStatis *pStatis, SDataStatis **pColStatis) {
342
  SColIndex *pColIndex = &pQuery->pSelectExpr[col].base.colInfo;
343
  if (TSDB_COL_IS_TAG(pColIndex->flag)) {
344 345
    return false;
  }
346

347 348 349 350
  // query on primary timestamp column, not null value at all
  if (pColIndex->colId == PRIMARYKEY_TIMESTAMP_COL_INDEX) {
    return false;
  }
351

352
  if (pStatis != NULL) {
H
Haojun Liao 已提交
353
    *pColStatis = getStatisInfo(pQuery, pStatis, numOfCols, col);
H
hjxilinx 已提交
354 355
  } else {
    *pColStatis = NULL;
356
  }
357

358 359 360
  if ((*pColStatis) != NULL && (*pColStatis)->numOfNull == 0) {
    return false;
  }
361

362 363 364 365 366 367
  return true;
}

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

369
  int32_t *p1 = (int32_t *) taosHashGet(pWindowResInfo->hashList, pData, bytes);
370 371 372 373 374
  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;
375

376 377 378 379 380 381 382
      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
      }
383

384 385 386 387 388 389
      for (int32_t i = pWindowResInfo->capacity; i < newCap; ++i) {
        SPosInfo pos = {-1, -1};
        createQueryResultInfo(pQuery, &pWindowResInfo->pResult[i], pRuntimeEnv->stableQuery, &pos);
      }
      pWindowResInfo->capacity = newCap;
    }
390

391 392 393 394
    // add a new result set for a new group
    pWindowResInfo->curIndex = pWindowResInfo->size++;
    taosHashPut(pWindowResInfo->hashList, pData, bytes, (char *)&pWindowResInfo->curIndex, sizeof(int32_t));
  }
395

396 397 398 399 400 401
  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};
402

403 404 405 406 407 408 409
  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;
  }
410

411 412
  if (w.skey > ts || w.ekey < ts) {
    int64_t st = w.skey;
413

414 415 416
    if (st > ts) {
      st -= ((st - ts + pQuery->slidingTime - 1) / pQuery->slidingTime) * pQuery->slidingTime;
    }
417

418 419 420 421
    int64_t et = st + pQuery->intervalTime - 1;
    if (et < ts) {
      st += ((ts - et + pQuery->slidingTime - 1) / pQuery->slidingTime) * pQuery->slidingTime;
    }
422

423 424 425
    w.skey = st;
    w.ekey = w.skey + pQuery->intervalTime - 1;
  }
426

427 428 429 430 431 432 433
  /*
   * 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;
  }
434

435
  assert(ts >= w.skey && ts <= w.ekey);
436

437 438 439 440 441 442 443 444
  return w;
}

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

446
  tFilePage *pData = NULL;
447

448 449 450
  // in the first scan, new space needed for results
  int32_t pageId = -1;
  SIDList list = getDataBufPagesIdList(pResultBuf, sid);
451

452 453 454 455
  if (list.size == 0) {
    pData = getNewDataBuf(pResultBuf, sid, &pageId);
  } else {
    pageId = getLastPageId(&list);
H
Haojun Liao 已提交
456
    pData = GET_RES_BUF_PAGE_BY_ID(pResultBuf, pageId);
457

458
    if (pData->num >= numOfRowsPerPage) {
459 460
      pData = getNewDataBuf(pResultBuf, sid, &pageId);
      if (pData != NULL) {
461
        assert(pData->num == 0);  // number of elements must be 0 for new allocated buffer
462 463 464
      }
    }
  }
465

466 467 468
  if (pData == NULL) {
    return -1;
  }
469

470 471 472
  // set the number of rows in current disk page
  if (pWindowRes->pos.pageId == -1) {  // not allocated yet, allocate new buffer
    pWindowRes->pos.pageId = pageId;
473
    pWindowRes->pos.rowId = pData->num++;
474
  }
475

476 477 478 479 480 481 482
  return 0;
}

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

484 485 486 487
  SWindowResult *pWindowRes = doSetTimeWindowFromKey(pRuntimeEnv, pWindowResInfo, (char *)&win->skey, TSDB_KEYSIZE);
  if (pWindowRes == NULL) {
    return -1;
  }
488

489 490 491 492 493 494 495
  // 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;
    }
  }
496

497 498
  // set time window for current result
  pWindowRes->window = *win;
499

H
Haojun Liao 已提交
500
  setWindowResOutputBufInitCtx(pRuntimeEnv, pWindowRes);
501 502 503 504 505 506 507 508
  return TSDB_CODE_SUCCESS;
}

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

H
Haojun Liao 已提交
509
static int32_t getForwardStepsInBlock(int32_t numOfRows, __block_search_fn_t searchFn, TSKEY ekey, int16_t pos,
510
                                      int16_t order, int64_t *pData) {
H
Haojun Liao 已提交
511
  int32_t endPos = searchFn((char *)pData, numOfRows, ekey, order);
512
  int32_t forwardStep = 0;
513

514
  if (endPos >= 0) {
515
    forwardStep = (order == TSDB_ORDER_ASC) ? (endPos - pos) : (pos - endPos);
516
    assert(forwardStep >= 0);
517

518 519 520 521 522
    // endPos data is equalled to the key so, we do need to read the element in endPos
    if (pData[endPos] == ekey) {
      forwardStep += 1;
    }
  }
523

524 525 526 527 528 529
  return forwardStep;
}

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

536
  // no qualified results exist, abort check
537 538
  int32_t numOfClosed = 0;
  
539
  if (pWindowResInfo->size == 0) {
540
    return pWindowResInfo->size;
541
  }
542

543
  // query completed
H
hjxilinx 已提交
544 545
  if ((lastKey >= pQuery->current->win.ekey && QUERY_IS_ASC_QUERY(pQuery)) ||
      (lastKey <= pQuery->current->win.ekey && !QUERY_IS_ASC_QUERY(pQuery))) {
546
    closeAllTimeWindow(pWindowResInfo);
547

548 549 550 551
    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;
552
    int64_t skey = TSKEY_INITIAL_VAL;
553

554 555 556
    for (i = 0; i < pWindowResInfo->size; ++i) {
      SWindowResult *pResult = &pWindowResInfo->pResult[i];
      if (pResult->status.closed) {
557
        numOfClosed += 1;
558 559
        continue;
      }
560

561 562 563 564 565 566 567 568
      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;
      }
    }
569

570
    // all windows are closed, set the last one to be the skey
571
    if (skey == TSKEY_INITIAL_VAL) {
572 573 574 575 576
      assert(i == pWindowResInfo->size);
      pWindowResInfo->curIndex = pWindowResInfo->size - 1;
    } else {
      pWindowResInfo->curIndex = i;
    }
577

578
    pWindowResInfo->prevSKey = pWindowResInfo->pResult[pWindowResInfo->curIndex].window.skey;
579

580 581
    // the number of completed slots are larger than the threshold, return current generated results to client.
    if (numOfClosed > pWindowResInfo->threshold) {
582
      qDebug("QInfo:%p total result window:%d closed:%d, reached the output threshold %d, return",
583 584
          GET_QINFO_ADDR(pRuntimeEnv), pWindowResInfo->size, numOfClosed, pQuery->rec.threshold);
      
585
      setQueryStatus(pQuery, QUERY_RESBUF_FULL);
586
    } else {
587
      qDebug("QInfo:%p total result window:%d already closed:%d", GET_QINFO_ADDR(pRuntimeEnv), pWindowResInfo->size,
588
             numOfClosed);
589 590
    }
  }
591 592 593 594 595 596 597
  
  // output has reached the limitation, set query completed
  if (pQuery->limit.limit > 0 && (pQuery->limit.limit + pQuery->limit.offset) <= numOfClosed &&
      pRuntimeEnv->scanFlag == MASTER_SCAN) {
    setQueryStatus(pQuery, QUERY_COMPLETED);
  }
  
598
  assert(pWindowResInfo->prevSKey != TSKEY_INITIAL_VAL);
599
  return numOfClosed;
600 601 602
}

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

606 607 608
  int32_t num = -1;
  int32_t order = pQuery->order.order;
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(order);
609

H
hjxilinx 已提交
610 611
  STableQueryInfo* item = pQuery->current;
  
612 613
  if (QUERY_IS_ASC_QUERY(pQuery)) {
    if (ekey < pDataBlockInfo->window.ekey) {
614
      num = getForwardStepsInBlock(pDataBlockInfo->rows, searchFn, ekey, startPos, order, pPrimaryColumn);
615 616 617 618
      if (num == 0) {  // no qualified data in current block, do not update the lastKey value
        assert(ekey < pPrimaryColumn[startPos]);
      } else {
        if (updateLastKey) {
H
hjxilinx 已提交
619
          item->lastKey = pPrimaryColumn[startPos + (num - 1)] + step;
620 621 622
        }
      }
    } else {
623
      num = pDataBlockInfo->rows - startPos;
624
      if (updateLastKey) {
H
hjxilinx 已提交
625
        item->lastKey = pDataBlockInfo->window.ekey + step;
626 627 628 629
      }
    }
  } else {  // desc
    if (ekey > pDataBlockInfo->window.skey) {
630
      num = getForwardStepsInBlock(pDataBlockInfo->rows, searchFn, ekey, startPos, order, pPrimaryColumn);
631 632 633 634
      if (num == 0) {  // no qualified data in current block, do not update the lastKey value
        assert(ekey > pPrimaryColumn[startPos]);
      } else {
        if (updateLastKey) {
H
hjxilinx 已提交
635
          item->lastKey = pPrimaryColumn[startPos - (num - 1)] + step;
636 637 638 639 640
        }
      }
    } else {
      num = startPos + 1;
      if (updateLastKey) {
H
hjxilinx 已提交
641
        item->lastKey = pDataBlockInfo->window.skey + step;
642 643 644
      }
    }
  }
645

646 647 648 649 650
  assert(num >= 0);
  return num;
}

static void doBlockwiseApplyFunctions(SQueryRuntimeEnv *pRuntimeEnv, SWindowStatus *pStatus, STimeWindow *pWin,
H
Haojun Liao 已提交
651
                                      int32_t offset, int32_t forwardStep, TSKEY *tsBuf, int32_t numOfTotal) {
652 653
  SQuery *        pQuery = pRuntimeEnv->pQuery;
  SQLFunctionCtx *pCtx = pRuntimeEnv->pCtx;
654

655
  if (IS_MASTER_SCAN(pRuntimeEnv) || pStatus->closed) {
656
    for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
657
      int32_t functionId = pQuery->pSelectExpr[k].base.functionId;
658

659 660
      pCtx[k].nStartQueryTimestamp = pWin->skey;
      pCtx[k].size = forwardStep;
H
Haojun Liao 已提交
661
      pCtx[k].startOffset = (QUERY_IS_ASC_QUERY(pQuery)) ? offset : offset - (forwardStep - 1);
662

663
      if ((aAggs[functionId].nStatus & TSDB_FUNCSTATE_SELECTIVITY) != 0) {
H
Haojun Liao 已提交
664
        pCtx[k].ptsList = &tsBuf[offset];
665
      }
666

H
Haojun Liao 已提交
667 668 669 670 671
      // not a whole block involved in query processing, statistics data can not be used
      if (forwardStep != numOfTotal) {
        pCtx[k].preAggVals.isSet = false;
      }
      
672 673 674 675 676 677 678 679 680 681 682
      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;
683

684
  if (IS_MASTER_SCAN(pRuntimeEnv) || pStatus->closed) {
685
    for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
686
      pCtx[k].nStartQueryTimestamp = pWin->skey;
687

688
      int32_t functionId = pQuery->pSelectExpr[k].base.functionId;
689 690 691 692 693 694 695 696
      if (functionNeedToExecute(pRuntimeEnv, &pCtx[k], functionId)) {
        aAggs[functionId].xFunctionF(&pCtx[k], offset);
      }
    }
  }
}

static int32_t getNextQualifiedWindow(SQueryRuntimeEnv *pRuntimeEnv, STimeWindow *pNextWin,
697 698
                                      SDataBlockInfo *pDataBlockInfo, TSKEY *primaryKeys,
                                      __block_search_fn_t searchFn) {
699
  SQuery *pQuery = pRuntimeEnv->pQuery;
700

H
Haojun Liao 已提交
701 702 703 704
  // tumbling time window query, a special case of sliding time window query
  if (pQuery->slidingTime == pQuery->intervalTime) {
    // todo opt
  }
705

H
Haojun Liao 已提交
706
  getNextTimeWindow(pQuery, pNextWin);
707

H
Haojun Liao 已提交
708 709 710 711 712
  // 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;
  }
713

H
Haojun Liao 已提交
714 715 716 717 718
  TSKEY startKey = -1;
  if (QUERY_IS_ASC_QUERY(pQuery)) {
    startKey = pNextWin->skey;
    if (startKey < pQuery->window.skey) {
      startKey = pQuery->window.skey;
719
    }
H
Haojun Liao 已提交
720 721 722 723
  } else {
    startKey = pNextWin->ekey;
    if (startKey > pQuery->window.skey) {
      startKey = pQuery->window.skey;
724
    }
H
Haojun Liao 已提交
725
  }
726

H
Haojun Liao 已提交
727
  int32_t startPos = searchFn((char *)primaryKeys, pDataBlockInfo->rows, startKey, pQuery->order.order);
728

H
Haojun Liao 已提交
729 730 731 732 733 734
  /*
   * This time window does not cover any data, try next time window,
   * this case may happen when the time window is too small
   */
  if (QUERY_IS_ASC_QUERY(pQuery) && primaryKeys[startPos] > pNextWin->ekey) {
    TSKEY next = primaryKeys[startPos];
735

H
Haojun Liao 已提交
736 737 738 739
    pNextWin->ekey += ((next - pNextWin->ekey + pQuery->slidingTime - 1)/pQuery->slidingTime) * pQuery->slidingTime;
    pNextWin->skey = pNextWin->ekey - pQuery->intervalTime + 1;
  } else if ((!QUERY_IS_ASC_QUERY(pQuery)) && primaryKeys[startPos] < pNextWin->skey) {
    TSKEY next = primaryKeys[startPos];
740

H
Haojun Liao 已提交
741 742
    pNextWin->skey -= ((pNextWin->skey - next + pQuery->slidingTime - 1) / pQuery->slidingTime) * pQuery->slidingTime;
    pNextWin->ekey = pNextWin->skey + pQuery->intervalTime - 1;
743
  }
744

H
Haojun Liao 已提交
745
  return startPos;
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
}

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;
    }
  }
761

762 763 764
  return ekey;
}

H
hjxilinx 已提交
765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
//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,
780
                    SArray *pDataBlock) {
dengyihao's avatar
dengyihao 已提交
781 782 783
  if (pDataBlock == NULL) {
    return NULL;
  }
784
  char *dataBlock = NULL;
785
  SQuery *pQuery = pRuntimeEnv->pQuery;
786

787
  SQLFunctionCtx *pCtx = pRuntimeEnv->pCtx;
788

789
  int32_t functionId = pQuery->pSelectExpr[col].base.functionId;
790
  if (functionId == TSDB_FUNC_ARITHM) {
791
    sas->pArithExpr = &pQuery->pSelectExpr[col];
792

793 794 795 796 797 798
    // 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);
    }
799

800 801 802 803
    sas->offset  = 0;
    sas->colList = pQuery->colList;
    sas->numOfCols = pQuery->numOfCols;
    sas->data    = calloc(pQuery->numOfCols, POINTER_BYTES);
804

805
    // here the pQuery->colList and sas->colList are identical
H
Haojun Liao 已提交
806
    int32_t numOfCols = taosArrayGetSize(pDataBlock);
807
    for (int32_t i = 0; i < pQuery->numOfCols; ++i) {
808
      SColumnInfo *pColMsg = &pQuery->colList[i];
809

810 811 812 813 814 815 816 817
      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;
        }
      }
818

819
      assert(dataBlock != NULL);
H
Haojun Liao 已提交
820
      sas->data[i] = dataBlock/* + pQuery->colList[i].bytes*/;  // start from the offset
821
    }
822

823
  } else {  // other type of query function
824
    SColIndex *pCol = &pQuery->pSelectExpr[col].base.colInfo;
825
    if (TSDB_COL_IS_TAG(pCol->flag) || pDataBlock == NULL) {
826 827
      dataBlock = NULL;
    } else {
H
hjxilinx 已提交
828
      dataBlock = getDataBlockImpl(pDataBlock, pCol->colId);
829 830
    }
  }
831

832 833 834 835
  return dataBlock;
}

/**
H
Haojun Liao 已提交
836
 * todo set the last value for pQueryTableInfo as in rowwiseapplyfunctions
837 838
 * @param pRuntimeEnv
 * @param forwardStep
839
 * @param tsCols
840 841 842 843 844
 * @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.
 */
845
static void blockwiseApplyFunctions(SQueryRuntimeEnv *pRuntimeEnv, SDataStatis *pStatis,
846 847
                                       SDataBlockInfo *pDataBlockInfo, SWindowResInfo *pWindowResInfo,
                                       __block_search_fn_t searchFn, SArray *pDataBlock) {
848
  SQLFunctionCtx *pCtx = pRuntimeEnv->pCtx;
849 850 851
  
  SQuery *pQuery = pRuntimeEnv->pQuery;
  TSKEY  *tsCols = NULL;
852
  if (pDataBlock != NULL) {
853
    SColumnInfoData* pColInfo = taosArrayGet(pDataBlock, 0);
854
    tsCols = (TSKEY *)(pColInfo->pData);
855
  }
856

857
  SArithmeticSupport *sasArray = calloc((size_t)pQuery->numOfOutput, sizeof(SArithmeticSupport));
858

859
  for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
H
hjxilinx 已提交
860
    char *dataBlock = getDataBlock(pRuntimeEnv, &sasArray[k], k, pDataBlockInfo->rows, pDataBlock);
861
    setExecParams(pQuery, &pCtx[k], dataBlock, tsCols, pDataBlockInfo, pStatis, &sasArray[k], k);
862
  }
863

864
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);
dengyihao's avatar
dengyihao 已提交
865
  if (isIntervalQuery(pQuery) && tsCols != NULL) {
866
    int32_t offset = GET_COL_DATA_POS(pQuery, 0, step);
867
    TSKEY   ts = tsCols[offset];
868

869
    STimeWindow win = getActiveTimeWindow(pWindowResInfo, ts, pQuery);
H
hjxilinx 已提交
870
    if (setWindowOutputBufByKey(pRuntimeEnv, pWindowResInfo, pDataBlockInfo->tid, &win) != TSDB_CODE_SUCCESS) {
dengyihao's avatar
dengyihao 已提交
871
      tfree(sasArray);
H
hjxilinx 已提交
872
      return;
873
    }
874

875 876
    TSKEY   ekey = reviseWindowEkey(pQuery, &win);
    int32_t forwardStep =
877
        getNumOfRowsInTimeWindow(pQuery, pDataBlockInfo, tsCols, pQuery->pos, ekey, searchFn, true);
878

879
    SWindowStatus *pStatus = getTimeWindowResStatus(pWindowResInfo, curTimeWindow(pWindowResInfo));
880
    doBlockwiseApplyFunctions(pRuntimeEnv, pStatus, &win, pQuery->pos, forwardStep, tsCols, pDataBlockInfo->rows);
881

882 883
    int32_t     index = pWindowResInfo->curIndex;
    STimeWindow nextWin = win;
884

885
    while (1) {
886
      int32_t startPos = getNextQualifiedWindow(pRuntimeEnv, &nextWin, pDataBlockInfo, tsCols, searchFn);
887 888 889
      if (startPos < 0) {
        break;
      }
890

891
      // null data, failed to allocate more memory buffer
H
hjxilinx 已提交
892
      if (setWindowOutputBufByKey(pRuntimeEnv, pWindowResInfo, pDataBlockInfo->tid, &nextWin) != TSDB_CODE_SUCCESS) {
893 894
        break;
      }
895

896
      ekey = reviseWindowEkey(pQuery, &nextWin);
897
      forwardStep = getNumOfRowsInTimeWindow(pQuery, pDataBlockInfo, tsCols, startPos, ekey, searchFn, true);
898

899
      pStatus = getTimeWindowResStatus(pWindowResInfo, curTimeWindow(pWindowResInfo));
900
      doBlockwiseApplyFunctions(pRuntimeEnv, pStatus, &nextWin, startPos, forwardStep, tsCols, pDataBlockInfo->rows);
901
    }
902

903 904 905 906 907 908 909
    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
     */
910
    for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
911
      int32_t functionId = pQuery->pSelectExpr[k].base.functionId;
912 913 914 915 916
      if (functionNeedToExecute(pRuntimeEnv, &pCtx[k], functionId)) {
        aAggs[functionId].xFunction(&pCtx[k]);
      }
    }
  }
917

918 919 920 921
  for(int32_t i = 0; i < pQuery->numOfOutput; ++i) {
    if (pQuery->pSelectExpr[i].base.functionId != TSDB_FUNC_ARITHM) {
      continue;
    }
922

923 924
    tfree(sasArray[i].data);
  }
925

926 927 928 929 930 931 932
  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;
  }
933

934
  int32_t GROUPRESULTID = 1;
935

936
  SDiskbasedResultBuf *pResultBuf = pRuntimeEnv->pResultBuf;
937

938 939 940 941 942 943 944 945 946 947 948
  int64_t v = -1;
  // not assign result buffer yet, add new result buffer
  switch(type) {
    case TSDB_DATA_TYPE_BOOL:
    case TSDB_DATA_TYPE_TINYINT:  v = GET_INT8_VAL(pData);  break;
    case TSDB_DATA_TYPE_SMALLINT: v = GET_INT16_VAL(pData); break;
    case TSDB_DATA_TYPE_INT:      v = GET_INT32_VAL(pData); break;
    case TSDB_DATA_TYPE_BIGINT:   v = GET_INT64_VAL(pData); break;
  }

//  assert(pRuntimeEnv->windowResInfo.hashList->size <= 2);
949 950 951 952
  SWindowResult *pWindowRes = doSetTimeWindowFromKey(pRuntimeEnv, &pRuntimeEnv->windowResInfo, pData, bytes);
  if (pWindowRes == NULL) {
    return -1;
  }
953

954 955 956
  pWindowRes->window.skey = v;
  pWindowRes->window.ekey = v;

957 958 959 960 961 962
  if (pWindowRes->pos.pageId == -1) {
    int32_t ret = addNewWindowResultBuf(pWindowRes, pResultBuf, GROUPRESULTID, pRuntimeEnv->numOfRowsPerPage);
    if (ret != 0) {
      return -1;
    }
  }
963

964 965 966 967 968
  setWindowResOutputBuf(pRuntimeEnv, pWindowRes);
  initCtxOutputBuf(pRuntimeEnv);
  return TSDB_CODE_SUCCESS;
}

969
static char *getGroupbyColumnData(SQuery *pQuery, int16_t *type, int16_t *bytes, SArray* pDataBlock) {
970
  SSqlGroupbyExpr *pGroupbyExpr = pQuery->pGroupbyExpr;
971

972
  for (int32_t k = 0; k < pGroupbyExpr->numOfGroupCols; ++k) {
973 974
    SColIndex* pColIndex = taosArrayGet(pGroupbyExpr->columnInfo, k);
    if (pColIndex->flag == TSDB_COL_TAG) {
975 976
      continue;
    }
977

978
    int16_t colIndex = -1;
979
    int32_t colId = pColIndex->colId;
980

981
    for (int32_t i = 0; i < pQuery->numOfCols; ++i) {
982
      if (pQuery->colList[i].colId == colId) {
983 984 985 986
        colIndex = i;
        break;
      }
    }
987

988
    assert(colIndex >= 0 && colIndex < pQuery->numOfCols);
989

990 991
    *type = pQuery->colList[colIndex].type;
    *bytes = pQuery->colList[colIndex].bytes;
992 993 994 995 996 997
    /*
     *  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);
998

999 1000 1001 1002 1003 1004
    for (int32_t i = 0; i < numOfCols; ++i) {
      SColumnInfoData *p = taosArrayGet(pDataBlock, i);
      if (pColIndex->colId == p->info.colId) {
        return p->pData;
      }
    }
1005
  }
1006

1007
  return NULL;
1008 1009 1010 1011
}

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

1013 1014
  STSElem         elem = tsBufGetElem(pRuntimeEnv->pTSBuf);
  SQLFunctionCtx *pCtx = pRuntimeEnv->pCtx;
1015

1016 1017 1018 1019
  // compare tag first
  if (pCtx[0].tag.i64Key != elem.tag) {
    return TS_JOIN_TAG_NOT_EQUALS;
  }
1020

1021 1022 1023
  TSKEY key = *(TSKEY *)(pCtx[0].aInputElemBuf + TSDB_KEYSIZE * offset);

#if defined(_DEBUG_VIEW)
1024 1025
  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,
1026 1027
         pRuntimeEnv->pTSBuf->cur.order, pRuntimeEnv->pTSBuf->cur.tsIndex);
#endif
1028

1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
  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);
    }
  }
1042

1043 1044 1045 1046 1047
  return TS_JOIN_TS_EQUAL;
}

static bool functionNeedToExecute(SQueryRuntimeEnv *pRuntimeEnv, SQLFunctionCtx *pCtx, int32_t functionId) {
  SResultInfo *pResInfo = GET_RES_INFO(pCtx);
H
hjxilinx 已提交
1048 1049
  SQuery* pQuery = pRuntimeEnv->pQuery;
  
1050 1051 1052
  if (pResInfo->complete || functionId == TSDB_FUNC_TAG_DUMMY || functionId == TSDB_FUNC_TS_DUMMY) {
    return false;
  }
1053

1054
  if (functionId == TSDB_FUNC_FIRST_DST || functionId == TSDB_FUNC_FIRST) {
H
hjxilinx 已提交
1055 1056
    return QUERY_IS_ASC_QUERY(pQuery);
  }
1057 1058 1059 1060 1061 1062 1063

  // todo add comments
  if ((functionId == TSDB_FUNC_LAST_DST || functionId == TSDB_FUNC_LAST)) {
    return pCtx->param[0].i64Key == pQuery->order.order;
//    return !QUERY_IS_ASC_QUERY(pQuery);
  }

1064
  // in the supplementary scan, only the following functions need to be executed
H
Haojun Liao 已提交
1065
  if (IS_REVERSE_SCAN(pRuntimeEnv)) {
1066 1067
    return false;
  }
1068

1069 1070 1071
  return true;
}

1072 1073
static void rowwiseApplyFunctions(SQueryRuntimeEnv *pRuntimeEnv, SDataStatis *pStatis, SDataBlockInfo *pDataBlockInfo,
    SWindowResInfo *pWindowResInfo, SArray *pDataBlock) {
1074
  SQLFunctionCtx *pCtx = pRuntimeEnv->pCtx;
1075

1076
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
1077
  STableQueryInfo* item = pQuery->current;
H
Haojun Liao 已提交
1078 1079 1080 1081 1082

  SColumnInfoData* pColumnInfoData = (SColumnInfoData *)taosArrayGet(pDataBlock, 0);

  TSKEY  *tsCols = (pColumnInfoData->info.type == TSDB_DATA_TYPE_TIMESTAMP)? (TSKEY*) pColumnInfoData->pData:NULL;
  bool    groupbyColumnValue = isGroupbyNormalCol(pQuery->pGroupbyExpr);
1083
  SArithmeticSupport *sasArray = calloc((size_t)pQuery->numOfOutput, sizeof(SArithmeticSupport));
1084

1085 1086
  int16_t type = 0;
  int16_t bytes = 0;
1087

1088
  char *groupbyColumnData = NULL;
H
Haojun Liao 已提交
1089
  if (groupbyColumnValue) {
1090
    groupbyColumnData = getGroupbyColumnData(pQuery, &type, &bytes, pDataBlock);
1091
  }
1092

1093
  for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
H
hjxilinx 已提交
1094
    char *dataBlock = getDataBlock(pRuntimeEnv, &sasArray[k], k, pDataBlockInfo->rows, pDataBlock);
1095
    setExecParams(pQuery, &pCtx[k], dataBlock, tsCols, pDataBlockInfo, pStatis, &sasArray[k], k);
1096
  }
1097

1098 1099
  // set the input column data
  for (int32_t k = 0; k < pQuery->numOfFilterCols; ++k) {
1100
    SSingleColumnFilterInfo *pFilterInfo = &pQuery->pFilterInfo[k];
H
hjxilinx 已提交
1101 1102
    pFilterInfo->pData = getDataBlockImpl(pDataBlock, pFilterInfo->info.colId);
    assert(pFilterInfo->pData != NULL);
1103
  }
1104

1105
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);
1106

1107 1108 1109
  // from top to bottom in desc
  // from bottom to top in asc order
  if (pRuntimeEnv->pTSBuf != NULL) {
H
Haojun Liao 已提交
1110
    SQInfo *pQInfo = (SQInfo *)GET_QINFO_ADDR(pRuntimeEnv);
1111
    qDebug("QInfo:%p process data rows, numOfRows:%d, query order:%d, ts comp order:%d", pQInfo, pDataBlockInfo->rows,
1112 1113
           pQuery->order.order, pRuntimeEnv->pTSBuf->cur.order);
  }
1114

1115
  int32_t j = 0;
H
hjxilinx 已提交
1116
  int32_t offset = -1;
1117

1118
  for (j = 0; j < pDataBlockInfo->rows; ++j) {
H
hjxilinx 已提交
1119
    offset = GET_COL_DATA_POS(pQuery, j, step);
1120

1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
    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);
      }
    }
1131

1132
    if (pQuery->numOfFilterCols > 0 && (!doFilterData(pQuery, offset))) {
1133 1134
      continue;
    }
1135

1136 1137 1138
    // interval window query
    if (isIntervalQuery(pQuery)) {
      // decide the time window according to the primary timestamp
1139
      int64_t     ts = tsCols[offset];
1140
      STimeWindow win = getActiveTimeWindow(pWindowResInfo, ts, pQuery);
1141

H
hjxilinx 已提交
1142
      int32_t ret = setWindowOutputBufByKey(pRuntimeEnv, pWindowResInfo, pDataBlockInfo->tid, &win);
1143 1144 1145
      if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
        continue;
      }
1146

1147 1148
      SWindowStatus *pStatus = getTimeWindowResStatus(pWindowResInfo, curTimeWindow(pWindowResInfo));
      doRowwiseApplyFunctions(pRuntimeEnv, pStatus, &win, offset);
1149

1150 1151
      STimeWindow nextWin = win;
      int32_t     index = pWindowResInfo->curIndex;
1152

1153 1154
      while (1) {
        getNextTimeWindow(pQuery, &nextWin);
H
Haojun Liao 已提交
1155
        if (/*pWindowResInfo->startTime > nextWin.skey ||*/
1156
            (nextWin.skey > pQuery->window.ekey && QUERY_IS_ASC_QUERY(pQuery)) ||
H
Haojun Liao 已提交
1157
            (nextWin.skey < pQuery->window.ekey && !QUERY_IS_ASC_QUERY(pQuery))) {
1158 1159
          break;
        }
1160

1161 1162 1163
        if (ts < nextWin.skey || ts > nextWin.ekey) {
          break;
        }
1164

1165
        // null data, failed to allocate more memory buffer
H
hjxilinx 已提交
1166
        if (setWindowOutputBufByKey(pRuntimeEnv, pWindowResInfo, pDataBlockInfo->tid, &nextWin) != TSDB_CODE_SUCCESS) {
1167 1168
          break;
        }
1169

1170 1171 1172
        pStatus = getTimeWindowResStatus(pWindowResInfo, curTimeWindow(pWindowResInfo));
        doRowwiseApplyFunctions(pRuntimeEnv, pStatus, &nextWin, offset);
      }
1173

1174 1175 1176
      pWindowResInfo->curIndex = index;
    } else {  // other queries
      // decide which group this rows belongs to according to current state value
H
Haojun Liao 已提交
1177
      if (groupbyColumnValue) {
H
hjxilinx 已提交
1178
        char *val = groupbyColumnData + bytes * offset;
1179

H
hjxilinx 已提交
1180
        int32_t ret = setGroupResultOutputBuf(pRuntimeEnv, val, type, bytes);
1181 1182 1183 1184
        if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
          continue;
        }
      }
1185

1186
      for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
1187
        int32_t functionId = pQuery->pSelectExpr[k].base.functionId;
1188 1189 1190 1191 1192
        if (functionNeedToExecute(pRuntimeEnv, &pCtx[k], functionId)) {
          aAggs[functionId].xFunctionF(&pCtx[k], offset);
        }
      }
    }
1193

1194 1195 1196
    if (pRuntimeEnv->pTSBuf != NULL) {
      // if timestamp filter list is empty, quit current query
      if (!tsBufNextPos(pRuntimeEnv->pTSBuf)) {
H
hjxilinx 已提交
1197
        setQueryStatus(pQuery, QUERY_COMPLETED);
1198 1199 1200 1201
        break;
      }
    }
  }
H
Haojun Liao 已提交
1202 1203 1204 1205 1206 1207 1208 1209

  assert(offset >= 0);
  if (tsCols != NULL) {
    item->lastKey = tsCols[offset] + step;
  } else {
    item->lastKey = (QUERY_IS_ASC_QUERY(pQuery)? pDataBlockInfo->window.ekey:pDataBlockInfo->window.skey) + step;
  }

1210 1211 1212 1213 1214
  // todo refactor: extract method
  for(int32_t i = 0; i < pQuery->numOfOutput; ++i) {
    if (pQuery->pSelectExpr[i].base.functionId != TSDB_FUNC_ARITHM) {
      continue;
    }
1215

1216 1217
    tfree(sasArray[i].data);
  }
1218

1219 1220 1221 1222
  free(sasArray);
}

static int32_t tableApplyFunctionsOnBlock(SQueryRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pDataBlockInfo,
H
hjxilinx 已提交
1223
                                          SDataStatis *pStatis, __block_search_fn_t searchFn, SArray *pDataBlock) {
H
hjxilinx 已提交
1224
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
1225 1226 1227
  
  STableQueryInfo* pTableQInfo = pQuery->current;
  SWindowResInfo*  pWindowResInfo = &pRuntimeEnv->windowResInfo;
H
hjxilinx 已提交
1228
  
1229
  if (pQuery->numOfFilterCols > 0 || pRuntimeEnv->pTSBuf != NULL || isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
1230
    rowwiseApplyFunctions(pRuntimeEnv, pStatis, pDataBlockInfo, pWindowResInfo, pDataBlock);
1231
  } else {
1232
    blockwiseApplyFunctions(pRuntimeEnv, pStatis, pDataBlockInfo, pWindowResInfo, searchFn, pDataBlock);
1233
  }
1234

1235
  // update the lastkey of current table
1236
  TSKEY lastKey = QUERY_IS_ASC_QUERY(pQuery) ? pDataBlockInfo->window.ekey : pDataBlockInfo->window.skey;
H
hjxilinx 已提交
1237
  pTableQInfo->lastKey = lastKey + GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);
1238

1239
  // interval query with limit applied
1240 1241 1242 1243 1244
  int32_t numOfRes = 0;
  if (isIntervalQuery(pQuery)) {
    numOfRes = doCheckQueryCompleted(pRuntimeEnv, lastKey, pWindowResInfo);
  } else {
    numOfRes = getNumOfResult(pRuntimeEnv);
1245

1246 1247 1248 1249
    // update the number of output result
    if (numOfRes > 0 && pQuery->checkBuffer == 1) {
      assert(numOfRes >= pQuery->rec.rows);
      pQuery->rec.rows = numOfRes;
1250

1251 1252 1253
      if (numOfRes >= pQuery->rec.threshold) {
        setQueryStatus(pQuery, QUERY_RESBUF_FULL);
      }
1254

1255 1256 1257
      if ((pQuery->limit.limit >= 0) && (pQuery->limit.limit + pQuery->limit.offset) <= numOfRes) {
        setQueryStatus(pQuery, QUERY_COMPLETED);
      }
H
Haojun Liao 已提交
1258
    }
1259
  }
1260

1261
  return numOfRes;
1262 1263
}

H
Haojun Liao 已提交
1264
void setExecParams(SQuery *pQuery, SQLFunctionCtx *pCtx, void* inputData, TSKEY *tsCol, SDataBlockInfo* pBlockInfo,
1265 1266 1267 1268 1269 1270 1271
                   SDataStatis *pStatis, void *param, int32_t colIndex) {
  
  int32_t functionId = pQuery->pSelectExpr[colIndex].base.functionId;
  int32_t colId = pQuery->pSelectExpr[colIndex].base.colInfo.colId;
  
  SDataStatis *tpField = NULL;
  pCtx->hasNull = hasNullValue(pQuery, colIndex, pBlockInfo->numOfCols, pStatis, &tpField);
1272
  pCtx->aInputElemBuf = inputData;
1273

1274
  if (tpField != NULL) {
H
Haojun Liao 已提交
1275
    pCtx->preAggVals.isSet  = true;
1276 1277
    pCtx->preAggVals.statis = *tpField;
    assert(pCtx->preAggVals.statis.numOfNull <= pBlockInfo->rows);
1278 1279 1280
  } else {
    pCtx->preAggVals.isSet = false;
  }
1281

H
Haojun Liao 已提交
1282 1283 1284
  // limit/offset query will affect this value
  pCtx->startOffset = QUERY_IS_ASC_QUERY(pQuery) ? pQuery->pos:0;
  pCtx->size = QUERY_IS_ASC_QUERY(pQuery) ? pBlockInfo->rows - pQuery->pos : pQuery->pos + 1;
1285

1286 1287
  uint32_t status = aAggs[functionId].nStatus;
  if (((status & (TSDB_FUNCSTATE_SELECTIVITY | TSDB_FUNCSTATE_NEED_TS)) != 0) && (tsCol != NULL)) {
H
Haojun Liao 已提交
1288
    pCtx->ptsList = tsCol;
1289
  }
1290

1291 1292 1293 1294 1295
  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 ||
1296
             functionId == TSDB_FUNC_DIFF || (functionId >= TSDB_FUNC_RATE && functionId <= TSDB_FUNC_AVG_IRATE)) {
1297
    /*
H
Haojun Liao 已提交
1298
     * least squares function needs two columns of input, currently, the x value of linear equation is set to
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
     * 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;
    }
1309

1310 1311
  } else if (functionId == TSDB_FUNC_ARITHM) {
    pCtx->param[1].pz = param;
H
Haojun Liao 已提交
1312 1313 1314 1315 1316 1317
  } else if (functionId == TSDB_FUNC_SPREAD) {  // set the statistics data for primary time stamp column
    if (colId == PRIMARYKEY_TIMESTAMP_COL_INDEX) {
      pCtx->preAggVals.isSet  = true;
      pCtx->preAggVals.statis.min = pBlockInfo->window.skey;
      pCtx->preAggVals.statis.max = pBlockInfo->window.ekey;
    }
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
  } else if (functionId == TSDB_FUNC_INTERP) {
    SInterpInfoDetail *pInterpInfo = GET_RES_INFO(pCtx)->interResultBuf;
    pInterpInfo->type = pQuery->fillType;
    pInterpInfo->ts = pQuery->window.skey;
    pInterpInfo->primaryCol = (colId == PRIMARYKEY_TIMESTAMP_COL_INDEX);
  
    if (pQuery->fillVal != NULL) {
      if (isNull((const char*) &pQuery->fillVal[colIndex], pCtx->inputType)) {
        pCtx->param[1].nType = TSDB_DATA_TYPE_NULL;
      } else { // todo refactor, tVariantCreateFromBinary should handle the NULL value
        tVariantCreateFromBinary(&pCtx->param[1], (char*) &pQuery->fillVal[colIndex], pCtx->inputBytes, pCtx->inputType);
      }
    }
1331
  }
1332

1333 1334 1335 1336 1337 1338
#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)) {
1339
//        qDebug("QInfo:%p query ts:%lld-%lld, offset:%d, rows:%d, bstatus:%d,
1340 1341 1342
//        functId:%d", GET_QINFO_ADDR(pQuery),
//               s, e, startOffset, size, blockStatus, functionId);
//    } else {
1343
//        qDebug("QInfo:%p block not loaded, bstatus:%d",
1344 1345 1346 1347 1348 1349 1350 1351
//        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)) {
1352
    int32_t num = 0;
1353
    int16_t tagLen = 0;
1354 1355
    
    SQLFunctionCtx *p = NULL;
1356
    SQLFunctionCtx **pTagCtx = calloc(pQuery->numOfOutput, POINTER_BYTES);
1357
    
1358
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1359
      SSqlFuncMsg *pSqlFuncMsg = &pQuery->pSelectExpr[i].base;
1360
      
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
      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
      }
    }
dengyihao's avatar
dengyihao 已提交
1374 1375 1376 1377 1378 1379 1380
    if (p != NULL) {
      p->tagInfo.pTagCtxList = pTagCtx;
      p->tagInfo.numOfTagCols = num;
      p->tagInfo.tagsLen = tagLen;
    } else {
      tfree(pTagCtx); 
    }
1381 1382 1383 1384
  }
}

static void setWindowResultInfo(SResultInfo *pResultInfo, SQuery *pQuery, bool isStableQuery) {
1385
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1386 1387
    assert(pQuery->pSelectExpr[i].interBytes <= DEFAULT_INTERN_BUF_PAGE_SIZE);
    
1388
    setResultInfoBuf(&pResultInfo[i], pQuery->pSelectExpr[i].interBytes, isStableQuery);
1389 1390 1391
  }
}

1392
static int32_t setupQueryRuntimeEnv(SQueryRuntimeEnv *pRuntimeEnv, int16_t order) {
1393
  qDebug("QInfo:%p setup runtime env", GET_QINFO_ADDR(pRuntimeEnv));
1394 1395
  SQuery *pQuery = pRuntimeEnv->pQuery;

1396 1397
  pRuntimeEnv->resultInfo = calloc(pQuery->numOfOutput, sizeof(SResultInfo));
  pRuntimeEnv->pCtx = (SQLFunctionCtx *)calloc(pQuery->numOfOutput, sizeof(SQLFunctionCtx));
1398

1399
  if (pRuntimeEnv->resultInfo == NULL || pRuntimeEnv->pCtx == NULL) {
1400
    goto _clean;
1401
  }
1402

1403
  pRuntimeEnv->offset[0] = 0;
1404
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1405
    SSqlFuncMsg *pSqlFuncMsg = &pQuery->pSelectExpr[i].base;
1406

1407
    SQLFunctionCtx *pCtx = &pRuntimeEnv->pCtx[i];
1408
    SColIndex* pIndex = &pSqlFuncMsg->colInfo;
1409

1410 1411
    int32_t index = pSqlFuncMsg->colInfo.colIndex;
    if (TSDB_COL_IS_TAG(pIndex->flag)) {
1412
      if (pIndex->colId == TSDB_TBNAME_COLUMN_INDEX) {  // todo refactor
H
Haojun Liao 已提交
1413 1414 1415 1416
        SSchema s = tGetTableNameColumnSchema();

        pCtx->inputBytes = s.bytes;
        pCtx->inputType = s.type;
1417 1418 1419 1420
      } else {
        pCtx->inputBytes = pQuery->tagColList[index].bytes;
        pCtx->inputType = pQuery->tagColList[index].type;
      }
1421
      
1422 1423 1424 1425
    } else {
      pCtx->inputBytes = pQuery->colList[index].bytes;
      pCtx->inputType = pQuery->colList[index].type;
    }
1426
  
1427
    assert(isValidDataType(pCtx->inputType));
1428
    pCtx->ptsOutputBuf = NULL;
1429

1430 1431
    pCtx->outputBytes = pQuery->pSelectExpr[i].bytes;
    pCtx->outputType = pQuery->pSelectExpr[i].type;
1432

1433 1434
    pCtx->order = pQuery->order.order;
    pCtx->functionId = pSqlFuncMsg->functionId;
1435

1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
    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);
      }
    }
1446

1447 1448
    // set the order information for top/bottom query
    int32_t functionId = pCtx->functionId;
1449

1450
    if (functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM || functionId == TSDB_FUNC_DIFF) {
1451
      int32_t f = pQuery->pSelectExpr[0].base.functionId;
1452
      assert(f == TSDB_FUNC_TS || f == TSDB_FUNC_TS_DUMMY);
1453

1454 1455 1456 1457
      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;
1458

1459 1460
      pCtx->param[1].i64Key = pQuery->order.orderColId;
    }
1461

1462 1463 1464 1465
    if (i > 0) {
      pRuntimeEnv->offset[i] = pRuntimeEnv->offset[i - 1] + pRuntimeEnv->pCtx[i - 1].outputBytes;
    }
  }
1466

1467
  // set the intermediate result output buffer
1468
  setWindowResultInfo(pRuntimeEnv->resultInfo, pQuery, pRuntimeEnv->stableQuery);
1469

1470
  // if it is group by normal column, do not set output buffer, the output buffer is pResult
1471
  if (!isGroupbyNormalCol(pQuery->pGroupbyExpr) && !pRuntimeEnv->stableQuery) {
1472 1473
    resetCtxOutputBuf(pRuntimeEnv);
  }
1474

1475 1476
  setCtxTagColumnInfo(pQuery, pRuntimeEnv->pCtx);
  return TSDB_CODE_SUCCESS;
1477

1478
_clean:
1479 1480
  tfree(pRuntimeEnv->resultInfo);
  tfree(pRuntimeEnv->pCtx);
1481

1482
  return TSDB_CODE_QRY_OUT_OF_MEMORY;
1483 1484 1485 1486 1487 1488
}

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

1490
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
1491
  SQInfo* pQInfo = (SQInfo*) GET_QINFO_ADDR(pRuntimeEnv);
1492

1493
  qDebug("QInfo:%p teardown runtime env", pQInfo);
1494
  cleanupTimeWindowInfo(&pRuntimeEnv->windowResInfo, pQuery->numOfOutput);
1495

1496
  if (pRuntimeEnv->pCtx != NULL) {
1497
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1498
      SQLFunctionCtx *pCtx = &pRuntimeEnv->pCtx[i];
1499

1500 1501 1502
      for (int32_t j = 0; j < pCtx->numOfParams; ++j) {
        tVariantDestroy(&pCtx->param[j]);
      }
1503

1504 1505 1506 1507
      tVariantDestroy(&pCtx->tag);
      tfree(pCtx->tagInfo.pTagCtxList);
      tfree(pRuntimeEnv->resultInfo[i].interResultBuf);
    }
1508

1509 1510 1511
    tfree(pRuntimeEnv->resultInfo);
    tfree(pRuntimeEnv->pCtx);
  }
1512

H
Haojun Liao 已提交
1513
  pRuntimeEnv->pFillInfo = taosDestoryFillInfo(pRuntimeEnv->pFillInfo);
1514

H
hjxilinx 已提交
1515
  destroyResultBuf(pRuntimeEnv->pResultBuf, pQInfo);
1516
  tsdbCleanupQueryHandle(pRuntimeEnv->pQueryHandle);
1517
  tsdbCleanupQueryHandle(pRuntimeEnv->pSecQueryHandle);
1518

1519 1520 1521
  pRuntimeEnv->pTSBuf = tsBufDestory(pRuntimeEnv->pTSBuf);
}

1522
static bool isQueryKilled(SQInfo *pQInfo) {
1523
  return false;
1524
  return (pQInfo->code == TSDB_CODE_TSC_QUERY_CANCELLED);
1525 1526
}

1527
static void setQueryKilled(SQInfo *pQInfo) { pQInfo->code = TSDB_CODE_TSC_QUERY_CANCELLED; }
H
hjxilinx 已提交
1528

H
hjxilinx 已提交
1529
static bool isFixedOutputQuery(SQuery *pQuery) {
1530 1531 1532
  if (pQuery->intervalTime != 0) {
    return false;
  }
1533

1534 1535 1536 1537
  // Note:top/bottom query is fixed output query
  if (isTopBottomQuery(pQuery) || isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
    return true;
  }
1538

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

1542 1543
    // ignore the ts_comp function
    if (i == 0 && pExprMsg->functionId == TSDB_FUNC_PRJ && pExprMsg->numOfParams == 1 &&
1544
        pExprMsg->colInfo.colIndex == PRIMARYKEY_TIMESTAMP_COL_INDEX) {
1545 1546
      continue;
    }
1547

1548 1549 1550
    if (pExprMsg->functionId == TSDB_FUNC_TS || pExprMsg->functionId == TSDB_FUNC_TS_DUMMY) {
      continue;
    }
1551

1552 1553 1554 1555
    if (!IS_MULTIOUTPUT(aAggs[pExprMsg->functionId].nStatus)) {
      return true;
    }
  }
1556

1557 1558 1559
  return false;
}

1560
// todo refactor with isLastRowQuery
H
hjxilinx 已提交
1561
static bool isPointInterpoQuery(SQuery *pQuery) {
1562
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1563
    int32_t functionID = pQuery->pSelectExpr[i].base.functionId;
1564
    if (functionID == TSDB_FUNC_INTERP) {
1565 1566 1567
      return true;
    }
  }
1568

1569 1570 1571 1572
  return false;
}

// TODO REFACTOR:MERGE WITH CLIENT-SIDE FUNCTION
H
hjxilinx 已提交
1573
static bool isSumAvgRateQuery(SQuery *pQuery) {
1574
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1575
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
1576 1577 1578
    if (functionId == TSDB_FUNC_TS) {
      continue;
    }
1579

1580 1581 1582 1583 1584
    if (functionId == TSDB_FUNC_SUM_RATE || functionId == TSDB_FUNC_SUM_IRATE || functionId == TSDB_FUNC_AVG_RATE ||
        functionId == TSDB_FUNC_AVG_IRATE) {
      return true;
    }
  }
1585

1586 1587 1588
  return false;
}

H
hjxilinx 已提交
1589
static bool isFirstLastRowQuery(SQuery *pQuery) {
1590
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1591
    int32_t functionID = pQuery->pSelectExpr[i].base.functionId;
1592 1593 1594 1595
    if (functionID == TSDB_FUNC_LAST_ROW) {
      return true;
    }
  }
1596

1597 1598 1599
  return false;
}

H
hjxilinx 已提交
1600
static bool needReverseScan(SQuery *pQuery) {
1601
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1602
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
1603 1604 1605
    if (functionId == TSDB_FUNC_TS || functionId == TSDB_FUNC_TS_DUMMY || functionId == TSDB_FUNC_TAG) {
      continue;
    }
1606

1607
    if ((functionId == TSDB_FUNC_FIRST || functionId == TSDB_FUNC_FIRST_DST) && !QUERY_IS_ASC_QUERY(pQuery)) {
1608 1609
      return true;
    }
1610 1611 1612 1613 1614

    if (functionId == TSDB_FUNC_LAST || functionId == TSDB_FUNC_LAST_DST) {
      int32_t order = pQuery->pSelectExpr[i].base.arg->argValue.i64;
      return order != pQuery->order.order;
    }
1615
  }
1616

1617 1618
  return false;
}
H
hjxilinx 已提交
1619 1620 1621

static bool onlyQueryTags(SQuery* pQuery) {
  for(int32_t i = 0; i < pQuery->numOfOutput; ++i) {
H
Haojun Liao 已提交
1622 1623 1624 1625 1626
    SExprInfo* pExprInfo = &pQuery->pSelectExpr[i];

    int32_t functionId = pExprInfo->base.functionId;
    if (functionId != TSDB_FUNC_TAGPRJ && functionId != TSDB_FUNC_TID_TAG &&
        (!(functionId == TSDB_FUNC_COUNT && pExprInfo->base.colInfo.colId == TSDB_TBNAME_COLUMN_INDEX))) {
H
hjxilinx 已提交
1627 1628 1629
      return false;
    }
  }
1630

H
hjxilinx 已提交
1631 1632 1633
  return true;
}

1634 1635
/////////////////////////////////////////////////////////////////////////////////////////////

H
Haojun Liao 已提交
1636
void getAlignQueryTimeWindow(SQuery *pQuery, int64_t key, int64_t keyFirst, int64_t keyLast, STimeWindow *realWin, STimeWindow *win) {
1637
  assert(key >= keyFirst && key <= keyLast && pQuery->slidingTime <= pQuery->intervalTime);
1638

1639
  win->skey = taosGetIntervalStartTimestamp(key, pQuery->slidingTime, pQuery->slidingTimeUnit, pQuery->precision);
1640

1641 1642 1643 1644 1645 1646
  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);
1647

H
Haojun Liao 已提交
1648 1649
    realWin->skey = keyFirst;
    realWin->ekey = keyLast;
1650

1651 1652 1653
    win->ekey = INT64_MAX;
    return;
  }
1654

1655
  win->ekey = win->skey + pQuery->intervalTime - 1;
1656

H
Haojun Liao 已提交
1657 1658
  realWin->skey = (win->skey < keyFirst)? keyFirst : win->skey;
  realWin->ekey = (win->ekey < keyLast) ? win->ekey : keyLast;
1659 1660 1661 1662
}

static void setScanLimitationByResultBuffer(SQuery *pQuery) {
  if (isTopBottomQuery(pQuery)) {
1663
    pQuery->checkBuffer = 0;
1664
  } else if (isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
1665
    pQuery->checkBuffer = 0;
1666 1667
  } else {
    bool hasMultioutput = false;
1668
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1669
      SSqlFuncMsg *pExprMsg = &pQuery->pSelectExpr[i].base;
1670 1671 1672
      if (pExprMsg->functionId == TSDB_FUNC_TS || pExprMsg->functionId == TSDB_FUNC_TS_DUMMY) {
        continue;
      }
1673

1674 1675 1676 1677 1678
      hasMultioutput = IS_MULTIOUTPUT(aAggs[pExprMsg->functionId].nStatus);
      if (!hasMultioutput) {
        break;
      }
    }
1679

1680
    pQuery->checkBuffer = hasMultioutput ? 1 : 0;
1681 1682 1683 1684 1685 1686
  }
}

/*
 * todo add more parameters to check soon..
 */
1687
bool colIdCheck(SQuery *pQuery) {
1688 1689
  // load data column information is incorrect
  for (int32_t i = 0; i < pQuery->numOfCols - 1; ++i) {
1690
    if (pQuery->colList[i].colId == pQuery->colList[i + 1].colId) {
S
slguan 已提交
1691
      qError("QInfo:%p invalid data load column for query", GET_QINFO_ADDR(pQuery));
1692 1693 1694
      return false;
    }
  }
1695
  
1696 1697 1698 1699 1700 1701
  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) {
1702
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1703
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
1704

1705 1706 1707 1708
    if (functionId == TSDB_FUNC_TS || functionId == TSDB_FUNC_TS_DUMMY || functionId == TSDB_FUNC_TAG ||
        functionId == TSDB_FUNC_TAG_DUMMY) {
      continue;
    }
1709

1710 1711 1712 1713
    if (functionId != functId && functionId != functIdDst) {
      return false;
    }
  }
1714

1715 1716 1717 1718 1719 1720 1721
  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); }

H
Haojun Liao 已提交
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735
// todo refactor, add iterator
static void doExchangeTimeWindow(SQInfo* pQInfo) {
  size_t t = GET_NUM_OF_TABLEGROUP(pQInfo);
  for(int32_t i = 0; i < t; ++i) {
    SArray* p1 = GET_TABLEGROUP(pQInfo, i);

    size_t len = taosArrayGetSize(p1);
    for(int32_t j = 0; j < len; ++j) {
      STableQueryInfo* pTableQueryInfo = (STableQueryInfo*) taosArrayGetP(p1, j);
      SWAP(pTableQueryInfo->win.skey, pTableQueryInfo->win.ekey, TSKEY);
    }
  }
}

H
Haojun Liao 已提交
1736 1737 1738
static void changeExecuteScanOrder(SQInfo *pQInfo, bool stableQuery) {
  SQuery* pQuery = pQInfo->runtimeEnv.pQuery;

1739 1740 1741
  // 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;
1742

1743 1744 1745
  // 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)) {
1746
    qDebug("QInfo:%p scan order changed for last_row query, old:%d, new:%d", GET_QINFO_ADDR(pQuery),
1747
           pQuery->order.order, TSDB_ORDER_DESC);
1748

1749
    pQuery->order.order = TSDB_ORDER_DESC;
1750

1751 1752
    int64_t skey = MIN(pQuery->window.skey, pQuery->window.ekey);
    int64_t ekey = MAX(pQuery->window.skey, pQuery->window.ekey);
1753

1754 1755
    pQuery->window.skey = ekey;
    pQuery->window.ekey = skey;
1756

1757 1758
    return;
  }
1759

1760 1761
  if (isPointInterpoQuery(pQuery) && pQuery->intervalTime == 0) {
    if (!QUERY_IS_ASC_QUERY(pQuery)) {
1762
      qDebug(msg, GET_QINFO_ADDR(pQuery), "interp", pQuery->order.order, TSDB_ORDER_ASC, pQuery->window.skey,
1763
             pQuery->window.ekey, pQuery->window.ekey, pQuery->window.skey);
1764 1765
      SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);
    }
1766

1767
    pQuery->order.order = TSDB_ORDER_ASC;
1768 1769
    return;
  }
1770

1771 1772 1773
  if (pQuery->intervalTime == 0) {
    if (onlyFirstQuery(pQuery)) {
      if (!QUERY_IS_ASC_QUERY(pQuery)) {
1774
        qDebug(msg, GET_QINFO_ADDR(pQuery), "only-first", pQuery->order.order, TSDB_ORDER_ASC, pQuery->window.skey,
1775 1776
               pQuery->window.ekey, pQuery->window.ekey, pQuery->window.skey);

1777
        SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);
H
Haojun Liao 已提交
1778
        doExchangeTimeWindow(pQInfo);
1779
      }
1780

1781
      pQuery->order.order = TSDB_ORDER_ASC;
1782 1783
    } else if (onlyLastQuery(pQuery)) {
      if (QUERY_IS_ASC_QUERY(pQuery)) {
1784
        qDebug(msg, GET_QINFO_ADDR(pQuery), "only-last", pQuery->order.order, TSDB_ORDER_DESC, pQuery->window.skey,
1785 1786
               pQuery->window.ekey, pQuery->window.ekey, pQuery->window.skey);

1787
        SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);
H
Haojun Liao 已提交
1788
        doExchangeTimeWindow(pQInfo);
1789
      }
1790

1791
      pQuery->order.order = TSDB_ORDER_DESC;
1792
    }
1793

1794
  } else {  // interval query
1795
    if (stableQuery) {
1796 1797
      if (onlyFirstQuery(pQuery)) {
        if (!QUERY_IS_ASC_QUERY(pQuery)) {
1798
          qDebug(msg, GET_QINFO_ADDR(pQuery), "only-first stable", pQuery->order.order, TSDB_ORDER_ASC,
1799 1800
                 pQuery->window.skey, pQuery->window.ekey, pQuery->window.ekey, pQuery->window.skey);

1801 1802
          SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);
        }
1803

1804
        pQuery->order.order = TSDB_ORDER_ASC;
1805 1806
      } else if (onlyLastQuery(pQuery)) {
        if (QUERY_IS_ASC_QUERY(pQuery)) {
1807
          qDebug(msg, GET_QINFO_ADDR(pQuery), "only-last stable", pQuery->order.order, TSDB_ORDER_DESC,
1808 1809
                 pQuery->window.skey, pQuery->window.ekey, pQuery->window.ekey, pQuery->window.skey);

1810 1811
          SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);
        }
1812

1813
        pQuery->order.order = TSDB_ORDER_DESC;
1814 1815 1816 1817 1818 1819 1820 1821
      }
    }
  }
}

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

1823
  int32_t num = 0;
1824

1825 1826 1827
  if (isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
    num = 128;
  } else if (isIntervalQuery(pQuery)) {  // time window query, allocate one page for each table
1828
    size_t s = pQInfo->tableqinfoGroupInfo.numOfTables;
1829
    num = MAX(s, INITIAL_RESULT_ROWS_VALUE);
1830 1831
  } else {    // for super table query, one page for each subset
    num = 1;  // pQInfo->pSidSet->numOfSubSet;
1832
  }
1833

1834 1835 1836 1837
  assert(num > 0);
  return num;
}

H
Haojun Liao 已提交
1838
#define GET_ROW_PARAM_FOR_MULTIOUTPUT(_q, tbq, sq) (((tbq) && (!sq))? (_q)->pSelectExpr[1].base.arg->argValue.i64:1)
1839

H
Haojun Liao 已提交
1840 1841
static FORCE_INLINE int32_t getNumOfRowsInResultPage(SQuery *pQuery, bool topBotQuery, bool isSTableQuery) {
  int32_t rowSize = pQuery->rowSize * GET_ROW_PARAM_FOR_MULTIOUTPUT(pQuery, topBotQuery, isSTableQuery);
1842
  return (DEFAULT_INTERN_BUF_PAGE_SIZE - sizeof(tFilePage)) / rowSize;
1843 1844 1845 1846
}

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

H
Haojun Liao 已提交
1848 1849 1850
  SQuery    *pQuery = pRuntimeEnv->pQuery;
  tFilePage *page = GET_RES_BUF_PAGE_BY_ID(pRuntimeEnv->pResultBuf, pResult->pos.pageId);
  int32_t realRowId = pResult->pos.rowId * GET_ROW_PARAM_FOR_MULTIOUTPUT(pQuery, pRuntimeEnv->topBotQuery, pRuntimeEnv->stableQuery);
1851

H
Haojun Liao 已提交
1852
  return ((char *)page->data) + pRuntimeEnv->offset[columnIndex] * pRuntimeEnv->numOfRowsPerPage +
1853
         pQuery->pSelectExpr[columnIndex].bytes * realRowId;
1854 1855 1856 1857 1858 1859
}

/**
 * decrease the refcount for each table involved in this query
 * @param pQInfo
 */
1860
UNUSED_FUNC void vnodeDecMeterRefcnt(SQInfo *pQInfo) {
1861
  if (pQInfo != NULL) {
1862
    //    assert(taosHashGetSize(pQInfo->tableqinfoGroupInfo) >= 1);
1863 1864 1865
  }

#if 0
1866
  if (pQInfo == NULL || pQInfo->tableqinfoGroupInfo.numOfTables == 1) {
1867
    atomic_fetch_sub_32(&pQInfo->pObj->numOfQueries, 1);
1868
    qDebug("QInfo:%p vid:%d sid:%d meterId:%s, query is over, numOfQueries:%d", pQInfo, pQInfo->pObj->vnode,
1869 1870 1871
           pQInfo->pObj->sid, pQInfo->pObj->meterId, pQInfo->pObj->numOfQueries);
  } else {
    int32_t num = 0;
1872 1873
    for (int32_t i = 0; i < pQInfo->tableqinfoGroupInfo.numOfTables; ++i) {
      SMeterObj *pMeter = getMeterObj(pQInfo->tableqinfoGroupInfo, pQInfo->pSidSet->pTableIdList[i]->sid);
1874
      atomic_fetch_sub_32(&(pMeter->numOfQueries), 1);
1875

1876
      if (pMeter->numOfQueries > 0) {
1877
        qDebug("QInfo:%p vid:%d sid:%d meterId:%s, query is over, numOfQueries:%d", pQInfo, pMeter->vnode, pMeter->sid,
1878 1879 1880 1881
               pMeter->meterId, pMeter->numOfQueries);
        num++;
      }
    }
1882

1883 1884 1885 1886
    /*
     * in order to reduce log output, for all meters of which numOfQueries count are 0,
     * we do not output corresponding information
     */
1887
    num = pQInfo->tableqinfoGroupInfo.numOfTables - num;
1888
    qDebug("QInfo:%p metric query is over, dec query ref for %d meters, numOfQueries on %d meters are 0", pQInfo,
1889
           pQInfo->tableqinfoGroupInfo.numOfTables, num);
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
  }
#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];
1903
    int32_t                  colIndex = pFilterInfo->info.colIndex;
1904

1905 1906 1907 1908
    // this column not valid in current data block
    if (colIndex < 0 || pDataStatis[colIndex].colId != pFilterInfo->info.data.colId) {
      continue;
    }
1909

1910 1911 1912 1913
    // not support pre-filter operation on binary/nchar data type
    if (!vnodeSupportPrefilter(pFilterInfo->info.data.type)) {
      continue;
    }
1914

1915 1916 1917 1918
    // all points in current column are NULL, no need to check its boundary value
    if (pDataStatis[colIndex].numOfNull == numOfTotalPoints) {
      continue;
    }
1919

1920 1921 1922
    if (pFilterInfo->info.info.type == TSDB_DATA_TYPE_FLOAT) {
      float minval = *(double *)(&pDataStatis[colIndex].min);
      float maxval = *(double *)(&pDataStatis[colIndex].max);
1923

1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
      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;
        }
      }
    }
  }
1938

1939
  // todo disable this opt code block temporarily
1940
  //  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1941
  //    int32_t functId = pQuery->pSelectExpr[i].base.functionId;
1942 1943 1944 1945
  //    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);
  //    }
  //  }
1946

1947 1948 1949 1950 1951 1952 1953
#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);
1954

1955 1956 1957 1958
  pTimeWindow->skey += (pQuery->slidingTime * factor);
  pTimeWindow->ekey = pTimeWindow->skey + (pQuery->intervalTime - 1);
}

H
hjxilinx 已提交
1959
SArray *loadDataBlockOnDemand(SQueryRuntimeEnv *pRuntimeEnv, void* pQueryHandle, SDataBlockInfo* pBlockInfo, SDataStatis **pStatis) {
1960
  SQuery *pQuery = pRuntimeEnv->pQuery;
1961 1962 1963 1964

  uint32_t r = 0;
  SArray * pDataBlock = NULL;

1965 1966 1967
  if (pQuery->numOfFilterCols > 0) {
    r = BLK_DATA_ALL_NEEDED;
  } else {
1968
    // check if this data block is required to load
1969
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
1970 1971 1972 1973
      SSqlFuncMsg* pSqlFunc = &pQuery->pSelectExpr[i].base;
      
      int32_t functionId = pSqlFunc->functionId;
      int32_t colId = pSqlFunc->colInfo.colId;
1974
      r |= aAggs[functionId].dataReqFunc(&pRuntimeEnv->pCtx[i], pQuery->window.skey, pQuery->window.ekey, colId);
1975
    }
1976

1977 1978 1979 1980
    if (pRuntimeEnv->pTSBuf > 0 || isIntervalQuery(pQuery)) {
      r |= BLK_DATA_ALL_NEEDED;
    }
  }
1981

1982
  if (r == BLK_DATA_NO_NEEDED) {
1983
    qDebug("QInfo:%p data block discard, brange:%" PRId64 "-%" PRId64 ", rows:%d", GET_QINFO_ADDR(pRuntimeEnv),
1984
           pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows);
1985 1986
    pRuntimeEnv->summary.discardBlocks += 1;
  } else if (r == BLK_DATA_STATIS_NEEDED) {
H
hjxilinx 已提交
1987
    if (tsdbRetrieveDataBlockStatisInfo(pQueryHandle, pStatis) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1988
      //        return DISK_DATA_LOAD_FAILED;
1989
    }
1990 1991 1992 1993
  
    pRuntimeEnv->summary.loadBlockStatis += 1;
  
    if (*pStatis == NULL) { // data block statistics does not exist, load data block
H
hjxilinx 已提交
1994
      pDataBlock = tsdbRetrieveDataBlock(pQueryHandle, NULL);
1995
      pRuntimeEnv->summary.totalCheckedRows += pBlockInfo->rows;
1996 1997 1998
    }
  } else {
    assert(r == BLK_DATA_ALL_NEEDED);
1999 2000 2001
  
    // load the data block statistics to perform further filter
    pRuntimeEnv->summary.loadBlockStatis +=1;
H
hjxilinx 已提交
2002
    if (tsdbRetrieveDataBlockStatisInfo(pQueryHandle, pStatis) != TSDB_CODE_SUCCESS) {
2003
    }
2004 2005
    
    if (!needToLoadDataBlock(pQuery,*pStatis, pRuntimeEnv->pCtx, pBlockInfo->rows)) {
2006
#if defined(_DEBUG_VIEW)
2007
      qDebug("QInfo:%p block discarded by per-filter", GET_QINFO_ADDR(pRuntimeEnv));
2008
#endif
2009 2010
      // current block has been discard due to filter applied
      pRuntimeEnv->summary.discardBlocks += 1;
2011 2012
      //        return DISK_DATA_DISCARDED;
    }
2013
  
2014
    pRuntimeEnv->summary.totalCheckedRows += pBlockInfo->rows;
H
Haojun Liao 已提交
2015
    pRuntimeEnv->summary.loadBlocks += 1;
H
hjxilinx 已提交
2016
    pDataBlock = tsdbRetrieveDataBlock(pQueryHandle, NULL);
2017
  }
2018

2019 2020 2021
  return pDataBlock;
}

H
hjxilinx 已提交
2022
int32_t binarySearchForKey(char *pValue, int num, TSKEY key, int order) {
2023
  int32_t midPos = -1;
H
Haojun Liao 已提交
2024
  int32_t numOfRows;
2025

2026 2027 2028
  if (num <= 0) {
    return -1;
  }
2029

2030
  assert(order == TSDB_ORDER_ASC || order == TSDB_ORDER_DESC);
2031 2032

  TSKEY * keyList = (TSKEY *)pValue;
2033
  int32_t firstPos = 0;
2034
  int32_t lastPos = num - 1;
2035

2036
  if (order == TSDB_ORDER_DESC) {
H
hjxilinx 已提交
2037 2038 2039 2040 2041
    // 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;
2042

H
Haojun Liao 已提交
2043 2044
      numOfRows = lastPos - firstPos + 1;
      midPos = (numOfRows >> 1) + firstPos;
2045

H
hjxilinx 已提交
2046 2047 2048 2049 2050 2051 2052 2053
      if (key < keyList[midPos]) {
        lastPos = midPos - 1;
      } else if (key > keyList[midPos]) {
        firstPos = midPos + 1;
      } else {
        break;
      }
    }
2054

H
hjxilinx 已提交
2055 2056 2057 2058 2059
  } 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;
2060

H
hjxilinx 已提交
2061 2062 2063 2064 2065 2066 2067
      if (key > keyList[lastPos]) {
        lastPos = lastPos + 1;
        if (lastPos >= num)
          return -1;
        else
          return lastPos;
      }
2068

H
Haojun Liao 已提交
2069 2070
      numOfRows = lastPos - firstPos + 1;
      midPos = (numOfRows >> 1) + firstPos;
2071

H
hjxilinx 已提交
2072 2073 2074 2075 2076 2077 2078 2079 2080
      if (key < keyList[midPos]) {
        lastPos = midPos - 1;
      } else if (key > keyList[midPos]) {
        firstPos = midPos + 1;
      } else {
        break;
      }
    }
  }
2081

H
hjxilinx 已提交
2082 2083 2084
  return midPos;
}

2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
static void ensureOutputBufferSimple(SQueryRuntimeEnv* pRuntimeEnv, int32_t capacity) {
  SQuery* pQuery = pRuntimeEnv->pQuery;

  if (capacity < pQuery->rec.capacity) {
    return;
  }

  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
    int32_t bytes = pQuery->pSelectExpr[i].bytes;
    assert(bytes > 0 && capacity > 0);

    char *tmp = realloc(pQuery->sdata[i], bytes * capacity + sizeof(tFilePage));
    if (tmp == NULL) {  // todo handle the oom
      assert(0);
    } else {
      pQuery->sdata[i] = (tFilePage *)tmp;
    }

    // set the pCtx output buffer position
    pRuntimeEnv->pCtx[i].aOutputBuf = pQuery->sdata[i]->data;
  }

2107
  qDebug("QInfo:%p realloc output buffer to inc output buffer from: %" PRId64 " rows to:%d rows", GET_QINFO_ADDR(pRuntimeEnv),
2108 2109 2110 2111 2112
         pQuery->rec.capacity, capacity);

  pQuery->rec.capacity = capacity;
}

2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124
static void ensureOutputBuffer(SQueryRuntimeEnv* pRuntimeEnv, SDataBlockInfo* pBlockInfo) {
  // in case of prj/diff query, ensure the output buffer is sufficient to accommodate the results of current block
  SQuery* pQuery = pRuntimeEnv->pQuery;
  if (!isIntervalQuery(pQuery) && !isGroupbyNormalCol(pQuery->pGroupbyExpr) && !isFixedOutputQuery(pQuery)) {
    SResultRec *pRec = &pQuery->rec;
    
    if (pQuery->rec.capacity - pQuery->rec.rows < pBlockInfo->rows) {
      int32_t remain = pRec->capacity - pRec->rows;
      int32_t newSize = pRec->capacity + (pBlockInfo->rows - remain);
      
      for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
        int32_t bytes = pQuery->pSelectExpr[i].bytes;
H
Haojun Liao 已提交
2125 2126
        assert(bytes > 0 && newSize > 0);

2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
        char *tmp = realloc(pQuery->sdata[i], bytes * newSize + sizeof(tFilePage));
        if (tmp == NULL) {  // todo handle the oom
          assert(0);
        } else {
          pQuery->sdata[i] = (tFilePage *)tmp;
        }
        
        // set the pCtx output buffer position
        pRuntimeEnv->pCtx[i].aOutputBuf = pQuery->sdata[i]->data + pRec->rows * bytes;
        
        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;
        }
      }
      
2143
      qDebug("QInfo:%p realloc output buffer, new size: %d rows, old:%" PRId64 ", remain:%" PRId64, GET_QINFO_ADDR(pRuntimeEnv),
2144 2145 2146 2147 2148 2149 2150
             newSize, pRec->capacity, newSize - pRec->rows);
      
      pRec->capacity = newSize;
    }
  }
}

2151 2152
static int64_t doScanAllDataBlocks(SQueryRuntimeEnv *pRuntimeEnv) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
2153
  STableQueryInfo* pTableQueryInfo = pQuery->current;
H
Haojun Liao 已提交
2154
  SQueryCostInfo*  summary  = &pRuntimeEnv->summary;
2155

2156
  qDebug("QInfo:%p query start, qrange:%" PRId64 "-%" PRId64 ", lastkey:%" PRId64 ", order:%d",
H
hjxilinx 已提交
2157 2158
         GET_QINFO_ADDR(pRuntimeEnv), pTableQueryInfo->win.skey, pTableQueryInfo->win.ekey, pTableQueryInfo->lastKey,
         pQuery->order.order);
2159

2160
  TsdbQueryHandleT pQueryHandle = IS_MASTER_SCAN(pRuntimeEnv)? pRuntimeEnv->pQueryHandle : pRuntimeEnv->pSecQueryHandle;
2161
  while (tsdbNextDataBlock(pQueryHandle)) {
H
Haojun Liao 已提交
2162
    summary->totalBlocks += 1;
2163
    if (isQueryKilled(GET_QINFO_ADDR(pRuntimeEnv))) {
2164
      return 0;
2165
    }
2166

2167
    SDataBlockInfo blockInfo = tsdbRetrieveDataBlockInfo(pQueryHandle);
2168

2169
    // todo extract methods
H
Haojun Liao 已提交
2170
    if (isIntervalQuery(pQuery) && pRuntimeEnv->windowResInfo.prevSKey == TSKEY_INITIAL_VAL) {
H
Haojun Liao 已提交
2171
      STimeWindow realWin = TSWINDOW_INITIALIZER, w = TSWINDOW_INITIALIZER;
2172 2173
      SWindowResInfo *pWindowResInfo = &pRuntimeEnv->windowResInfo;

2174
      if (QUERY_IS_ASC_QUERY(pQuery)) {
H
Haojun Liao 已提交
2175
        getAlignQueryTimeWindow(pQuery, blockInfo.window.skey, blockInfo.window.skey, pQuery->window.ekey, &realWin, &w);
2176 2177 2178 2179
        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
H
Haojun Liao 已提交
2180
        getAlignQueryTimeWindow(pQuery, blockInfo.window.ekey, pQuery->window.ekey, blockInfo.window.ekey, &realWin, &w);
2181

H
hjxilinx 已提交
2182
        pWindowResInfo->startTime = pQuery->window.skey;
2183 2184
        pWindowResInfo->prevSKey = w.skey;
      }
2185 2186 2187 2188
      
      if (pRuntimeEnv->pFillInfo != NULL) {
        pRuntimeEnv->pFillInfo->start = w.skey;
      }
2189
    }
2190

H
hjxilinx 已提交
2191
    // in case of prj/diff query, ensure the output buffer is sufficient to accommodate the results of current block
2192
    ensureOutputBuffer(pRuntimeEnv, &blockInfo);
2193

2194
    SDataStatis *pStatis = NULL;
H
Haojun Liao 已提交
2195
    SArray *pDataBlock = loadDataBlockOnDemand(pRuntimeEnv, pQueryHandle, &blockInfo, &pStatis);
2196

H
Haojun Liao 已提交
2197 2198
    // query start position can not move into tableApplyFunctionsOnBlock due to limit/offset condition
    pQuery->pos = QUERY_IS_ASC_QUERY(pQuery)? 0 : blockInfo.rows - 1;
H
hjxilinx 已提交
2199
    int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, &blockInfo, pStatis, binarySearchForKey, pDataBlock);
2200

H
Haojun Liao 已提交
2201
    summary->totalRows += blockInfo.rows;
2202
    qDebug("QInfo:%p check data block, brange:%" PRId64 "-%" PRId64 ", numOfRows:%d, numOfRes:%d, lastKey:%"PRId64, GET_QINFO_ADDR(pRuntimeEnv),
2203
           blockInfo.window.skey, blockInfo.window.ekey, blockInfo.rows, numOfRes, pQuery->current->lastKey);
2204

2205 2206
    // 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 已提交
2207
      break;
2208 2209
    }
  }
2210

H
hjxilinx 已提交
2211
  // if the result buffer is not full, set the query complete
2212 2213 2214
  if (!Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL)) {
    setQueryStatus(pQuery, QUERY_COMPLETED);
  }
2215

2216
  if (isIntervalQuery(pQuery) && IS_MASTER_SCAN(pRuntimeEnv)) {
H
hjxilinx 已提交
2217
    if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
2218 2219
      int32_t step = QUERY_IS_ASC_QUERY(pQuery) ? QUERY_ASC_FORWARD_STEP : QUERY_DESC_FORWARD_STEP;

2220
      closeAllTimeWindow(&pRuntimeEnv->windowResInfo);
H
hjxilinx 已提交
2221
      removeRedundantWindow(&pRuntimeEnv->windowResInfo, pTableQueryInfo->lastKey - step, step);
H
hjxilinx 已提交
2222
      pRuntimeEnv->windowResInfo.curIndex = pRuntimeEnv->windowResInfo.size - 1;  // point to the last time window
2223 2224 2225 2226
    } else {
      assert(Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL));
    }
  }
2227

2228
  return 0;
2229 2230 2231 2232 2233 2234
}

/*
 * set tag value in SQLFunctionCtx
 * e.g.,tag information into input buffer
 */
2235
static void doSetTagValueInParam(void *tsdb, void* pTable, int32_t tagColId, tVariant *tag, int16_t type, int16_t bytes) {
H
[td-90]  
Haojun Liao 已提交
2236
  tVariantDestroy(tag);
2237

2238
  if (tagColId == TSDB_TBNAME_COLUMN_INDEX) {
2239
    char* val = tsdbGetTableName(pTable);
H
[td-90]  
Haojun Liao 已提交
2240 2241 2242
    assert(val != NULL);
    
    tVariantCreateFromBinary(tag, varDataVal(val), varDataLen(val), TSDB_DATA_TYPE_BINARY);
2243
  } else {
2244
    char* val = tsdbGetTableTagVal(pTable, tagColId, type, bytes);
H
[td-90]  
Haojun Liao 已提交
2245 2246 2247 2248
    if (val == NULL) {
      tag->nType = TSDB_DATA_TYPE_NULL;
      return;
    }
H
hjxilinx 已提交
2249 2250
    
    if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
H
Hongze Cheng 已提交
2251
      if (isNull(val, type)) {
H
Haojun Liao 已提交
2252 2253 2254 2255
        tag->nType = TSDB_DATA_TYPE_NULL;
        return;
      }

H
[td-90]  
Haojun Liao 已提交
2256
      tVariantCreateFromBinary(tag, varDataVal(val), varDataLen(val), type);
H
hjxilinx 已提交
2257
    } else {
H
Haojun Liao 已提交
2258 2259 2260 2261 2262
      if (isNull(val, type)) {
        tag->nType = TSDB_DATA_TYPE_NULL;
        return;
      }

H
[td-90]  
Haojun Liao 已提交
2263
      tVariantCreateFromBinary(tag, val, bytes, type);
H
hjxilinx 已提交
2264
    }
2265
  }
2266 2267
}

2268
void setTagVal(SQueryRuntimeEnv *pRuntimeEnv, void *pTable, void *tsdb) {
2269
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
Haojun Liao 已提交
2270
  SQInfo* pQInfo = GET_QINFO_ADDR(pRuntimeEnv);
2271

H
[td-90]  
Haojun Liao 已提交
2272 2273 2274
  SExprInfo *pExprInfo = &pQuery->pSelectExpr[0];
  if (pQuery->numOfOutput == 1 && pExprInfo->base.functionId == TSDB_FUNC_TS_COMP) {
    assert(pExprInfo->base.numOfParams == 1);
H
Haojun Liao 已提交
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284

    // todo refactor extract function.
    int16_t type = -1, bytes = -1;
    for(int32_t i = 0; i < pQuery->numOfTags; ++i) {
      if (pQuery->tagColList[i].colId == pExprInfo->base.arg->argValue.i64) {
        type = pQuery->tagColList[i].type;
        bytes = pQuery->tagColList[i].bytes;
      }
    }

2285
    doSetTagValueInParam(tsdb, pTable, pExprInfo->base.arg->argValue.i64, &pRuntimeEnv->pCtx[0].tag, type, bytes);
2286 2287
  } else {
    // set tag value, by which the results are aggregated.
2288
    for (int32_t idx = 0; idx < pQuery->numOfOutput; ++idx) {
H
Haojun Liao 已提交
2289
      SExprInfo* pLocalExprInfo = &pQuery->pSelectExpr[idx];
H
[td-90]  
Haojun Liao 已提交
2290
  
2291
      // ts_comp column required the tag value for join filter
H
Haojun Liao 已提交
2292
      if (!TSDB_COL_IS_TAG(pLocalExprInfo->base.colInfo.flag)) {
2293 2294
        continue;
      }
2295

2296
      // todo use tag column index to optimize performance
2297
      doSetTagValueInParam(tsdb, pTable, pLocalExprInfo->base.colInfo.colId, &pRuntimeEnv->pCtx[idx].tag,
H
Haojun Liao 已提交
2298
                           pLocalExprInfo->type, pLocalExprInfo->bytes);
2299
    }
2300

2301
    // set the join tag for first column
H
[td-90]  
Haojun Liao 已提交
2302
    SSqlFuncMsg *pFuncMsg = &pExprInfo->base;
H
Haojun Liao 已提交
2303
    if ((pFuncMsg->functionId == TSDB_FUNC_TS || pFuncMsg->functionId == TSDB_FUNC_PRJ) && pFuncMsg->colInfo.colIndex == PRIMARYKEY_TIMESTAMP_COL_INDEX &&
2304 2305
        pRuntimeEnv->pTSBuf != NULL) {
      assert(pFuncMsg->numOfParams == 1);
H
Haojun Liao 已提交
2306 2307 2308 2309 2310 2311 2312 2313 2314 2315

      // todo refactor
      int16_t type = -1, bytes = -1;
      for(int32_t i = 0; i < pQuery->numOfTags; ++i) {
        if (pQuery->tagColList[i].colId == pExprInfo->base.arg->argValue.i64) {
          type = pQuery->tagColList[i].type;
          bytes = pQuery->tagColList[i].bytes;
        }
      }

2316
      doSetTagValueInParam(tsdb, pTable, pExprInfo->base.arg->argValue.i64, &pRuntimeEnv->pCtx[0].tag, type, bytes);
2317
      qDebug("QInfo:%p set tag value for join comparison, colId:%" PRId64 ", val:%"PRId64, pQInfo, pExprInfo->base.arg->argValue.i64,
B
Bomin Zhang 已提交
2318
          pRuntimeEnv->pCtx[0].tag.i64Key)
2319 2320 2321 2322 2323 2324 2325
    }
  }
}

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

2327
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
2328
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
2329 2330 2331
    if (!mergeFlag) {
      pCtx[i].aOutputBuf = pCtx[i].aOutputBuf + pCtx[i].outputBytes;
      pCtx[i].currentStage = FIRST_STAGE_MERGE;
2332

2333 2334 2335
      resetResultInfo(pCtx[i].resultInfo);
      aAggs[functionId].init(&pCtx[i]);
    }
2336

2337 2338 2339
    pCtx[i].hasNull = true;
    pCtx[i].nStartQueryTimestamp = timestamp;
    pCtx[i].aInputElemBuf = getPosInResultPage(pRuntimeEnv, i, pWindowRes);
2340

2341 2342 2343
    // 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);
2344 2345 2346 2347 2348 2349 2350 2351
  
      int32_t type = pCtx[i].outputType;
      if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
        tVariantCreateFromBinary(&pCtx[i].tag, varDataVal(pCtx[i].aInputElemBuf), varDataLen(pCtx[i].aInputElemBuf), type);
      } else {
        tVariantCreateFromBinary(&pCtx[i].tag, pCtx[i].aInputElemBuf, pCtx[i].inputBytes, pCtx[i].inputType);
      }
      
2352 2353
    }
  }
2354

2355
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
2356
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
2357 2358 2359
    if (functionId == TSDB_FUNC_TAG_DUMMY) {
      continue;
    }
2360

2361 2362 2363 2364
    aAggs[functionId].distMergeFunc(&pCtx[i]);
  }
}

2365
static UNUSED_FUNC void printBinaryData(int32_t functionId, char *data, int32_t srcDataType) {
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433
  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);
  }
}

2434
void UNUSED_FUNC displayInterResult(tFilePage **pdata, SQueryRuntimeEnv* pRuntimeEnv, int32_t numOfRows) {
2435
  SQuery* pQuery = pRuntimeEnv->pQuery;
2436
  int32_t numOfCols = pQuery->numOfOutput;
2437
  printf("super table query intermediate result, total:%d\n", numOfRows);
2438

2439 2440
  for (int32_t j = 0; j < numOfRows; ++j) {
    for (int32_t i = 0; i < numOfCols; ++i) {
2441
      
2442
      switch (pQuery->pSelectExpr[i].type) {
2443
        case TSDB_DATA_TYPE_BINARY: {
2444 2445 2446 2447 2448
//          int32_t colIndex = pQuery->pSelectExpr[i].base.colInfo.colIndex;
          int32_t type = pQuery->pSelectExpr[i].type;
//          } else {
//            type = pMeterObj->schema[colIndex].type;
//          }
2449
          printBinaryData(pQuery->pSelectExpr[i].base.functionId, pdata[i]->data + pQuery->pSelectExpr[i].bytes * j,
2450 2451 2452 2453 2454
                          type);
          break;
        }
        case TSDB_DATA_TYPE_TIMESTAMP:
        case TSDB_DATA_TYPE_BIGINT:
2455
          printf("%" PRId64 "\t", *(int64_t *)(pdata[i]->data + pQuery->pSelectExpr[i].bytes * j));
2456 2457
          break;
        case TSDB_DATA_TYPE_INT:
2458
          printf("%d\t", *(int32_t *)(pdata[i]->data + pQuery->pSelectExpr[i].bytes * j));
2459 2460
          break;
        case TSDB_DATA_TYPE_FLOAT:
2461
          printf("%f\t", *(float *)(pdata[i]->data + pQuery->pSelectExpr[i].bytes * j));
2462 2463
          break;
        case TSDB_DATA_TYPE_DOUBLE:
2464
          printf("%lf\t", *(double *)(pdata[i]->data + pQuery->pSelectExpr[i].bytes * j));
2465 2466 2467 2468 2469 2470 2471 2472
          break;
      }
    }
    printf("\n");
  }
}

typedef struct SCompSupporter {
H
hjxilinx 已提交
2473 2474 2475
  STableQueryInfo **pTableQueryInfo;
  int32_t *         position;
  SQInfo *          pQInfo;
2476 2477 2478 2479 2480
} SCompSupporter;

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

2482 2483
  SCompSupporter *  supporter = (SCompSupporter *)param;
  SQueryRuntimeEnv *pRuntimeEnv = &supporter->pQInfo->runtimeEnv;
2484

2485 2486
  int32_t leftPos = supporter->position[left];
  int32_t rightPos = supporter->position[right];
2487

2488 2489 2490 2491
  /* left source is exhausted */
  if (leftPos == -1) {
    return 1;
  }
2492

2493 2494 2495 2496
  /* right source is exhausted*/
  if (rightPos == -1) {
    return -1;
  }
2497

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

2501 2502
  char *b1 = getPosInResultPage(pRuntimeEnv, PRIMARYKEY_TIMESTAMP_COL_INDEX, pWindowRes1);
  TSKEY leftTimestamp = GET_INT64_VAL(b1);
2503

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

2507 2508
  char *b2 = getPosInResultPage(pRuntimeEnv, PRIMARYKEY_TIMESTAMP_COL_INDEX, pWindowRes2);
  TSKEY rightTimestamp = GET_INT64_VAL(b2);
2509

2510 2511 2512
  if (leftTimestamp == rightTimestamp) {
    return 0;
  }
2513

2514 2515 2516
  return leftTimestamp > rightTimestamp ? 1 : -1;
}

2517
int32_t mergeIntoGroupResult(SQInfo *pQInfo) {
2518
  int64_t st = taosGetTimestampMs();
2519
  int32_t ret = TSDB_CODE_SUCCESS;
2520

H
Haojun Liao 已提交
2521
  int32_t numOfGroups = GET_NUM_OF_TABLEGROUP(pQInfo);
2522

2523
  while (pQInfo->groupIndex < numOfGroups) {
H
Haojun Liao 已提交
2524
    SArray *group = GET_TABLEGROUP(pQInfo, pQInfo->groupIndex);
2525
    ret = mergeIntoGroupResultImpl(pQInfo, group);
2526 2527 2528 2529
    if (ret < 0) {  // not enough disk space to save the data into disk
      return -1;
    }

2530
    pQInfo->groupIndex += 1;
2531 2532

    // this group generates at least one result, return results
2533 2534 2535
    if (ret > 0) {
      break;
    }
2536 2537

    assert(pQInfo->numOfGroupResultPages == 0);
2538
    qDebug("QInfo:%p no result in group %d, continue", pQInfo, pQInfo->groupIndex - 1);
2539
  }
2540

2541
  qDebug("QInfo:%p merge res data into group, index:%d, total group:%d, elapsed time:%" PRId64 "ms", pQInfo,
2542
         pQInfo->groupIndex - 1, numOfGroups, taosGetTimestampMs() - st);
2543

2544 2545 2546 2547 2548 2549
  return TSDB_CODE_SUCCESS;
}

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

2551
    // current results of group has been sent to client, try next group
2552
    if (mergeIntoGroupResult(pQInfo) != TSDB_CODE_SUCCESS) {
2553 2554
      return;  // failed to save data in the disk
    }
2555

2556
    // check if all results has been sent to client
H
Haojun Liao 已提交
2557
    int32_t numOfGroup = GET_NUM_OF_TABLEGROUP(pQInfo);
2558
    if (pQInfo->numOfGroupResultPages == 0 && pQInfo->groupIndex == numOfGroup) {
2559
      pQInfo->tableIndex = pQInfo->tableqinfoGroupInfo.numOfTables;  // set query completed
2560 2561
      return;
    }
2562
  }
2563 2564

  SQueryRuntimeEnv *   pRuntimeEnv = &pQInfo->runtimeEnv;
2565
  SDiskbasedResultBuf *pResultBuf = pRuntimeEnv->pResultBuf;
2566

2567
  int32_t id = getGroupResultId(pQInfo->groupIndex - 1);
2568
  SIDList list = getDataBufPagesIdList(pResultBuf, pQInfo->offset + id);
2569

2570 2571
  int32_t total = 0;
  for (int32_t i = 0; i < list.size; ++i) {
H
Haojun Liao 已提交
2572
    tFilePage *pData = GET_RES_BUF_PAGE_BY_ID(pResultBuf, list.pData[i]);
2573
    total += pData->num;
2574
  }
2575

2576
  int32_t rows = total;
2577

2578 2579
  int32_t offset = 0;
  for (int32_t num = 0; num < list.size; ++num) {
H
Haojun Liao 已提交
2580
    tFilePage *pData = GET_RES_BUF_PAGE_BY_ID(pResultBuf, list.pData[num]);
2581

2582
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
2583
      int32_t bytes = pRuntimeEnv->pCtx[i].outputBytes;
2584
      char *  pDest = pQuery->sdata[i]->data;
2585

2586 2587
      memcpy(pDest + offset * bytes, pData->data + pRuntimeEnv->offset[i] * pData->num,
             bytes * pData->num);
2588
    }
2589

2590
    offset += pData->num;
2591
  }
2592

2593
  assert(pQuery->rec.rows == 0);
2594

2595
  pQuery->rec.rows += rows;
2596 2597 2598
  pQInfo->offset += 1;
}

H
Haojun Liao 已提交
2599
int64_t getNumOfResultWindowRes(SQuery *pQuery, SWindowResult *pWindowRes) {
2600
  for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
2601
    int32_t functionId = pQuery->pSelectExpr[j].base.functionId;
2602

2603 2604 2605 2606 2607 2608 2609
    /*
     * 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;
    }
2610

2611
    SResultInfo *pResultInfo = &pWindowRes->resultInfo[j];
H
Haojun Liao 已提交
2612
    assert(pResultInfo != NULL);
2613

H
Haojun Liao 已提交
2614 2615
    if (pResultInfo->numOfRes > 0) {
      return pResultInfo->numOfRes;
2616 2617
    }
  }
2618

H
Haojun Liao 已提交
2619
  return 0;
2620 2621
}

2622
int32_t mergeIntoGroupResultImpl(SQInfo *pQInfo, SArray *pGroup) {
2623
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
2624
  SQuery *          pQuery = pRuntimeEnv->pQuery;
2625

2626
  size_t size = taosArrayGetSize(pGroup);
2627
  tFilePage **buffer = pQuery->sdata;
2628

2629
  int32_t*   posList = calloc(size, sizeof(int32_t));
H
hjxilinx 已提交
2630
  STableQueryInfo **pTableList = malloc(POINTER_BYTES * size);
2631

2632 2633 2634 2635 2636 2637 2638 2639
  if (pTableList == NULL || posList == NULL) {
    tfree(posList);
    tfree(pTableList);

    qError("QInfo:%p failed alloc memory", pQInfo);
    longjmp(pQInfo->env, TSDB_CODE_QRY_OUT_OF_MEMORY);
  }

2640
  // todo opt for the case of one table per group
2641
  int32_t numOfTables = 0;
2642
  for (int32_t i = 0; i < size; ++i) {
2643
    STableQueryInfo *item = taosArrayGetP(pGroup, i);
2644

2645 2646 2647
    SIDList list = getDataBufPagesIdList(pRuntimeEnv->pResultBuf, tsdbGetTableId(item->pTable).tid);
    if (list.size > 0 && item->windowResInfo.size > 0) {
      pTableList[numOfTables] = item;
2648
      numOfTables += 1;
2649 2650
    }
  }
2651

2652
  if (numOfTables == 0) {
2653 2654
    tfree(posList);
    tfree(pTableList);
2655

2656 2657
    assert(pQInfo->numOfGroupResultPages == 0);
    return 0;
H
Haojun Liao 已提交
2658
  } else if (numOfTables == 1) { // no need to merge results since only one table in each group
2659

2660
  }
2661

2662
  SCompSupporter cs = {pTableList, posList, pQInfo};
2663

2664
  SLoserTreeInfo *pTree = NULL;
2665
  tLoserTreeCreate(&pTree, numOfTables, &cs, tableResultComparFn);
2666

2667
  SResultInfo *pResultInfo = calloc(pQuery->numOfOutput, sizeof(SResultInfo));
2668 2669
  setWindowResultInfo(pResultInfo, pQuery, pRuntimeEnv->stableQuery);
  resetMergeResultBuf(pQuery, pRuntimeEnv->pCtx, pResultInfo);
2670

2671 2672
  int64_t lastTimestamp = -1;
  int64_t startt = taosGetTimestampMs();
2673

2674 2675
  while (1) {
    int32_t pos = pTree->pNode[0].index;
2676

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

2680 2681
    char *b = getPosInResultPage(pRuntimeEnv, PRIMARYKEY_TIMESTAMP_COL_INDEX, pWindowRes);
    TSKEY ts = GET_INT64_VAL(b);
2682

2683
    assert(ts == pWindowRes->window.skey);
H
Haojun Liao 已提交
2684
    int64_t num = getNumOfResultWindowRes(pQuery, pWindowRes);
2685 2686
    if (num <= 0) {
      cs.position[pos] += 1;
2687

2688 2689
      if (cs.position[pos] >= pWindowResInfo->size) {
        cs.position[pos] = -1;
2690

2691
        // all input sources are exhausted
2692
        if (--numOfTables == 0) {
2693 2694 2695 2696 2697 2698 2699
          break;
        }
      }
    } else {
      if (ts == lastTimestamp) {  // merge with the last one
        doMerge(pRuntimeEnv, ts, pWindowRes, true);
      } else {  // copy data to disk buffer
2700
        if (buffer[0]->num == pQuery->rec.capacity) {
2701 2702 2703
          if (flushFromResultBuf(pQInfo) != TSDB_CODE_SUCCESS) {
            return -1;
          }
2704

2705 2706
          resetMergeResultBuf(pQuery, pRuntimeEnv->pCtx, pResultInfo);
        }
2707

2708
        doMerge(pRuntimeEnv, ts, pWindowRes, false);
2709
        buffer[0]->num += 1;
2710
      }
2711

2712
      lastTimestamp = ts;
2713

2714 2715 2716
      cs.position[pos] += 1;
      if (cs.position[pos] >= pWindowResInfo->size) {
        cs.position[pos] = -1;
2717

2718
        // all input sources are exhausted
2719
        if (--numOfTables == 0) {
2720 2721 2722 2723
          break;
        }
      }
    }
2724

2725 2726
    tLoserTreeAdjust(pTree, pos + pTree->numOfEntries);
  }
2727

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

2732 2733 2734 2735
      tfree(pTree);
      tfree(pTableList);
      tfree(posList);
      tfree(pResultInfo);
2736

2737 2738 2739
      return -1;
    }
  }
2740

2741 2742 2743
  int64_t endt = taosGetTimestampMs();

#ifdef _DEBUG_VIEW
2744
  displayInterResult(pQuery->sdata, pRuntimeEnv, pQuery->sdata[0]->num);
2745
#endif
2746

2747
  qDebug("QInfo:%p result merge completed for group:%d, elapsed time:%" PRId64 " ms", pQInfo, pQInfo->groupIndex, endt - startt);
2748

2749 2750
  tfree(pTableList);
  tfree(posList);
H
Haojun Liao 已提交
2751
  tfree(pTree);
2752

2753
  pQInfo->offset = 0;
2754
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
2755 2756
    tfree(pResultInfo[i].interResultBuf);
  }
2757

2758 2759 2760 2761 2762
  tfree(pResultInfo);
  return pQInfo->numOfGroupResultPages;
}

int32_t flushFromResultBuf(SQInfo *pQInfo) {
2763 2764 2765
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;

2766
  SDiskbasedResultBuf *pResultBuf = pRuntimeEnv->pResultBuf;
2767
  int32_t              capacity = (DEFAULT_INTERN_BUF_PAGE_SIZE - sizeof(tFilePage)) / pQuery->rowSize;
2768

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

2772
  int32_t remain = pQuery->sdata[0]->num;
2773
  int32_t offset = 0;
2774

2775 2776 2777 2778 2779
  while (remain > 0) {
    int32_t r = remain;
    if (r > capacity) {
      r = capacity;
    }
2780

2781
    int32_t    id = getGroupResultId(pQInfo->groupIndex) + pQInfo->numOfGroupResultPages;
2782
    tFilePage *buf = getNewDataBuf(pResultBuf, id, &pageId);
2783

2784
    // pagewise copy to dest buffer
2785
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
2786
      int32_t bytes = pRuntimeEnv->pCtx[i].outputBytes;
2787
      buf->num = r;
2788

2789 2790
      memcpy(buf->data + pRuntimeEnv->offset[i] * buf->num, ((char *)pQuery->sdata[i]->data) + offset * bytes,
             buf->num * bytes);
2791
    }
2792

2793 2794 2795
    offset += r;
    remain -= r;
  }
2796

2797 2798 2799 2800 2801
  pQInfo->numOfGroupResultPages += 1;
  return TSDB_CODE_SUCCESS;
}

void resetMergeResultBuf(SQuery *pQuery, SQLFunctionCtx *pCtx, SResultInfo *pResultInfo) {
2802
  for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
2803
    pCtx[k].aOutputBuf = pQuery->sdata[k]->data - pCtx[k].outputBytes;
2804 2805 2806
    pCtx[k].size = 1;
    pCtx[k].startOffset = 0;
    pCtx[k].resultInfo = &pResultInfo[k];
2807

2808
    pQuery->sdata[k]->num = 0;
2809 2810 2811
  }
}

2812 2813 2814 2815 2816 2817 2818
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 已提交
2819 2820 2821 2822 2823 2824 2825
  
  // 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);
//  }
2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838
  
  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;
  
2839 2840 2841 2842 2843
  for (int32_t i = 0; i < pWindowResInfo->size; ++i) {
    SWindowStatus *pStatus = getTimeWindowResStatus(pWindowResInfo, i);
    if (!pStatus->closed) {
      continue;
    }
2844

2845
    SWindowResult *buf = getWindowResult(pWindowResInfo, i);
2846

2847
    // open/close the specified query for each group result
2848
    for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
2849
      int32_t functId = pQuery->pSelectExpr[j].base.functionId;
2850

2851 2852
      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)) {
2853 2854 2855 2856 2857 2858 2859 2860
        buf->resultInfo[j].complete = false;
      } else if (functId != TSDB_FUNC_TS && functId != TSDB_FUNC_TAG) {
        buf->resultInfo[j].complete = true;
      }
    }
  }
}

2861 2862
void disableFuncInReverseScan(SQInfo *pQInfo) {
  SQueryRuntimeEnv* pRuntimeEnv = &pQInfo->runtimeEnv;
2863
  SQuery *pQuery = pRuntimeEnv->pQuery;
2864
  int32_t order = pQuery->order.order;
2865

2866 2867 2868
  // group by normal columns and interval query on normal table
  SWindowResInfo *pWindowResInfo = &pRuntimeEnv->windowResInfo;
  if (isGroupbyNormalCol(pQuery->pGroupbyExpr) || isIntervalQuery(pQuery)) {
2869
    disableFuncInReverseScanImpl(pQInfo, pWindowResInfo, order);
2870
  } else {  // for simple result of table query,
2871
    for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {  // todo refactor
2872
      int32_t functId = pQuery->pSelectExpr[j].base.functionId;
2873

2874
      SQLFunctionCtx *pCtx = &pRuntimeEnv->pCtx[j];
2875 2876 2877
      if (pCtx->resultInfo == NULL) {
        continue; // resultInfo is NULL, means no data checked in previous scan
      }
2878

2879 2880
      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)) {
2881 2882 2883 2884 2885 2886
        pCtx->resultInfo->complete = false;
      } else if (functId != TSDB_FUNC_TS && functId != TSDB_FUNC_TAG) {
        pCtx->resultInfo->complete = true;
      }
    }
  }
H
hjxilinx 已提交
2887
  
H
Haojun Liao 已提交
2888
  int32_t numOfGroups = GET_NUM_OF_TABLEGROUP(pQInfo);
H
hjxilinx 已提交
2889 2890
  
  for(int32_t i = 0; i < numOfGroups; ++i) {
H
Haojun Liao 已提交
2891
    SArray *group = GET_TABLEGROUP(pQInfo, i);
H
hjxilinx 已提交
2892 2893 2894
    
    size_t t = taosArrayGetSize(group);
    for (int32_t j = 0; j < t; ++j) {
2895 2896
      STableQueryInfo *pCheckInfo = taosArrayGetP(group, j);
      updateTableQueryInfoForReverseScan(pQuery, pCheckInfo);
H
hjxilinx 已提交
2897 2898
    }
  }
2899 2900
}

2901
void switchCtxOrder(SQueryRuntimeEnv *pRuntimeEnv) {
2902
  SQuery *pQuery = pRuntimeEnv->pQuery;
2903
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
H
Haojun Liao 已提交
2904
    SWITCH_ORDER(pRuntimeEnv->pCtx[i].order);
2905 2906 2907 2908
  }
}

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

2911 2912
  pResultRow->resultInfo = calloc((size_t)numOfCols, sizeof(SResultInfo));
  pResultRow->pos = *posInfo;
2913

2914 2915 2916 2917 2918 2919
  // set the intermediate result output buffer
  setWindowResultInfo(pResultRow->resultInfo, pQuery, isSTableQuery);
}

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

2921
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
2922 2923
    SQLFunctionCtx *pCtx = &pRuntimeEnv->pCtx[i];
    pCtx->aOutputBuf = pQuery->sdata[i]->data;
2924

2925 2926 2927 2928 2929 2930
    /*
     * 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];
2931

2932
    // set the timestamp output buffer for top/bottom/diff query
2933
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
2934 2935 2936
    if (functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM || functionId == TSDB_FUNC_DIFF) {
      pCtx->ptsOutputBuf = pRuntimeEnv->pCtx[0].aOutputBuf;
    }
2937

2938
    memset(pQuery->sdata[i]->data, 0, (size_t)pQuery->pSelectExpr[i].bytes * pQuery->rec.capacity);
2939
  }
2940

2941 2942 2943 2944 2945
  initCtxOutputBuf(pRuntimeEnv);
}

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

2947
  // reset the execution contexts
2948
  for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
2949
    int32_t functionId = pQuery->pSelectExpr[j].base.functionId;
2950
    assert(functionId != TSDB_FUNC_DIFF);
2951

2952 2953 2954 2955
    // set next output position
    if (IS_OUTER_FORWARD(aAggs[functionId].nStatus)) {
      pRuntimeEnv->pCtx[j].aOutputBuf += pRuntimeEnv->pCtx[j].outputBytes * output;
    }
2956

2957 2958 2959 2960 2961 2962 2963 2964 2965 2966
    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;
    }
2967

2968 2969 2970 2971 2972 2973
    resetResultInfo(pRuntimeEnv->pCtx[j].resultInfo);
  }
}

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

2975
  for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
2976
    int32_t functionId = pQuery->pSelectExpr[j].base.functionId;
2977
    pRuntimeEnv->pCtx[j].currentStage = 0;
2978

H
Haojun Liao 已提交
2979 2980 2981 2982
    SResultInfo* pResInfo = GET_RES_INFO(&pRuntimeEnv->pCtx[j]);
    if (pResInfo->initialized) {
      continue;
    }
2983

2984 2985 2986 2987
    aAggs[functionId].init(&pRuntimeEnv->pCtx[j]);
  }
}

2988
void skipResults(SQueryRuntimeEnv *pRuntimeEnv) {
2989
  SQuery *pQuery = pRuntimeEnv->pQuery;
2990
  if (pQuery->rec.rows == 0 || pQuery->limit.offset == 0) {
2991 2992
    return;
  }
2993

2994
  if (pQuery->rec.rows <= pQuery->limit.offset) {
2995
    qDebug("QInfo:%p skip rows:%" PRId64 ", new offset:%" PRIu64, GET_QINFO_ADDR(pRuntimeEnv), pQuery->rec.rows,
2996 2997
        pQuery->limit.offset - pQuery->rec.rows);
    
2998 2999
    pQuery->limit.offset -= pQuery->rec.rows;
    pQuery->rec.rows = 0;
3000

3001
    resetCtxOutputBuf(pRuntimeEnv);
3002

H
Haojun Liao 已提交
3003
    // clear the buffer full flag if exists
3004
    CLEAR_QUERY_STATUS(pQuery, QUERY_RESBUF_FULL);
3005
  } else {
3006
    int64_t numOfSkip = pQuery->limit.offset;
3007
    pQuery->rec.rows -= numOfSkip;
3008 3009
    pQuery->limit.offset = 0;
  
3010
    qDebug("QInfo:%p skip row:%"PRId64", new offset:%d, numOfRows remain:%" PRIu64, GET_QINFO_ADDR(pRuntimeEnv), numOfSkip,
3011 3012
           0, pQuery->rec.rows);
    
3013
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
3014
      int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
3015
      int32_t bytes = pRuntimeEnv->pCtx[i].outputBytes;
3016
      
H
Haojun Liao 已提交
3017 3018
      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;
3019

3020
      if (functionId == TSDB_FUNC_DIFF || functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM) {
3021
        pRuntimeEnv->pCtx[i].ptsOutputBuf = pRuntimeEnv->pCtx[0].aOutputBuf;
3022 3023
      }
    }
3024

3025
    updateNumOfResult(pRuntimeEnv, pQuery->rec.rows);
3026 3027 3028 3029 3030 3031 3032 3033
  }
}

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
3034
    CLEAR_QUERY_STATUS(pQuery, QUERY_NOT_COMPLETED);
3035 3036 3037 3038 3039 3040
    pQuery->status |= status;
  }
}

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

H
hjxilinx 已提交
3042
  bool toContinue = false;
3043 3044 3045
  if (isGroupbyNormalCol(pQuery->pGroupbyExpr) || isIntervalQuery(pQuery)) {
    // for each group result, call the finalize function for each column
    SWindowResInfo *pWindowResInfo = &pRuntimeEnv->windowResInfo;
3046

3047 3048 3049 3050 3051
    for (int32_t i = 0; i < pWindowResInfo->size; ++i) {
      SWindowResult *pResult = getWindowResult(pWindowResInfo, i);
      if (!pResult->status.closed) {
        continue;
      }
3052

3053
      setWindowResOutputBuf(pRuntimeEnv, pResult);
3054

3055
      for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
3056
        int16_t functId = pQuery->pSelectExpr[j].base.functionId;
3057 3058 3059
        if (functId == TSDB_FUNC_TS) {
          continue;
        }
3060

3061 3062
        aAggs[functId].xNextStep(&pRuntimeEnv->pCtx[j]);
        SResultInfo *pResInfo = GET_RES_INFO(&pRuntimeEnv->pCtx[j]);
3063

3064 3065 3066 3067
        toContinue |= (!pResInfo->complete);
      }
    }
  } else {
3068
    for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
3069
      int16_t functId = pQuery->pSelectExpr[j].base.functionId;
3070 3071 3072
      if (functId == TSDB_FUNC_TS) {
        continue;
      }
3073

3074 3075
      aAggs[functId].xNextStep(&pRuntimeEnv->pCtx[j]);
      SResultInfo *pResInfo = GET_RES_INFO(&pRuntimeEnv->pCtx[j]);
3076

3077 3078 3079
      toContinue |= (!pResInfo->complete);
    }
  }
3080

3081 3082 3083
  return toContinue;
}

H
Haojun Liao 已提交
3084
static SQueryStatusInfo getQueryStatusInfo(SQueryRuntimeEnv *pRuntimeEnv, TSKEY start) {
3085
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
3086 3087
  STableQueryInfo* pTableQueryInfo = pQuery->current;
  
H
Haojun Liao 已提交
3088 3089 3090
  assert((start <= pTableQueryInfo->lastKey && QUERY_IS_ASC_QUERY(pQuery)) ||
      (start >= pTableQueryInfo->lastKey && !QUERY_IS_ASC_QUERY(pQuery)));
  
3091
  SQueryStatusInfo info = {
H
hjxilinx 已提交
3092
      .status      = pQuery->status,
3093
      .windowIndex = pRuntimeEnv->windowResInfo.curIndex,
H
Haojun Liao 已提交
3094
      .lastKey     = start,
H
hjxilinx 已提交
3095
      .w           = pQuery->window,
H
Haojun Liao 已提交
3096
      .curWindow   = {.skey = start, .ekey = pTableQueryInfo->win.ekey},
3097
  };
3098

3099 3100 3101
  return info;
}

3102 3103 3104 3105
static void setEnvBeforeReverseScan(SQueryRuntimeEnv *pRuntimeEnv, SQueryStatusInfo *pStatus) {
  SQInfo *pQInfo = GET_QINFO_ADDR(pRuntimeEnv);
  SQuery *pQuery = pRuntimeEnv->pQuery;

3106 3107 3108 3109 3110
  pStatus->cur = tsBufGetCursor(pRuntimeEnv->pTSBuf);  // save the cursor
  if (pRuntimeEnv->pTSBuf) {
    SWITCH_ORDER(pRuntimeEnv->pTSBuf->cur.order);
    tsBufNextPos(pRuntimeEnv->pTSBuf);
  }
3111

3112
  // reverse order time range
3113 3114 3115
  pQuery->window = pStatus->curWindow;
  SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);

3116
  SWITCH_ORDER(pQuery->order.order);
3117
  SET_REVERSE_SCAN_FLAG(pRuntimeEnv);
3118

3119
  STsdbQueryCond cond = {
3120
      .twindow = pQuery->window,
H
hjxilinx 已提交
3121
      .order   = pQuery->order.order,
3122
      .colList = pQuery->colList,
3123 3124
      .numOfCols = pQuery->numOfCols,
  };
3125

3126 3127 3128 3129
  // clean unused handle
  if (pRuntimeEnv->pSecQueryHandle != NULL) {
    tsdbCleanupQueryHandle(pRuntimeEnv->pSecQueryHandle);
  }
3130

3131 3132
  // add ref for table
  pRuntimeEnv->pSecQueryHandle = tsdbQueryTables(pQInfo->tsdb, &cond, &pQInfo->tableGroupInfo, pQInfo);
3133

3134 3135
  setQueryStatus(pQuery, QUERY_NOT_COMPLETED);
  switchCtxOrder(pRuntimeEnv);
3136
  disableFuncInReverseScan(pQInfo);
3137 3138
}

3139 3140
static void clearEnvAfterReverseScan(SQueryRuntimeEnv *pRuntimeEnv, SQueryStatusInfo *pStatus) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
3141
  STableQueryInfo* pTableQueryInfo = pQuery->current;
3142

3143 3144
  SWITCH_ORDER(pQuery->order.order);
  switchCtxOrder(pRuntimeEnv);
3145

3146 3147 3148 3149
  tsBufSetCursor(pRuntimeEnv->pTSBuf, &pStatus->cur);
  if (pRuntimeEnv->pTSBuf) {
    pRuntimeEnv->pTSBuf->cur.order = pQuery->order.order;
  }
3150

3151
  SET_MASTER_SCAN_FLAG(pRuntimeEnv);
3152

3153 3154
  // update the pQuery->window.skey and pQuery->window.ekey to limit the scan scope of sliding query
  // during reverse scan
H
hjxilinx 已提交
3155
  pTableQueryInfo->lastKey = pStatus->lastKey;
3156
  pQuery->status = pStatus->status;
3157
  
H
hjxilinx 已提交
3158
  pTableQueryInfo->win = pStatus->w;
3159
  pQuery->window = pTableQueryInfo->win;
3160 3161
}

3162
void scanOneTableDataBlocks(SQueryRuntimeEnv *pRuntimeEnv, TSKEY start) {
H
hjxilinx 已提交
3163
  SQInfo *pQInfo = (SQInfo *) GET_QINFO_ADDR(pRuntimeEnv);
3164
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
3165 3166
  STableQueryInfo *pTableQueryInfo = pQuery->current;
  
3167
  setQueryStatus(pQuery, QUERY_NOT_COMPLETED);
3168

3169
  // store the start query position
H
Haojun Liao 已提交
3170
  SQueryStatusInfo qstatus = getQueryStatusInfo(pRuntimeEnv, start);
3171

3172 3173
  SET_MASTER_SCAN_FLAG(pRuntimeEnv);
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);
3174

3175 3176
  while (1) {
    doScanAllDataBlocks(pRuntimeEnv);
3177

3178 3179
    if (pRuntimeEnv->scanFlag == MASTER_SCAN) {
      qstatus.status = pQuery->status;
H
hjxilinx 已提交
3180
      qstatus.curWindow.ekey = pTableQueryInfo->lastKey - step;
3181
      qstatus.lastKey = pTableQueryInfo->lastKey;
3182
    }
3183

3184
    if (!needScanDataBlocksAgain(pRuntimeEnv)) {
3185
      // restore the status code and jump out of loop
3186
      if (pRuntimeEnv->scanFlag == REPEAT_SCAN) {
3187
        pQuery->status = qstatus.status;
3188
      }
3189

3190 3191
      break;
    }
3192

3193
    STsdbQueryCond cond = {
3194
        .twindow = qstatus.curWindow,
H
hjxilinx 已提交
3195
        .order   = pQuery->order.order,
3196
        .colList = pQuery->colList,
3197
        .numOfCols = pQuery->numOfCols,
3198
    };
3199

3200 3201
    if (pRuntimeEnv->pSecQueryHandle != NULL) {
      tsdbCleanupQueryHandle(pRuntimeEnv->pSecQueryHandle);
3202
    }
3203

3204
    pRuntimeEnv->pSecQueryHandle = tsdbQueryTables(pQInfo->tsdb, &cond, &pQInfo->tableGroupInfo, pQInfo);
3205
    pRuntimeEnv->windowResInfo.curIndex = qstatus.windowIndex;
3206

3207 3208
    setQueryStatus(pQuery, QUERY_NOT_COMPLETED);
    pRuntimeEnv->scanFlag = REPEAT_SCAN;
3209
    
3210
    qDebug("QInfo:%p start to repeat scan data blocks due to query func required, qrange:%"PRId64"-%"PRId64, pQInfo,
3211
        cond.twindow.skey, cond.twindow.ekey);
3212

3213
    // check if query is killed or not
3214
    if (isQueryKilled(pQInfo)) {
3215 3216 3217
      return;
    }
  }
3218

H
hjxilinx 已提交
3219
  if (!needReverseScan(pQuery)) {
3220 3221
    return;
  }
3222

3223
  setEnvBeforeReverseScan(pRuntimeEnv, &qstatus);
3224

3225
  // reverse scan from current position
3226
  qDebug("QInfo:%p start to reverse scan", pQInfo);
3227
  doScanAllDataBlocks(pRuntimeEnv);
3228 3229

  clearEnvAfterReverseScan(pRuntimeEnv, &qstatus);
3230 3231
}

H
hjxilinx 已提交
3232
void finalizeQueryResult(SQueryRuntimeEnv *pRuntimeEnv) {
3233
  SQuery *pQuery = pRuntimeEnv->pQuery;
3234

3235 3236 3237 3238 3239 3240
  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);
    }
3241

3242 3243 3244 3245 3246
    for (int32_t i = 0; i < pWindowResInfo->size; ++i) {
      SWindowResult *buf = &pWindowResInfo->pResult[i];
      if (!isWindowResClosed(pWindowResInfo, i)) {
        continue;
      }
3247

3248
      setWindowResOutputBuf(pRuntimeEnv, buf);
3249

3250
      for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
3251
        aAggs[pQuery->pSelectExpr[j].base.functionId].xFinalize(&pRuntimeEnv->pCtx[j]);
3252
      }
3253

3254 3255 3256 3257 3258 3259
      /*
       * 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);
    }
3260

3261
  } else {
3262
    for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
3263
      aAggs[pQuery->pSelectExpr[j].base.functionId].xFinalize(&pRuntimeEnv->pCtx[j]);
3264 3265 3266 3267 3268
    }
  }
}

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

3272 3273 3274 3275
    if (functionId != TSDB_FUNC_TS && functionId != TSDB_FUNC_TAG && functionId != TSDB_FUNC_TAGPRJ) {
      return true;
    }
  }
3276

3277 3278 3279
  return false;
}

3280
static STableQueryInfo *createTableQueryInfo( SQueryRuntimeEnv *pRuntimeEnv, void* pTable, STimeWindow win) {
H
Haojun Liao 已提交
3281 3282
  SQuery* pQuery = pRuntimeEnv->pQuery;

3283
  STableQueryInfo *pTableQueryInfo = calloc(1, sizeof(STableQueryInfo));
3284

H
hjxilinx 已提交
3285 3286
  pTableQueryInfo->win = win;
  pTableQueryInfo->lastKey = win.skey;
3287

3288
  pTableQueryInfo->pTable = pTable;
3289
  pTableQueryInfo->cur.vgroupIndex = -1;
3290

H
Haojun Liao 已提交
3291 3292 3293 3294 3295 3296 3297 3298 3299
  int32_t initialSize      = 1;
  int32_t initialThreshold = 1;

  if (isIntervalQuery(pQuery) || isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
    initialSize = 20;
    initialThreshold = 100;
  }

  initWindowResInfo(&pTableQueryInfo->windowResInfo, pRuntimeEnv, initialSize, initialThreshold, TSDB_DATA_TYPE_INT);
3300 3301 3302
  return pTableQueryInfo;
}

3303
void destroyTableQueryInfo(STableQueryInfo *pTableQueryInfo, int32_t numOfCols) {
3304 3305 3306
  if (pTableQueryInfo == NULL) {
    return;
  }
3307

3308 3309 3310 3311
  cleanupTimeWindowInfo(&pTableQueryInfo->windowResInfo, numOfCols);
  free(pTableQueryInfo);
}

H
Haojun Liao 已提交
3312 3313 3314 3315 3316 3317 3318
#define SET_CURRENT_QUERY_TABLE_INFO(_runtime, _tableInfo)                                      \
  do {                                                                                          \
    SQuery *_query = (_runtime)->pQuery;                                                        \
    _query->current = _tableInfo;                                                               \
    assert((((_tableInfo)->lastKey >= (_tableInfo)->win.skey) && QUERY_IS_ASC_QUERY(_query)) || \
           (((_tableInfo)->lastKey <= (_tableInfo)->win.skey) && !QUERY_IS_ASC_QUERY(_query))); \
  } while (0)
3319 3320 3321

/**
 * set output buffer for different group
H
Haojun Liao 已提交
3322
 * TODO opt performance if current group is identical to previous group
3323
 * @param pRuntimeEnv
3324
 * @param pDataBlockInfo
3325
 */
H
Haojun Liao 已提交
3326
void setExecutionContext(SQInfo *pQInfo, int32_t groupIndex, TSKEY nextKey) {
3327
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
H
Haojun Liao 已提交
3328 3329 3330
  STableQueryInfo  *pTableQueryInfo = pRuntimeEnv->pQuery->current;
  SWindowResInfo   *pWindowResInfo = &pRuntimeEnv->windowResInfo;

H
Haojun Liao 已提交
3331 3332 3333 3334
  // lastKey needs to be updated
  pTableQueryInfo->lastKey = nextKey;
  setAdditionalInfo(pQInfo, pTableQueryInfo->pTable, pTableQueryInfo);

H
Haojun Liao 已提交
3335 3336 3337
  if (pRuntimeEnv->prevGroupId != INT32_MIN && pRuntimeEnv->prevGroupId == groupIndex) {
    return;
  }
3338

H
Haojun Liao 已提交
3339
  int32_t GROUPRESULTID = 1;
3340
  SWindowResult *pWindowRes = doSetTimeWindowFromKey(pRuntimeEnv, pWindowResInfo, (char *)&groupIndex, sizeof(groupIndex));
3341 3342 3343
  if (pWindowRes == NULL) {
    return;
  }
3344

3345 3346 3347 3348 3349 3350 3351 3352 3353 3354
  /*
   * 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;
    }
  }
3355

H
Haojun Liao 已提交
3356 3357
  // record the current active group id
  pRuntimeEnv->prevGroupId = groupIndex;
3358 3359 3360 3361
  setWindowResOutputBuf(pRuntimeEnv, pWindowRes);
  initCtxOutputBuf(pRuntimeEnv);
}

H
Haojun Liao 已提交
3362
void setWindowResOutputBuf(SQueryRuntimeEnv *pRuntimeEnv, SWindowResult *pResult) {
3363
  SQuery *pQuery = pRuntimeEnv->pQuery;
3364

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

3370
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
3371 3372 3373
    if (functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM || functionId == TSDB_FUNC_DIFF) {
      pCtx->ptsOutputBuf = pRuntimeEnv->pCtx[0].aOutputBuf;
    }
3374

3375 3376 3377 3378 3379
    /*
     * set the output buffer information and intermediate buffer
     * not all queries require the interResultBuf, such as COUNT
     */
    pCtx->resultInfo = &pResult->resultInfo[i];
3380

3381 3382 3383 3384 3385 3386
    // set super table query flag
    SResultInfo *pResInfo = GET_RES_INFO(pCtx);
    pResInfo->superTableQ = pRuntimeEnv->stableQuery;
  }
}

H
Haojun Liao 已提交
3387 3388
void setWindowResOutputBufInitCtx(SQueryRuntimeEnv *pRuntimeEnv, SWindowResult *pResult) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
3389

H
Haojun Liao 已提交
3390 3391 3392 3393 3394
  // Note: pResult->pos[i]->num == 0, there is only fixed number of results for each group
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
    SQLFunctionCtx *pCtx = &pRuntimeEnv->pCtx[i];

    pCtx->resultInfo = &pResult->resultInfo[i];
H
Haojun Liao 已提交
3395
    if (pCtx->resultInfo->initialized && pCtx->resultInfo->complete) {
H
Haojun Liao 已提交
3396 3397
      continue;
    }
3398

H
Haojun Liao 已提交
3399 3400
    pCtx->aOutputBuf = getPosInResultPage(pRuntimeEnv, i, pResult);
    pCtx->currentStage = 0;
3401

H
Haojun Liao 已提交
3402 3403 3404 3405
    int32_t functionId = pCtx->functionId;
    if (functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM || functionId == TSDB_FUNC_DIFF) {
      pCtx->ptsOutputBuf = pRuntimeEnv->pCtx[0].aOutputBuf;
    }
3406

H
Haojun Liao 已提交
3407 3408 3409 3410 3411
    /*
     * set the output buffer information and intermediate buffer
     * not all queries require the interResultBuf, such as COUNT
     */
    pCtx->resultInfo->superTableQ = pRuntimeEnv->stableQuery;     // set super table query flag
3412

H
Haojun Liao 已提交
3413 3414 3415 3416 3417 3418
    if (!pCtx->resultInfo->initialized) {
      aAggs[functionId].init(pCtx);
    }
  }
}

3419
int32_t setAdditionalInfo(SQInfo *pQInfo, void* pTable, STableQueryInfo *pTableQueryInfo) {
3420
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
3421

3422
  setTagVal(pRuntimeEnv, pTable, pQInfo->tsdb);
3423

3424 3425
  // both the master and supplement scan needs to set the correct ts comp start position
  if (pRuntimeEnv->pTSBuf != NULL) {
3426
    if (pTableQueryInfo->cur.vgroupIndex == -1) {
3427
      pTableQueryInfo->tag = pRuntimeEnv->pCtx[0].tag.i64Key;
3428

3429
      tsBufGetElemStartPos(pRuntimeEnv->pTSBuf, 0, pTableQueryInfo->tag);
3430

3431 3432 3433 3434 3435 3436
      // keep the cursor info of current meter
      pTableQueryInfo->cur = pRuntimeEnv->pTSBuf->cur;
    } else {
      tsBufSetCursor(pRuntimeEnv->pTSBuf, &pTableQueryInfo->cur);
    }
  }
3437

3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449
  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 已提交
3450
void setIntervalQueryRange(SQInfo *pQInfo, TSKEY key) {
3451 3452
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
3453 3454
  STableQueryInfo *pTableQueryInfo = pQuery->current;
  
3455 3456 3457
  if (pTableQueryInfo->queryRangeSet) {
    pTableQueryInfo->lastKey = key;
  } else {
3458
    pTableQueryInfo->win.skey = key;
3459
    STimeWindow win = {.skey = key, .ekey = pQuery->window.ekey};
3460

3461 3462 3463 3464 3465
    // 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;
    }
3466

3467 3468 3469 3470 3471 3472
    /**
     * 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.
     */
H
Haojun Liao 已提交
3473
    STimeWindow     w = TSWINDOW_INITIALIZER, realWin = TSWINDOW_INITIALIZER;
3474
    SWindowResInfo *pWindowResInfo = &pTableQueryInfo->windowResInfo;
3475

H
Haojun Liao 已提交
3476 3477
    TSKEY sk = MIN(win.skey, win.ekey);
    TSKEY ek = MAX(win.skey, win.ekey);
H
Haojun Liao 已提交
3478
    getAlignQueryTimeWindow(pQuery, win.skey, sk, ek, &realWin, &w);
3479
    pWindowResInfo->startTime = pTableQueryInfo->win.skey;  // windowSKey may be 0 in case of 1970 timestamp
3480

3481 3482
    if (pWindowResInfo->prevSKey == TSKEY_INITIAL_VAL) {
      if (!QUERY_IS_ASC_QUERY(pQuery)) {
H
Haojun Liao 已提交
3483
        assert(win.ekey == pQuery->window.ekey);
3484
      }
3485 3486
      
      pWindowResInfo->prevSKey = w.skey;
3487
    }
3488

3489
    pTableQueryInfo->queryRangeSet = 1;
3490
    pTableQueryInfo->lastKey = pTableQueryInfo->win.skey;
3491 3492 3493 3494
  }
}

bool requireTimestamp(SQuery *pQuery) {
3495
  for (int32_t i = 0; i < pQuery->numOfOutput; i++) {
3496
    int32_t functionId = pQuery->pSelectExpr[i].base.functionId;
3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509
    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 已提交
3510 3511 3512
  STableQueryInfo* pTableQueryInfo = pQuery->current;
  
  bool loadPrimaryTS = (pTableQueryInfo->lastKey >= w->skey && pTableQueryInfo->lastKey <= w->ekey) ||
3513 3514
                       (pQuery->window.ekey >= w->skey && pQuery->window.ekey <= w->ekey) || requireTimestamp(pQuery);

3515 3516 3517 3518 3519
  return loadPrimaryTS;
}

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

3521 3522 3523 3524
  int32_t totalSubset = 0;
  if (isGroupbyNormalCol(pQuery->pGroupbyExpr) || (isIntervalQuery(pQuery))) {
    totalSubset = numOfClosedTimeWindow(&pQInfo->runtimeEnv.windowResInfo);
  } else {
H
Haojun Liao 已提交
3525
    totalSubset = GET_NUM_OF_TABLEGROUP(pQInfo);
3526
  }
3527

3528 3529 3530 3531 3532 3533
  return totalSubset;
}

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

3535 3536 3537
  int32_t numOfResult = 0;
  int32_t startIdx = 0;
  int32_t step = -1;
3538

3539
  qDebug("QInfo:%p start to copy data from windowResInfo to query buf", pQInfo);
3540
  int32_t totalSubset = getNumOfSubset(pQInfo);
3541

3542
  if (orderType == TSDB_ORDER_ASC) {
3543
    startIdx = pQInfo->groupIndex;
3544 3545
    step = 1;
  } else {  // desc order copy all data
3546
    startIdx = totalSubset - pQInfo->groupIndex - 1;
3547 3548
    step = -1;
  }
3549

3550 3551 3552
  for (int32_t i = startIdx; (i < totalSubset) && (i >= 0); i += step) {
    if (result[i].numOfRows == 0) {
      pQInfo->offset = 0;
3553
      pQInfo->groupIndex += 1;
3554 3555
      continue;
    }
3556

dengyihao's avatar
dengyihao 已提交
3557
    assert(pQInfo->offset <= 1);
3558

3559 3560
    int32_t numOfRowsToCopy = result[i].numOfRows - pQInfo->offset;
    int32_t oldOffset = pQInfo->offset;
3561

3562 3563 3564 3565
    /*
     * 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
     */
3566 3567 3568 3569 3570
    if (numOfRowsToCopy > pQuery->rec.capacity - numOfResult) {
      numOfRowsToCopy = pQuery->rec.capacity - numOfResult;
      pQInfo->offset += numOfRowsToCopy;
    } else {
      pQInfo->offset = 0;
3571
      pQInfo->groupIndex += 1;
3572
    }
3573

3574
    for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
3575
      int32_t size = pRuntimeEnv->pCtx[j].outputBytes;
3576

3577 3578 3579 3580
      char *out = pQuery->sdata[j]->data + numOfResult * size;
      char *in = getPosInResultPage(pRuntimeEnv, j, &result[i]);
      memcpy(out, in + oldOffset * size, size * numOfRowsToCopy);
    }
3581

3582
    numOfResult += numOfRowsToCopy;
3583 3584 3585
    if (numOfResult == pQuery->rec.capacity) {
      break;
    }
3586
  }
3587

3588
  qDebug("QInfo:%p copy data to query buf completed", pQInfo);
3589 3590

#ifdef _DEBUG_VIEW
3591
  displayInterResult(pQuery->sdata, pRuntimeEnv, numOfResult);
3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606
#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;
3607

3608
  int32_t orderType = (pQuery->pGroupbyExpr != NULL) ? pQuery->pGroupbyExpr->orderType : TSDB_ORDER_ASC;
3609
  int32_t numOfResult = doCopyToSData(pQInfo, result, orderType);
3610

3611
  pQuery->rec.rows += numOfResult;
3612

3613
  assert(pQuery->rec.rows <= pQuery->rec.capacity);
3614 3615
}

3616
static UNUSED_FUNC void updateWindowResNumOfRes(SQueryRuntimeEnv *pRuntimeEnv, STableQueryInfo *pTableQueryInfo) {
3617
  SQuery *pQuery = pRuntimeEnv->pQuery;
3618

3619 3620
  // update the number of result for each, only update the number of rows for the corresponding window result.
  if (pQuery->intervalTime == 0) {
3621

3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632
    for (int32_t i = 0; i < pRuntimeEnv->windowResInfo.size; ++i) {
      SWindowResult *pResult = &pRuntimeEnv->windowResInfo.pResult[i];

      for (int32_t j = 0; j < pQuery->numOfOutput; ++j) {
        int32_t functionId = pRuntimeEnv->pCtx[j].functionId;
        if (functionId == TSDB_FUNC_TS || functionId == TSDB_FUNC_TAG || functionId == TSDB_FUNC_TAGPRJ) {
          continue;
        }

        pResult->numOfRows = MAX(pResult->numOfRows, pResult->resultInfo[j].numOfRes);
      }
3633
    }
3634 3635 3636 3637 3638 3639 3640 3641

//    int32_t g = pTableQueryInfo->groupIndex;
//    assert(pRuntimeEnv->windowResInfo.size > 0);
//
//    SWindowResult *pWindowRes = doSetTimeWindowFromKey(pRuntimeEnv, &pRuntimeEnv->windowResInfo, (char *)&g, sizeof(g));
//    if (pWindowRes->numOfRows == 0) {
//      pWindowRes->numOfRows = getNumOfResult(pRuntimeEnv);
//    }
3642 3643 3644
  }
}

3645 3646
void stableApplyFunctionsOnBlock(SQueryRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pDataBlockInfo, SDataStatis *pStatis,
    SArray *pDataBlock, __block_search_fn_t searchFn) {
3647
  SQuery *         pQuery = pRuntimeEnv->pQuery;
3648 3649
  STableQueryInfo* pTableQueryInfo = pQuery->current;
  
3650
  SWindowResInfo * pWindowResInfo = &pTableQueryInfo->windowResInfo;
H
hjxilinx 已提交
3651
  pQuery->pos = QUERY_IS_ASC_QUERY(pQuery)? 0 : pDataBlockInfo->rows - 1;
3652

3653
  if (pQuery->numOfFilterCols > 0 || pRuntimeEnv->pTSBuf != NULL || isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
3654
    rowwiseApplyFunctions(pRuntimeEnv, pStatis, pDataBlockInfo, pWindowResInfo, pDataBlock);
3655
  } else {
3656
    blockwiseApplyFunctions(pRuntimeEnv, pStatis, pDataBlockInfo, pWindowResInfo, searchFn, pDataBlock);
3657
  }
3658

H
hjxilinx 已提交
3659
  updateWindowResNumOfRes(pRuntimeEnv, pTableQueryInfo);
3660 3661
}

3662 3663 3664
bool queryHasRemainResults(SQueryRuntimeEnv* pRuntimeEnv) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
  SFillInfo *pFillInfo = pRuntimeEnv->pFillInfo;
3665

H
Haojun Liao 已提交
3666
  if (pQuery->limit.limit > 0 && pQuery->rec.total >= pQuery->limit.limit) {
3667 3668
    return false;
  }
3669

3670
  if (pQuery->fillType != TSDB_FILL_NONE && !isPointInterpoQuery(pQuery)) {
H
Haojun Liao 已提交
3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698
    // There are results not returned to client yet, so filling operation applied to the remain result is required
    // in the first place.
    int32_t remain = taosNumOfRemainRows(pFillInfo);
    if (remain > 0) {
      return true;
    }

    /*
     * While the code reaches here, there are no results remains 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)) {
      int32_t numOfTotal = getFilledNumOfRes(pFillInfo, pQuery->window.ekey, pQuery->rec.capacity);
      return numOfTotal > 0;
    }

  } else {
    // there are results waiting for returned to client.
    if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED) &&
        (isGroupbyNormalCol(pQuery->pGroupbyExpr) || isIntervalQuery(pQuery)) &&
        (pRuntimeEnv->windowResInfo.size > 0)) {
      return true;
    }
3699
  }
3700 3701

  return false;
3702 3703 3704
}

static void doCopyQueryResultToMsg(SQInfo *pQInfo, int32_t numOfRows, char *data) {
3705
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
H
Haojun Liao 已提交
3706

3707 3708
  for (int32_t col = 0; col < pQuery->numOfOutput; ++col) {
    int32_t bytes = pQuery->pSelectExpr[col].bytes;
3709

3710 3711 3712
    memmove(data, pQuery->sdata[col]->data, bytes * numOfRows);
    data += bytes * numOfRows;
  }
3713

weixin_48148422's avatar
weixin_48148422 已提交
3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725
  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 已提交
3726 3727
  // all data returned, set query over
  if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
3728
    if (pQInfo->runtimeEnv.stableQuery) {
3729
      if (pQInfo->tableIndex >= pQInfo->tableqinfoGroupInfo.numOfTables) {
3730 3731 3732
        setQueryStatus(pQuery, QUERY_OVER);
      }
    } else {
3733 3734 3735
      if (!queryHasRemainResults(&pQInfo->runtimeEnv)) {
        setQueryStatus(pQuery, QUERY_OVER);
      }
3736
    }
H
hjxilinx 已提交
3737
  }
3738 3739
}

H
Haojun Liao 已提交
3740
int32_t doFillGapsInResults(SQueryRuntimeEnv* pRuntimeEnv, tFilePage **pDst, int32_t *numOfFilled) {
3741
  SQInfo* pQInfo = GET_QINFO_ADDR(pRuntimeEnv);
3742
  SQuery *pQuery = pRuntimeEnv->pQuery;
3743 3744
  SFillInfo* pFillInfo = pRuntimeEnv->pFillInfo;
  
3745
  while (1) {
3746
    int32_t ret = taosGenerateDataBlock(pFillInfo, (tFilePage**) pQuery->sdata, pQuery->rec.capacity);
3747
    
3748
    // todo apply limit output function
3749 3750
    /* reached the start position of according to offset value, return immediately */
    if (pQuery->limit.offset == 0) {
3751
      qDebug("QInfo:%p initial numOfRows:%d, generate filled result:%d rows", pQInfo, pFillInfo->numOfRows, ret);
3752 3753
      return ret;
    }
3754

3755
    if (pQuery->limit.offset < ret) {
3756
      qDebug("QInfo:%p initial numOfRows:%d, generate filled result:%d rows, offset:%" PRId64 ". Discard due to offset, remain:%" PRId64 ", new offset:%d",
3757 3758
             pQInfo, pFillInfo->numOfRows, ret, pQuery->limit.offset, ret - pQuery->limit.offset, 0);
      
3759 3760 3761
      ret -= pQuery->limit.offset;
      // todo !!!!there exactly number of interpo is not valid.
      // todo refactor move to the beginning of buffer
3762 3763 3764
      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);
3765
      }
3766
      
3767 3768 3769
      pQuery->limit.offset = 0;
      return ret;
    } else {
3770
      qDebug("QInfo:%p initial numOfRows:%d, generate filled result:%d rows, offset:%" PRId64 ". Discard due to offset, "
B
Bomin Zhang 已提交
3771
             "remain:%d, new offset:%" PRId64, pQInfo, pFillInfo->numOfRows, ret, pQuery->limit.offset, 0,
3772 3773
          pQuery->limit.offset - ret);
      
3774
      pQuery->limit.offset -= ret;
3775
      pQuery->rec.rows = 0;
3776 3777
      ret = 0;
    }
3778 3779

    if (!queryHasRemainResults(pRuntimeEnv)) {
3780 3781 3782 3783 3784
      return ret;
    }
  }
}

3785
static void queryCostStatis(SQInfo *pQInfo) {
3786
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
3787 3788 3789 3790 3791 3792 3793
  SQueryCostInfo *pSummary = &pRuntimeEnv->summary;
//  if (pRuntimeEnv->pResultBuf == NULL) {
////    pSummary->tmpBufferInDisk = 0;
//  } else {
////    pSummary->tmpBufferInDisk = getResBufSize(pRuntimeEnv->pResultBuf);
//  }
//
3794
//  qDebug("QInfo:%p cost: comp blocks:%d, size:%d Bytes, elapsed time:%.2f ms", pQInfo, pSummary->readCompInfo,
3795 3796
//         pSummary->totalCompInfoSize, pSummary->loadCompInfoUs / 1000.0);
//
3797
//  qDebug("QInfo:%p cost: field info: %d, size:%d Bytes, avg size:%.2f Bytes, elapsed time:%.2f ms", pQInfo,
3798 3799 3800
//         pSummary->readField, pSummary->totalFieldSize, (double)pSummary->totalFieldSize / pSummary->readField,
//         pSummary->loadFieldUs / 1000.0);
//
3801
//  qDebug(
3802 3803 3804
//      "QInfo:%p cost: 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);
3805
  
3806
  qDebug("QInfo:%p :cost summary: elpased time:%"PRId64" us, total blocks:%d, use block statis:%d, use block data:%d, "
3807 3808
         "total rows:%"PRId64 ", check rows:%"PRId64, pQInfo, pSummary->elapsedTime, pSummary->totalBlocks,
         pSummary->loadBlockStatis, pSummary->loadBlocks, pSummary->totalRows, pSummary->totalCheckedRows);
3809

3810
//  qDebug("QInfo:%p cost: temp file:%d Bytes", pQInfo, pSummary->tmpBufferInDisk);
3811
//
3812 3813
//  qDebug("QInfo:%p cost: file:%d, table:%d", pQInfo, pSummary->numOfFiles, pSummary->numOfTables);
//  qDebug("QInfo:%p cost: seek ops:%d", pQInfo, pSummary->numOfSeek);
3814 3815 3816
//
//  double total = pSummary->fileTimeUs + pSummary->cacheTimeUs;
//  double io = pSummary->loadCompInfoUs + pSummary->loadBlocksUs + pSummary->loadFieldUs;
3817 3818
  
  // todo add the intermediate result save cost!!
3819 3820
//  double computing = total - io;
//
3821
//  qDebug(
3822 3823 3824 3825 3826
//      "QInfo:%p cost: 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);
3827 3828
}

3829 3830
static void updateOffsetVal(SQueryRuntimeEnv *pRuntimeEnv, SDataBlockInfo *pBlockInfo) {
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
hjxilinx 已提交
3831 3832
  STableQueryInfo* pTableQueryInfo = pQuery->current;
  
3833
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);
3834

3835
  if (pQuery->limit.offset == pBlockInfo->rows) {  // current block will ignore completed
H
hjxilinx 已提交
3836
    pTableQueryInfo->lastKey = QUERY_IS_ASC_QUERY(pQuery) ? pBlockInfo->window.ekey + step : pBlockInfo->window.skey + step;
3837 3838 3839
    pQuery->limit.offset = 0;
    return;
  }
3840

3841 3842 3843 3844 3845
  if (QUERY_IS_ASC_QUERY(pQuery)) {
    pQuery->pos = pQuery->limit.offset;
  } else {
    pQuery->pos = pBlockInfo->rows - pQuery->limit.offset - 1;
  }
3846

3847
  assert(pQuery->pos >= 0 && pQuery->pos <= pBlockInfo->rows - 1);
3848

3849
  SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pQueryHandle, NULL);
3850
  SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);
3851

3852
  // update the pQuery->limit.offset value, and pQuery->pos value
H
Haojun Liao 已提交
3853
  TSKEY *keys = (TSKEY *) pColInfoData->pData;
3854 3855

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

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

3861
  qDebug("QInfo:%p check data block, brange:%" PRId64 "-%" PRId64 ", numOfRows:%d, numOfRes:%d, lastKey:%"PRId64, GET_QINFO_ADDR(pRuntimeEnv),
3862
         pBlockInfo->window.skey, pBlockInfo->window.ekey, pBlockInfo->rows, numOfRes, pQuery->current->lastKey);
3863
}
3864

3865 3866 3867 3868 3869
void skipBlocks(SQueryRuntimeEnv *pRuntimeEnv) {
  SQuery *pQuery = pRuntimeEnv->pQuery;

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

3872 3873 3874
  pQuery->pos = 0;
  int32_t step = GET_FORWARD_DIRECTION_FACTOR(pQuery->order.order);

H
hjxilinx 已提交
3875
  STableQueryInfo* pTableQueryInfo = pQuery->current;
3876
  TsdbQueryHandleT pQueryHandle = pRuntimeEnv->pQueryHandle;
3877

3878 3879 3880
  while (tsdbNextDataBlock(pQueryHandle)) {
    if (isQueryKilled(GET_QINFO_ADDR(pRuntimeEnv))) {
      return;
3881
    }
3882

3883
    SDataBlockInfo blockInfo = tsdbRetrieveDataBlockInfo(pQueryHandle);
3884

3885 3886
    if (pQuery->limit.offset > blockInfo.rows) {
      pQuery->limit.offset -= blockInfo.rows;
H
hjxilinx 已提交
3887 3888
      pTableQueryInfo->lastKey = (QUERY_IS_ASC_QUERY(pQuery)) ? blockInfo.window.ekey : blockInfo.window.skey;
      pTableQueryInfo->lastKey += step;
3889

3890
      qDebug("QInfo:%p skip rows:%d, offset:%" PRId64, GET_QINFO_ADDR(pRuntimeEnv), blockInfo.rows,
3891 3892
             pQuery->limit.offset);
    } else {  // find the appropriated start position in current block
3893 3894 3895
      updateOffsetVal(pRuntimeEnv, &blockInfo);
      break;
    }
3896
  }
3897
}
3898

H
Haojun Liao 已提交
3899
static bool skipTimeInterval(SQueryRuntimeEnv *pRuntimeEnv, TSKEY* start) {
3900
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
Haojun Liao 已提交
3901
  *start = pQuery->current->lastKey;
3902

3903
  // if queried with value filter, do NOT forward query start position
3904
  if (pQuery->limit.offset <= 0 || pQuery->numOfFilterCols > 0 || pRuntimeEnv->pTSBuf != NULL || pRuntimeEnv->pFillInfo != NULL) {
3905
    return true;
3906
  }
3907

3908 3909 3910 3911 3912
  /*
   * 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
   */
3913
  assert(pRuntimeEnv->windowResInfo.prevSKey == TSKEY_INITIAL_VAL);
3914

H
Haojun Liao 已提交
3915
  STimeWindow w = TSWINDOW_INITIALIZER, realWin = TSWINDOW_INITIALIZER;
3916
  
3917
  SWindowResInfo *pWindowResInfo = &pRuntimeEnv->windowResInfo;
H
hjxilinx 已提交
3918
  STableQueryInfo *pTableQueryInfo = pQuery->current;
3919

3920 3921
  while (tsdbNextDataBlock(pRuntimeEnv->pQueryHandle)) {
    SDataBlockInfo blockInfo = tsdbRetrieveDataBlockInfo(pRuntimeEnv->pQueryHandle);
3922

H
Haojun Liao 已提交
3923 3924
    if (QUERY_IS_ASC_QUERY(pQuery)) {
      if (pWindowResInfo->prevSKey == TSKEY_INITIAL_VAL) {
H
Haojun Liao 已提交
3925
        getAlignQueryTimeWindow(pQuery, blockInfo.window.skey, blockInfo.window.skey, pQuery->window.ekey, &realWin, &w);
H
Haojun Liao 已提交
3926 3927 3928
        pWindowResInfo->startTime = w.skey;
        pWindowResInfo->prevSKey = w.skey;
      }
3929
    } else {
H
Haojun Liao 已提交
3930
      getAlignQueryTimeWindow(pQuery, blockInfo.window.ekey, pQuery->window.ekey, blockInfo.window.ekey, &realWin, &w);
3931

3932 3933 3934
      pWindowResInfo->startTime = pQuery->window.skey;
      pWindowResInfo->prevSKey = w.skey;
    }
3935

3936 3937
    // the first time window
    STimeWindow win = getActiveTimeWindow(pWindowResInfo, pWindowResInfo->prevSKey, pQuery);
3938

3939 3940 3941 3942 3943 3944
    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;
      }
3945

3946 3947
      STimeWindow tw = win;
      getNextTimeWindow(pQuery, &tw);
3948

3949
      if (pQuery->limit.offset == 0) {
3950 3951
        if ((tw.skey <= blockInfo.window.ekey && QUERY_IS_ASC_QUERY(pQuery)) ||
            (tw.ekey >= blockInfo.window.skey && !QUERY_IS_ASC_QUERY(pQuery))) {
H
Haojun Liao 已提交
3952 3953
          // load the data block and check data remaining in current data block
          // TODO optimize performance
3954 3955 3956
          SArray *         pDataBlock = tsdbRetrieveDataBlock(pRuntimeEnv->pQueryHandle, NULL);
          SColumnInfoData *pColInfoData = taosArrayGet(pDataBlock, 0);

3957 3958 3959
          tw = win;
          int32_t startPos =
              getNextQualifiedWindow(pRuntimeEnv, &tw, &blockInfo, pColInfoData->pData, binarySearchForKey);
3960 3961 3962 3963
          assert(startPos >= 0);

          // set the abort info
          pQuery->pos = startPos;
H
Haojun Liao 已提交
3964 3965 3966 3967 3968 3969
          
          // reset the query start timestamp
          pTableQueryInfo->win.skey = ((TSKEY *)pColInfoData->pData)[startPos];
          pQuery->window.skey = pTableQueryInfo->win.skey;
          *start = pTableQueryInfo->win.skey;
          
3970
          pWindowResInfo->prevSKey = tw.skey;
H
Haojun Liao 已提交
3971 3972
          int32_t index = pRuntimeEnv->windowResInfo.curIndex;
          
H
hjxilinx 已提交
3973
          int32_t numOfRes = tableApplyFunctionsOnBlock(pRuntimeEnv, &blockInfo, NULL, binarySearchForKey, pDataBlock);
H
Haojun Liao 已提交
3974 3975
          pRuntimeEnv->windowResInfo.curIndex = index;  // restore the window index
          
3976
          qDebug("QInfo:%p check data block, brange:%" PRId64 "-%" PRId64 ", numOfRows:%d, numOfRes:%d, lastKey:%"PRId64,
3977 3978
                 GET_QINFO_ADDR(pRuntimeEnv), blockInfo.window.skey, blockInfo.window.ekey, blockInfo.rows, numOfRes, pQuery->current->lastKey);
          
3979
          return true;
H
Haojun Liao 已提交
3980 3981 3982 3983
        } else { // do nothing
          *start = tw.skey;
          pQuery->window.skey = tw.skey;
          pWindowResInfo->prevSKey = tw.skey;
3984
          return true;
3985 3986 3987
        }
      }

H
Haojun Liao 已提交
3988 3989 3990 3991 3992 3993 3994
      /*
       * 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.
       */
3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006
      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 已提交
4007
        pTableQueryInfo->lastKey = ((TSKEY *)pColInfoData->pData)[startPos];
4008 4009
        pWindowResInfo->prevSKey = tw.skey;
        win = tw;
4010
      } else {
H
Haojun Liao 已提交
4011
        break;  // offset is not 0, and next time window begins or ends in the next block.
4012 4013 4014
      }
    }
  }
4015

4016 4017 4018
  return true;
}

B
Bomin Zhang 已提交
4019 4020
static void setupQueryHandle(void* tsdb, SQInfo* pQInfo, bool isSTableQuery) {
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
4021 4022
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;

B
Bomin Zhang 已提交
4023 4024 4025 4026 4027 4028 4029
  if (onlyQueryTags(pQuery)) {
    return;
  }

  if (isSTableQuery && (!isIntervalQuery(pQuery)) && (!isFixedOutputQuery(pQuery))) {
    return;
  }
4030 4031

  STsdbQueryCond cond = {
B
Bomin Zhang 已提交
4032 4033 4034 4035
    .twindow = pQuery->window,
    .order   = pQuery->order.order,
    .colList = pQuery->colList,
    .numOfCols = pQuery->numOfCols,
4036
  };
weixin_48148422's avatar
weixin_48148422 已提交
4037

B
Bomin Zhang 已提交
4038
  if (!isSTableQuery
4039
    && (pQInfo->tableqinfoGroupInfo.numOfTables == 1)
B
Bomin Zhang 已提交
4040 4041 4042 4043 4044
    && (cond.order == TSDB_ORDER_ASC) 
    && (!isIntervalQuery(pQuery))
    && (!isGroupbyNormalCol(pQuery->pGroupbyExpr))
    && (!isFixedOutputQuery(pQuery))
  ) {
H
Haojun Liao 已提交
4045
    SArray* pa = GET_TABLEGROUP(pQInfo, 0);
4046 4047
    STableQueryInfo* pCheckInfo = taosArrayGetP(pa, 0);
    cond.twindow = pCheckInfo->win;
4048
  }
B
Bomin Zhang 已提交
4049

H
Haojun Liao 已提交
4050
  if (isFirstLastRowQuery(pQuery)) {
4051
    pRuntimeEnv->pQueryHandle = tsdbQueryLastRow(tsdb, &cond, &pQInfo->tableGroupInfo, pQInfo);
4052
  } else if (isPointInterpoQuery(pQuery)) {
4053
    pRuntimeEnv->pQueryHandle = tsdbQueryRowsInExternalWindow(tsdb, &cond, &pQInfo->tableGroupInfo, pQInfo);
H
Haojun Liao 已提交
4054
  } else {
4055
    pRuntimeEnv->pQueryHandle = tsdbQueryTables(tsdb, &cond, &pQInfo->tableGroupInfo, pQInfo);
H
Haojun Liao 已提交
4056
  }
B
Bomin Zhang 已提交
4057 4058
}

4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071
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;
4072
    pFillCol[i].fillVal.i = pQuery->fillVal[i];
4073 4074 4075 4076 4077 4078 4079
    
    offset += pExprInfo->bytes;
  }
  
  return pFillCol;
}

4080
int32_t doInitQInfo(SQInfo *pQInfo, STSBuf *pTsBuf, void *tsdb, int32_t vgId, bool isSTableQuery) {
4081 4082
  int32_t code = TSDB_CODE_SUCCESS;
  
4083 4084 4085
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;

  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
4086
  pQuery->precision = tsdbGetCfg(tsdb)->precision;
4087 4088

  setScanLimitationByResultBuffer(pQuery);
H
Haojun Liao 已提交
4089
  changeExecuteScanOrder(pQInfo, false);
B
Bomin Zhang 已提交
4090
  setupQueryHandle(tsdb, pQInfo, isSTableQuery);
4091
  
4092
  pQInfo->tsdb = tsdb;
4093
  pQInfo->vgId = vgId;
4094 4095

  pRuntimeEnv->pQuery = pQuery;
H
Haojun Liao 已提交
4096
  pRuntimeEnv->pTSBuf = pTsBuf;
4097
  pRuntimeEnv->cur.vgroupIndex = -1;
4098
  pRuntimeEnv->stableQuery = isSTableQuery;
H
Haojun Liao 已提交
4099
  pRuntimeEnv->prevGroupId = INT32_MIN;
4100

H
Haojun Liao 已提交
4101
  if (pTsBuf != NULL) {
4102 4103 4104 4105 4106 4107 4108 4109 4110 4111
    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;
  }

H
Haojun Liao 已提交
4112
  pRuntimeEnv->numOfRowsPerPage = getNumOfRowsInResultPage(pQuery, pRuntimeEnv->topBotQuery, isSTableQuery);
4113 4114 4115

  if (isSTableQuery) {
    int32_t rows = getInitialPageNum(pQInfo);
4116
    code = createDiskbasedResultBuffer(&pRuntimeEnv->pResultBuf, rows, pQuery->rowSize, pQInfo);
4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134
    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);
4135
    code = createDiskbasedResultBuffer(&pRuntimeEnv->pResultBuf, rows, pQuery->rowSize, pQInfo);
4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149
    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);
  }

4150
  if (pQuery->fillType != TSDB_FILL_NONE && !isPointInterpoQuery(pQuery)) {
4151 4152
    SFillColInfo* pColInfo = taosCreateFillColInfo(pQuery);
    pRuntimeEnv->pFillInfo = taosInitFillInfo(pQuery->order.order, 0, 0, pQuery->rec.capacity, pQuery->numOfOutput,
H
Haojun Liao 已提交
4153 4154
                                              pQuery->slidingTime, pQuery->slidingTimeUnit, pQuery->precision,
                                              pQuery->fillType, pColInfo);
4155
  }
4156

4157 4158 4159
  // todo refactor
  pRuntimeEnv->topBotQuery = isTopBottomQuery(pQuery);
  setQueryStatus(pQuery, QUERY_NOT_COMPLETED);
4160

4161
  return TSDB_CODE_SUCCESS;
4162 4163
}

4164
static void enableExecutionForNextTable(SQueryRuntimeEnv *pRuntimeEnv) {
4165
  SQuery *pQuery = pRuntimeEnv->pQuery;
4166

4167
  for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
4168 4169 4170 4171 4172 4173 4174
    SResultInfo *pResInfo = GET_RES_INFO(&pRuntimeEnv->pCtx[i]);
    if (pResInfo != NULL) {
      pResInfo->complete = false;
    }
  }
}

H
Haojun Liao 已提交
4175
static int64_t scanMultiTableDataBlocks(SQInfo *pQInfo) {
4176
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
H
Haojun Liao 已提交
4177 4178
  SQuery*           pQuery = pRuntimeEnv->pQuery;
  SQueryCostInfo*   summary  = &pRuntimeEnv->summary;
4179
  
H
hjxilinx 已提交
4180
  int64_t st = taosGetTimestampMs();
4181

4182
  TsdbQueryHandleT pQueryHandle = IS_MASTER_SCAN(pRuntimeEnv)? pRuntimeEnv->pQueryHandle : pRuntimeEnv->pSecQueryHandle;
4183
  while (tsdbNextDataBlock(pQueryHandle)) {
4184
    summary->totalBlocks += 1;
4185
    if (isQueryKilled(pQInfo)) {
4186 4187
      break;
    }
4188

4189
    SDataBlockInfo  blockInfo = tsdbRetrieveDataBlockInfo(pQueryHandle);
H
Haojun Liao 已提交
4190 4191 4192 4193
    STableQueryInfo **pTableQueryInfo = (STableQueryInfo**) taosHashGet(pQInfo->tableqinfoGroupInfo.map, &blockInfo.tid, sizeof(blockInfo.tid));
    if(pTableQueryInfo == NULL) {
      break;
    }
4194

H
Haojun Liao 已提交
4195
    assert(*pTableQueryInfo != NULL);
H
Haojun Liao 已提交
4196
    SET_CURRENT_QUERY_TABLE_INFO(pRuntimeEnv, *pTableQueryInfo);
4197

4198
    SDataStatis *pStatis = NULL;
H
hjxilinx 已提交
4199
    SArray *pDataBlock = loadDataBlockOnDemand(pRuntimeEnv, pQueryHandle, &blockInfo, &pStatis);
4200

4201 4202 4203
    if (!isGroupbyNormalCol(pQuery->pGroupbyExpr)) {
      if (!isIntervalQuery(pQuery)) {
        int32_t step = QUERY_IS_ASC_QUERY(pQuery)? 1:-1;
H
Haojun Liao 已提交
4204
        setExecutionContext(pQInfo, (*pTableQueryInfo)->groupIndex, blockInfo.window.ekey + step);
4205 4206 4207
      } else {  // interval query
        TSKEY nextKey = blockInfo.window.skey;
        setIntervalQueryRange(pQInfo, nextKey);
H
Haojun Liao 已提交
4208
        /*int32_t ret = */setAdditionalInfo(pQInfo, (*pTableQueryInfo)->pTable, *pTableQueryInfo);
4209
      }
4210
    }
4211

4212 4213 4214
    summary->totalRows += blockInfo.rows;
    stableApplyFunctionsOnBlock(pRuntimeEnv, &blockInfo, pStatis, pDataBlock, binarySearchForKey);
  
4215
    qDebug("QInfo:%p check data block, uid:%"PRId64", tid:%d, brange:%" PRId64 "-%" PRId64 ", numOfRows:%d, lastKey:%" PRId64,
4216
           pQInfo, blockInfo.uid, blockInfo.tid, blockInfo.window.skey, blockInfo.window.ekey, blockInfo.rows, pQuery->current->lastKey);
4217
  }
4218

H
hjxilinx 已提交
4219 4220
  int64_t et = taosGetTimestampMs();
  return et - st;
4221 4222
}

4223 4224
static bool multiTableMultioutputHelper(SQInfo *pQInfo, int32_t index) {
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
4225
  SQuery *          pQuery = pRuntimeEnv->pQuery;
4226

4227
  setQueryStatus(pQuery, QUERY_NOT_COMPLETED);
H
Haojun Liao 已提交
4228
  SArray *group = GET_TABLEGROUP(pQInfo, 0);
4229
  STableQueryInfo* pCheckInfo = taosArrayGetP(group, index);
4230

4231
  setTagVal(pRuntimeEnv, pCheckInfo->pTable, pQInfo->tsdb);
4232

4233
  STableId id = tsdbGetTableId(pCheckInfo->pTable);
4234
  qDebug("QInfo:%p query on (%d): uid:%" PRIu64 ", tid:%d, qrange:%" PRId64 "-%" PRId64, pQInfo, index,
4235
         id.uid, id.tid, pCheckInfo->lastKey, pCheckInfo->win.ekey);
4236

4237
  STsdbQueryCond cond = {
4238
      .twindow   = {pCheckInfo->lastKey, pCheckInfo->win.ekey},
H
hjxilinx 已提交
4239 4240
      .order     = pQuery->order.order,
      .colList   = pQuery->colList,
4241
      .numOfCols = pQuery->numOfCols,
4242
  };
4243

H
hjxilinx 已提交
4244
  // todo refactor
4245
  SArray *g1 = taosArrayInit(1, POINTER_BYTES);
4246
  SArray *tx = taosArrayInit(1, POINTER_BYTES);
4247

4248
  taosArrayPush(tx, &pCheckInfo->pTable);
4249
  taosArrayPush(g1, &tx);
4250
  STableGroupInfo gp = {.numOfTables = 1, .pGroupList = g1};
4251

4252
  // include only current table
4253 4254 4255 4256
  if (pRuntimeEnv->pQueryHandle != NULL) {
    tsdbCleanupQueryHandle(pRuntimeEnv->pQueryHandle);
    pRuntimeEnv->pQueryHandle = NULL;
  }
4257

H
Haojun Liao 已提交
4258
  pRuntimeEnv->pQueryHandle = tsdbQueryTables(pQInfo->tsdb, &cond, &gp, pQInfo);
4259 4260
  taosArrayDestroy(tx);
  taosArrayDestroy(g1);
4261

4262
  if (pRuntimeEnv->pTSBuf != NULL) {
4263
    if (pRuntimeEnv->cur.vgroupIndex == -1) {
4264 4265
      int64_t tag = pRuntimeEnv->pCtx[0].tag.i64Key;
      STSElem elem = tsBufGetElemStartPos(pRuntimeEnv->pTSBuf, 0, tag);
4266

4267 4268 4269 4270 4271 4272 4273 4274
      // failed to find data with the specified tag value
      if (elem.vnode < 0) {
        return false;
      }
    } else {
      tsBufSetCursor(pRuntimeEnv->pTSBuf, &pRuntimeEnv->cur);
    }
  }
4275

4276
  initCtxOutputBuf(pRuntimeEnv);
4277 4278 4279 4280 4281 4282 4283 4284 4285 4286
  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
 */
4287
static void sequentialTableProcess(SQInfo *pQInfo) {
4288
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
4289
  SQuery *          pQuery = pRuntimeEnv->pQuery;
4290
  setQueryStatus(pQuery, QUERY_COMPLETED);
4291

H
Haojun Liao 已提交
4292
  size_t numOfGroups = GET_NUM_OF_TABLEGROUP(pQInfo);
4293

H
Haojun Liao 已提交
4294
  if (isPointInterpoQuery(pQuery) || isFirstLastRowQuery(pQuery)) {
4295 4296
    resetCtxOutputBuf(pRuntimeEnv);
    assert(pQuery->limit.offset == 0 && pQuery->limit.limit != 0);
4297

4298
    while (pQInfo->groupIndex < numOfGroups) {
H
Haojun Liao 已提交
4299
      SArray* group = taosArrayGetP(pQInfo->tableGroupInfo.pGroupList, pQInfo->groupIndex);
4300

4301
      qDebug("QInfo:%p last_row query on group:%d, total group:%zu, current group:%p", pQInfo, pQInfo->groupIndex,
dengyihao's avatar
dengyihao 已提交
4302
             numOfGroups, group);
H
Haojun Liao 已提交
4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322

      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);
      
      STableGroupInfo gp = {.numOfTables = taosArrayGetSize(tx), .pGroupList = g1};

      // include only current table
      if (pRuntimeEnv->pQueryHandle != NULL) {
        tsdbCleanupQueryHandle(pRuntimeEnv->pQueryHandle);
        pRuntimeEnv->pQueryHandle = NULL;
      }
      
4323
      if (isFirstLastRowQuery(pQuery)) {
H
Haojun Liao 已提交
4324
        pRuntimeEnv->pQueryHandle = tsdbQueryLastRow(pQInfo->tsdb, &cond, &gp, pQInfo);
H
Haojun Liao 已提交
4325
      } else {
H
Haojun Liao 已提交
4326
        pRuntimeEnv->pQueryHandle = tsdbQueryRowsInExternalWindow(pQInfo->tsdb, &cond, &gp, pQInfo);
4327
      }
H
Haojun Liao 已提交
4328 4329
      
      initCtxOutputBuf(pRuntimeEnv);
4330
      
4331
      SArray* s = tsdbGetQueriedTableList(pRuntimeEnv->pQueryHandle);
4332 4333
      assert(taosArrayGetSize(s) >= 1);
      
4334
      setTagVal(pRuntimeEnv, taosArrayGetP(s, 0), pQInfo->tsdb);
4335 4336 4337
      if (isFirstLastRowQuery(pQuery)) {
        assert(taosArrayGetSize(s) == 1);
      }
H
Haojun Liao 已提交
4338

dengyihao's avatar
dengyihao 已提交
4339
      taosArrayDestroy(s);
H
Haojun Liao 已提交
4340

H
Haojun Liao 已提交
4341
      // here we simply set the first table as current table
H
Haojun Liao 已提交
4342
      pQuery->current = (STableQueryInfo*) GET_TABLEGROUP(pQInfo, 0);
4343
      scanOneTableDataBlocks(pRuntimeEnv, pQuery->current->lastKey);
H
Haojun Liao 已提交
4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355
      
      int64_t numOfRes = getNumOfResult(pRuntimeEnv);
      if (numOfRes > 0) {
        pQuery->rec.rows += numOfRes;
        forwardCtxOutputBuf(pRuntimeEnv, numOfRes);
      }
      
      skipResults(pRuntimeEnv);
      pQInfo->groupIndex += 1;

      // enable execution for next table, when handling the projection query
      enableExecutionForNextTable(pRuntimeEnv);
4356 4357 4358 4359 4360 4361 4362 4363

      if (pQuery->rec.rows >= pQuery->rec.capacity) {
        setQueryStatus(pQuery, QUERY_RESBUF_FULL);
        break;
      }
    }
  } else if (isGroupbyNormalCol(pQuery->pGroupbyExpr)) { // group-by on normal columns query
    while (pQInfo->groupIndex < numOfGroups) {
H
Haojun Liao 已提交
4364
      SArray* group = taosArrayGetP(pQInfo->tableGroupInfo.pGroupList, pQInfo->groupIndex);
4365

4366
      qDebug("QInfo:%p group by normal columns group:%d, total group:%zu", pQInfo, pQInfo->groupIndex, numOfGroups);
4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388

      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);

      STableGroupInfo gp = {.numOfTables = taosArrayGetSize(tx), .pGroupList = g1};

      // include only current table
      if (pRuntimeEnv->pQueryHandle != NULL) {
        tsdbCleanupQueryHandle(pRuntimeEnv->pQueryHandle);
        pRuntimeEnv->pQueryHandle = NULL;
      }

      pRuntimeEnv->pQueryHandle = tsdbQueryTables(pQInfo->tsdb, &cond, &gp, pQInfo);

4389
      SArray* s = tsdbGetQueriedTableList(pRuntimeEnv->pQueryHandle);
4390 4391
      assert(taosArrayGetSize(s) >= 1);

4392
      setTagVal(pRuntimeEnv, taosArrayGetP(s, 0), pQInfo->tsdb);
4393 4394 4395 4396 4397 4398 4399 4400

      // here we simply set the first table as current table
      scanMultiTableDataBlocks(pQInfo);
      pQInfo->groupIndex += 1;

      SWindowResInfo *pWindowResInfo = &pRuntimeEnv->windowResInfo;

        // no results generated for current group, continue to try the next group
dengyihao's avatar
dengyihao 已提交
4401
      taosArrayDestroy(s); 
4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415
      if (pWindowResInfo->size <= 0) {
        continue;
      }

      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

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

4416
      qDebug("QInfo:%p generated groupby columns results %d rows for group %d completed", pQInfo, pWindowResInfo->size,
4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430
          pQInfo->groupIndex);
      int32_t currentGroupIndex = pQInfo->groupIndex;

      pQuery->rec.rows = 0;
      pQInfo->groupIndex = 0;

      ensureOutputBufferSimple(pRuntimeEnv, pWindowResInfo->size);
      copyFromWindowResToSData(pQInfo, pWindowResInfo->pResult);

      pQInfo->groupIndex = currentGroupIndex;  //restore the group index
      assert(pQuery->rec.rows == pWindowResInfo->size);

      clearClosedTimeWindow(pRuntimeEnv);
      break;
4431 4432 4433
    }
  } else {
    /*
4434
     * 1. super table projection query, 2. ts-comp query
4435 4436 4437
     * 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.
     */
4438
    if (pQInfo->groupIndex > 0) {
4439
      copyFromWindowResToSData(pQInfo, pRuntimeEnv->windowResInfo.pResult);
4440
      pQuery->rec.total += pQuery->rec.rows;
4441

4442
      if (pQuery->rec.rows > 0) {
4443 4444 4445
        return;
      }
    }
4446

4447
    // all data have returned already
4448
    if (pQInfo->tableIndex >= pQInfo->tableqinfoGroupInfo.numOfTables) {
4449 4450
      return;
    }
4451

4452 4453
    resetCtxOutputBuf(pRuntimeEnv);
    resetTimeWindowInfo(pRuntimeEnv, &pRuntimeEnv->windowResInfo);
4454

H
Haojun Liao 已提交
4455
    SArray *group = GET_TABLEGROUP(pQInfo, 0);
4456 4457
    assert(taosArrayGetSize(group) == pQInfo->tableqinfoGroupInfo.numOfTables &&
           1 == taosArrayGetSize(pQInfo->tableqinfoGroupInfo.pGroupList));
4458

4459
    while (pQInfo->tableIndex < pQInfo->tableqinfoGroupInfo.numOfTables) {
4460
      if (isQueryKilled(pQInfo)) {
4461 4462
        return;
      }
4463

4464
      pQuery->current = taosArrayGetP(group, pQInfo->tableIndex);
4465
      if (!multiTableMultioutputHelper(pQInfo, pQInfo->tableIndex)) {
4466
        pQInfo->tableIndex++;
4467 4468
        continue;
      }
4469

H
hjxilinx 已提交
4470
      // TODO handle the limit offset problem
4471
      if (pQuery->numOfFilterCols == 0 && pQuery->limit.offset > 0) {
4472
        //        skipBlocks(pRuntimeEnv);
4473 4474
        if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
          pQInfo->tableIndex++;
4475 4476 4477
          continue;
        }
      }
4478

4479
      scanOneTableDataBlocks(pRuntimeEnv, pQuery->current->lastKey);
4480
      skipResults(pRuntimeEnv);
4481

4482
      // the limitation of output result is reached, set the query completed
4483
      if (limitResults(pRuntimeEnv)) {
4484
        pQInfo->tableIndex = pQInfo->tableqinfoGroupInfo.numOfTables;
4485 4486
        break;
      }
4487

4488 4489
      // enable execution for next table, when handling the projection query
      enableExecutionForNextTable(pRuntimeEnv);
4490

4491
      if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
4492 4493 4494 4495 4496 4497
        /*
         * 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.
         */
4498
        pQInfo->tableIndex++;
weixin_48148422's avatar
weixin_48148422 已提交
4499 4500

        STableIdInfo tidInfo;
4501 4502 4503 4504
        STableId id = tsdbGetTableId(pQuery->current->pTable);

        tidInfo.uid = id.uid;
        tidInfo.tid = id.tid;
weixin_48148422's avatar
weixin_48148422 已提交
4505
        tidInfo.key = pQuery->current->lastKey;
weixin_48148422's avatar
weixin_48148422 已提交
4506 4507
        taosArrayPush(pQInfo->arrTableIdInfo, &tidInfo);

4508
        // if the buffer is full or group by each table, we need to jump out of the loop
4509 4510
        if (Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL) /*||
            isGroupbyEachTable(pQuery->pGroupbyExpr, pSupporter->pSidSet)*/) {
4511 4512
          break;
        }
4513

4514
      } else {
4515
        // all data in the result buffer are skipped due to the offset, continue to retrieve data from current meter
4516 4517
        if (pQuery->rec.rows == 0) {
          assert(!Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL));
4518 4519
          continue;
        } else {
4520 4521 4522
          // buffer is full, wait for the next round to retrieve data from current meter
          assert(Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL));
          break;
4523 4524 4525
        }
      }
    }
H
Haojun Liao 已提交
4526

4527
    if (pQInfo->tableIndex >= pQInfo->tableqinfoGroupInfo.numOfTables) {
H
Haojun Liao 已提交
4528 4529
      setQueryStatus(pQuery, QUERY_COMPLETED);
    }
4530
  }
4531

4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543
  /*
   * 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 已提交
4544
    finalizeQueryResult(pRuntimeEnv);
4545
  }
4546

4547 4548 4549
  if (pRuntimeEnv->pTSBuf != NULL) {
    pRuntimeEnv->cur = pRuntimeEnv->pTSBuf->cur;
  }
4550

4551
  qDebug(
B
Bomin Zhang 已提交
4552
      "QInfo %p numOfTables:%"PRIu64", index:%d, numOfGroups:%zu, %"PRId64" points returned, total:%"PRId64", offset:%" PRId64,
4553
      pQInfo, pQInfo->tableqinfoGroupInfo.numOfTables, pQInfo->tableIndex, numOfGroups, pQuery->rec.rows, pQuery->rec.total,
4554
      pQuery->limit.offset);
4555 4556
}

4557 4558 4559 4560
static void doSaveContext(SQInfo *pQInfo) {
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;

4561 4562 4563 4564
  SET_REVERSE_SCAN_FLAG(pRuntimeEnv);
  SWAP(pQuery->window.skey, pQuery->window.ekey, TSKEY);
  SWITCH_ORDER(pQuery->order.order);
  
4565
  if (pRuntimeEnv->pTSBuf != NULL) {
4566
    pRuntimeEnv->pTSBuf->cur.order = pQuery->order.order;
4567
  }
4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579
  
  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);
  }
H
Haojun Liao 已提交
4580 4581

  pRuntimeEnv->prevGroupId = INT32_MIN;
4582
  pRuntimeEnv->pSecQueryHandle = tsdbQueryTables(pQInfo->tsdb, &cond, &pQInfo->tableGroupInfo, pQInfo);
4583 4584 4585 4586
  
  setQueryStatus(pQuery, QUERY_NOT_COMPLETED);
  switchCtxOrder(pRuntimeEnv);
  disableFuncInReverseScan(pQInfo);
H
hjxilinx 已提交
4587 4588
}

4589 4590 4591 4592
static void doRestoreContext(SQInfo *pQInfo) {
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;

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

4595
  if (pRuntimeEnv->pTSBuf != NULL) {
4596
    SWITCH_ORDER(pRuntimeEnv->pTSBuf->cur.order);
4597
  }
4598

4599
  switchCtxOrder(pRuntimeEnv);
4600 4601 4602
  SET_MASTER_SCAN_FLAG(pRuntimeEnv);
}

4603 4604 4605
static void doCloseAllTimeWindowAfterScan(SQInfo *pQInfo) {
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;

H
hjxilinx 已提交
4606
  if (isIntervalQuery(pQuery)) {
H
Haojun Liao 已提交
4607
    size_t numOfGroup = GET_NUM_OF_TABLEGROUP(pQInfo);
4608
    for (int32_t i = 0; i < numOfGroup; ++i) {
H
Haojun Liao 已提交
4609
      SArray *group = GET_TABLEGROUP(pQInfo, i);
4610

4611
      size_t num = taosArrayGetSize(group);
4612
      for (int32_t j = 0; j < num; ++j) {
4613 4614
        STableQueryInfo* item = taosArrayGetP(group, j);
        closeAllTimeWindow(&item->windowResInfo);
4615
      }
H
hjxilinx 已提交
4616 4617 4618 4619 4620 4621 4622
    }
  } else {  // close results for group result
    closeAllTimeWindow(&pQInfo->runtimeEnv.windowResInfo);
  }
}

static void multiTableQueryProcess(SQInfo *pQInfo) {
4623 4624 4625
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;

4626
  if (pQInfo->groupIndex > 0) {
4627
    /*
4628
     * if the groupIndex > 0, the query process must be completed yet, we only need to
4629 4630
     * copy the data into output buffer
     */
H
hjxilinx 已提交
4631
    if (isIntervalQuery(pQuery)) {
4632 4633
      copyResToQueryResultBuf(pQInfo, pQuery);
#ifdef _DEBUG_VIEW
4634
      displayInterResult(pQuery->sdata, pRuntimeEnv, pQuery->sdata[0]->num);
4635 4636 4637 4638
#endif
    } else {
      copyFromWindowResToSData(pQInfo, pRuntimeEnv->windowResInfo.pResult);
    }
4639

4640
    qDebug("QInfo:%p current:%"PRId64", total:%"PRId64"", pQInfo, pQuery->rec.rows, pQuery->rec.total);
4641 4642
    return;
  }
4643

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

H
hjxilinx 已提交
4647
  // do check all qualified data blocks
H
Haojun Liao 已提交
4648
  int64_t el = scanMultiTableDataBlocks(pQInfo);
4649
  qDebug("QInfo:%p master scan completed, elapsed time: %" PRId64 "ms, reverse scan start", pQInfo, el);
4650

H
hjxilinx 已提交
4651 4652
  // query error occurred or query is killed, abort current execution
  if (pQInfo->code != TSDB_CODE_SUCCESS || isQueryKilled(pQInfo)) {
4653
    qDebug("QInfo:%p query killed or error occurred, code:%s, abort", pQInfo, tstrerror(pQInfo->code));
H
hjxilinx 已提交
4654
    return;
4655
  }
4656

H
hjxilinx 已提交
4657 4658
  // close all time window results
  doCloseAllTimeWindowAfterScan(pQInfo);
4659

H
hjxilinx 已提交
4660 4661
  if (needReverseScan(pQuery)) {
    doSaveContext(pQInfo);
4662

H
Haojun Liao 已提交
4663
    el = scanMultiTableDataBlocks(pQInfo);
4664
    qDebug("QInfo:%p reversed scan completed, elapsed time: %" PRId64 "ms", pQInfo, el);
4665

H
hjxilinx 已提交
4666 4667
    doRestoreContext(pQInfo);
  } else {
4668
    qDebug("QInfo:%p no need to do reversed scan, query completed", pQInfo);
4669
  }
4670

4671
  setQueryStatus(pQuery, QUERY_COMPLETED);
4672

H
hjxilinx 已提交
4673
  if (pQInfo->code != TSDB_CODE_SUCCESS || isQueryKilled(pQInfo)) {
4674
    qDebug("QInfo:%p query killed or error occurred, code:%s, abort", pQInfo, tstrerror(pQInfo->code));
H
hjxilinx 已提交
4675 4676
    return;
  }
4677

H
hjxilinx 已提交
4678
  if (isIntervalQuery(pQuery) || isSumAvgRateQuery(pQuery)) {
4679
    if (mergeIntoGroupResult(pQInfo) == TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
4680
      copyResToQueryResultBuf(pQInfo, pQuery);
4681 4682

#ifdef _DEBUG_VIEW
4683
      displayInterResult(pQuery->sdata, pRuntimeEnv, pQuery->sdata[0]->num);
4684 4685 4686 4687 4688
#endif
    }
  } else {  // not a interval query
    copyFromWindowResToSData(pQInfo, pRuntimeEnv->windowResInfo.pResult);
  }
4689

4690
  // handle the limitation of output buffer
4691
  qDebug("QInfo:%p points returned:%" PRId64 ", total:%" PRId64, pQInfo, pQuery->rec.rows, pQuery->rec.total + pQuery->rec.rows);
4692 4693 4694 4695 4696 4697 4698 4699
}

/*
 * 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 已提交
4700
static void tableFixedOutputProcess(SQInfo *pQInfo, STableQueryInfo* pTableInfo) {
4701
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
H
hjxilinx 已提交
4702 4703
  
  SQuery *pQuery = pRuntimeEnv->pQuery;
H
Haojun Liao 已提交
4704 4705 4706 4707
  if (!isTopBottomQuery(pQuery) && pQuery->limit.offset > 0) {  // no need to execute, since the output will be ignore.
    return;
  }
  
H
hjxilinx 已提交
4708 4709
  pQuery->current = pTableInfo;  // set current query table info
  
4710
  scanOneTableDataBlocks(pRuntimeEnv, pTableInfo->lastKey);
H
hjxilinx 已提交
4711
  finalizeQueryResult(pRuntimeEnv);
4712

4713
  if (isQueryKilled(pQInfo)) {
4714 4715
    return;
  }
4716

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

4720
  skipResults(pRuntimeEnv);
4721
  limitResults(pRuntimeEnv);
4722 4723
}

H
hjxilinx 已提交
4724
static void tableMultiOutputProcess(SQInfo *pQInfo, STableQueryInfo* pTableInfo) {
4725
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
H
hjxilinx 已提交
4726 4727 4728 4729
  
  SQuery *pQuery = pRuntimeEnv->pQuery;
  pQuery->current = pTableInfo;
  
4730 4731 4732 4733
  // for ts_comp query, re-initialized is not allowed
  if (!isTSCompQuery(pQuery)) {
    resetCtxOutputBuf(pRuntimeEnv);
  }
4734

4735 4736 4737 4738 4739 4740
  // 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;
  }
4741 4742

  while (1) {
4743
    scanOneTableDataBlocks(pRuntimeEnv, pQuery->current->lastKey);
H
hjxilinx 已提交
4744
    finalizeQueryResult(pRuntimeEnv);
4745

4746
    if (isQueryKilled(pQInfo)) {
4747 4748 4749
      return;
    }

4750 4751
    pQuery->rec.rows = getNumOfResult(pRuntimeEnv);
    if (pQuery->limit.offset > 0 && pQuery->numOfFilterCols > 0 && pQuery->rec.rows > 0) {
4752
      skipResults(pRuntimeEnv);
4753 4754 4755
    }

    /*
H
hjxilinx 已提交
4756 4757
     * 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
4758
     */
4759
    if (pQuery->rec.rows > 0 || Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
4760 4761 4762
      break;
    }

4763
    qDebug("QInfo:%p skip current result, offset:%" PRId64 ", next qrange:%" PRId64 "-%" PRId64,
B
Bomin Zhang 已提交
4764
           pQInfo, pQuery->limit.offset, pQuery->current->lastKey, pQuery->current->win.ekey);
4765 4766 4767 4768

    resetCtxOutputBuf(pRuntimeEnv);
  }

4769
  limitResults(pRuntimeEnv);
4770
  if (Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL)) {
4771
    qDebug("QInfo:%p query paused due to output limitation, next qrange:%" PRId64 "-%" PRId64, pQInfo,
H
hjxilinx 已提交
4772
        pQuery->current->lastKey, pQuery->window.ekey);
weixin_48148422's avatar
weixin_48148422 已提交
4773 4774
  } else if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
    STableIdInfo tidInfo;
4775 4776 4777 4778
    STableId id = tsdbGetTableId(pQuery->current);

    tidInfo.uid = id.uid;
    tidInfo.tid = id.tid;
weixin_48148422's avatar
weixin_48148422 已提交
4779 4780
    tidInfo.key = pQuery->current->lastKey;
    taosArrayPush(pQInfo->arrTableIdInfo, &tidInfo);
4781 4782
  }

4783 4784 4785
  if (!isTSCompQuery(pQuery)) {
    assert(pQuery->rec.rows <= pQuery->rec.capacity);
  }
4786 4787
}

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

4791
  while (1) {
4792
    scanOneTableDataBlocks(pRuntimeEnv, start);
4793

4794
    if (isQueryKilled(GET_QINFO_ADDR(pRuntimeEnv))) {
4795 4796
      return;
    }
4797

4798
    assert(!Q_STATUS_EQUAL(pQuery->status, QUERY_NOT_COMPLETED));
H
hjxilinx 已提交
4799
    finalizeQueryResult(pRuntimeEnv);
4800

4801 4802 4803
    // 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 &&
4804
        pQuery->fillType == TSDB_FILL_NONE) {
4805 4806
      // maxOutput <= 0, means current query does not generate any results
      int32_t numOfClosed = numOfClosedTimeWindow(&pRuntimeEnv->windowResInfo);
4807

4808 4809 4810 4811
      int32_t c = MIN(numOfClosed, pQuery->limit.offset);
      clearFirstNTimeWindow(pRuntimeEnv, c);
      pQuery->limit.offset -= c;
    }
4812

4813
    if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED | QUERY_RESBUF_FULL)) {
4814 4815 4816 4817 4818
      break;
    }
  }
}

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

H
hjxilinx 已提交
4823 4824
  SQuery *pQuery = pRuntimeEnv->pQuery;
  pQuery->current = pTableInfo;
4825

H
Haojun Liao 已提交
4826
  int32_t numOfFilled = 0;
H
Haojun Liao 已提交
4827 4828
  TSKEY newStartKey = TSKEY_INITIAL_VAL;
  
4829
  // skip blocks without load the actual data block from file if no filter condition present
H
Haojun Liao 已提交
4830
  skipTimeInterval(pRuntimeEnv, &newStartKey);
4831
  if (pQuery->limit.offset > 0 && pQuery->numOfFilterCols == 0 && pRuntimeEnv->pFillInfo == NULL) {
4832 4833 4834 4835
    setQueryStatus(pQuery, QUERY_COMPLETED);
    return;
  }

4836
  while (1) {
H
Haojun Liao 已提交
4837
    tableIntervalProcessImpl(pRuntimeEnv, newStartKey);
4838

H
hjxilinx 已提交
4839
    if (isIntervalQuery(pQuery)) {
4840
      pQInfo->groupIndex = 0;  // always start from 0
4841
      pQuery->rec.rows = 0;
4842
      copyFromWindowResToSData(pQInfo, pRuntimeEnv->windowResInfo.pResult);
4843

4844
      clearFirstNTimeWindow(pRuntimeEnv, pQInfo->groupIndex);
4845
    }
4846

4847
    // the offset is handled at prepare stage if no interpolation involved
4848
    if (pQuery->fillType == TSDB_FILL_NONE || pQuery->rec.rows == 0) {
4849
      limitResults(pRuntimeEnv);
4850 4851
      break;
    } else {
H
Haojun Liao 已提交
4852
      taosFillSetStartInfo(pRuntimeEnv->pFillInfo, pQuery->rec.rows, pQuery->window.ekey);
4853
      taosFillCopyInputDataFromFilePage(pRuntimeEnv->pFillInfo, (tFilePage**) pQuery->sdata);
H
Haojun Liao 已提交
4854
      numOfFilled = 0;
4855
      
H
Haojun Liao 已提交
4856
      pQuery->rec.rows = doFillGapsInResults(pRuntimeEnv, (tFilePage **)pQuery->sdata, &numOfFilled);
4857
      if (pQuery->rec.rows > 0 || Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
4858
        limitResults(pRuntimeEnv);
4859 4860
        break;
      }
4861

4862
      // no result generated yet, continue retrieve data
4863
      pQuery->rec.rows = 0;
4864 4865
    }
  }
4866

4867 4868
  // all data scanned, the group by normal column can return
  if (isGroupbyNormalCol(pQuery->pGroupbyExpr)) {  // todo refactor with merge interval time result
4869
    pQInfo->groupIndex = 0;
4870
    pQuery->rec.rows = 0;
4871
    copyFromWindowResToSData(pQInfo, pRuntimeEnv->windowResInfo.pResult);
4872
    clearFirstNTimeWindow(pRuntimeEnv, pQInfo->groupIndex);
4873
  }
4874

H
Haojun Liao 已提交
4875
  pQInfo->pointsInterpo += numOfFilled;
4876 4877
}

4878 4879 4880 4881
static void tableQueryImpl(SQInfo *pQInfo) {
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;

4882
  if (queryHasRemainResults(pRuntimeEnv)) {
4883

H
Haojun Liao 已提交
4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895
    if (pQuery->fillType != TSDB_FILL_NONE) {
      /*
       * 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 numOfFilled = 0;
      pQuery->rec.rows = doFillGapsInResults(pRuntimeEnv, (tFilePage **)pQuery->sdata, &numOfFilled);

      if (pQuery->rec.rows > 0) {
        limitResults(pRuntimeEnv);
      }

H
Haojun Liao 已提交
4896
      qDebug("QInfo:%p current:%" PRId64 " returned, total:%" PRId64, pQInfo, pQuery->rec.rows, pQuery->rec.total);
4897
      return;
H
Haojun Liao 已提交
4898
    } else {
4899
      pQuery->rec.rows = 0;
4900
      pQInfo->groupIndex = 0;  // always start from 0
4901

4902 4903
      if (pRuntimeEnv->windowResInfo.size > 0) {
        copyFromWindowResToSData(pQInfo, pRuntimeEnv->windowResInfo.pResult);
4904
        clearFirstNTimeWindow(pRuntimeEnv, pQInfo->groupIndex);
4905

4906
        if (pQuery->rec.rows > 0) {
4907
          qDebug("QInfo:%p %"PRId64" rows returned from group results, total:%"PRId64"", pQInfo, pQuery->rec.rows, pQuery->rec.total);
H
Haojun Liao 已提交
4908 4909 4910

          // there are not data remains
          if (pRuntimeEnv->windowResInfo.size <= 0) {
H
Haojun Liao 已提交
4911
            qDebug("QInfo:%p query over, %"PRId64" rows are returned", pQInfo, pQuery->rec.total);
H
Haojun Liao 已提交
4912 4913
          }

4914 4915 4916 4917 4918
          return;
        }
      }
    }
  }
4919

H
hjxilinx 已提交
4920
  // number of points returned during this query
4921
  pQuery->rec.rows = 0;
4922
  int64_t st = taosGetTimestampUs();
H
hjxilinx 已提交
4923
  
4924
  assert(pQInfo->tableqinfoGroupInfo.numOfTables == 1);
H
Haojun Liao 已提交
4925
  SArray* g = GET_TABLEGROUP(pQInfo, 0);
4926
  STableQueryInfo* item = taosArrayGetP(g, 0);
H
hjxilinx 已提交
4927
  
4928
  // group by normal column, sliding window query, interval query are handled by interval query processor
H
[td-98]  
hjxilinx 已提交
4929
  if (isIntervalQuery(pQuery) || isGroupbyNormalCol(pQuery->pGroupbyExpr)) {  // interval (down sampling operation)
4930
    tableIntervalProcess(pQInfo, item);
4931
  } else if (isFixedOutputQuery(pQuery)) {
4932
    tableFixedOutputProcess(pQInfo, item);
4933 4934
  } else {  // diff/add/multiply/subtract/division
    assert(pQuery->checkBuffer == 1);
4935
    tableMultiOutputProcess(pQInfo, item);
4936
  }
4937

4938
  // record the total elapsed time
4939
  pRuntimeEnv->summary.elapsedTime += (taosGetTimestampUs() - st);
4940
  assert(pQInfo->tableqinfoGroupInfo.numOfTables == 1);
4941 4942
}

4943 4944
static void stableQueryImpl(SQInfo *pQInfo) {
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
4945
  pQuery->rec.rows = 0;
4946

4947
  int64_t st = taosGetTimestampUs();
4948

H
hjxilinx 已提交
4949
  if (isIntervalQuery(pQuery) ||
4950 4951
      (isFixedOutputQuery(pQuery) && (!isPointInterpoQuery(pQuery)) && !isGroupbyNormalCol(pQuery->pGroupbyExpr) &&
      !isFirstLastRowQuery(pQuery))) {
H
hjxilinx 已提交
4952
    multiTableQueryProcess(pQInfo);
4953
  } else {
4954
    assert((pQuery->checkBuffer == 1 && pQuery->intervalTime == 0) || isPointInterpoQuery(pQuery) ||
4955
            isFirstLastRowQuery(pQuery) || isGroupbyNormalCol(pQuery->pGroupbyExpr));
4956

4957
    sequentialTableProcess(pQInfo);
4958
  }
4959

H
hjxilinx 已提交
4960
  // record the total elapsed time
4961
  pQInfo->runtimeEnv.summary.elapsedTime += (taosGetTimestampUs() - st);
H
hjxilinx 已提交
4962 4963
}

4964
static int32_t getColumnIndexInSource(SQueryTableMsg *pQueryMsg, SSqlFuncMsg *pExprMsg, SColumnInfo* pTagCols) {
4965
  int32_t j = 0;
4966

4967
  if (TSDB_COL_IS_TAG(pExprMsg->colInfo.flag)) {
H
Haojun Liao 已提交
4968 4969 4970 4971
    if (pExprMsg->colInfo.colId == TSDB_TBNAME_COLUMN_INDEX) {
      return -1;
    }

4972 4973 4974 4975
    while(j < pQueryMsg->numOfTags) {
      if (pExprMsg->colInfo.colId == pTagCols[j].colId) {
        return j;
      }
4976

4977 4978
      j += 1;
    }
4979

4980 4981 4982 4983 4984
  } else {
    while (j < pQueryMsg->numOfCols) {
      if (pExprMsg->colInfo.colId == pQueryMsg->colList[j].colId) {
        return j;
      }
4985

4986
      j += 1;
4987 4988 4989
    }
  }

4990
  assert(0);
4991 4992
}

4993 4994 4995
bool validateExprColumnInfo(SQueryTableMsg *pQueryMsg, SSqlFuncMsg *pExprMsg, SColumnInfo* pTagCols) {
  int32_t j = getColumnIndexInSource(pQueryMsg, pExprMsg, pTagCols);
  return j < pQueryMsg->numOfCols || j < pQueryMsg->numOfTags;
4996 4997
}

4998
static bool validateQueryMsg(SQueryTableMsg *pQueryMsg) {
H
hjxilinx 已提交
4999
  if (pQueryMsg->intervalTime < 0) {
5000
    qError("qmsg:%p illegal value of interval time %" PRId64, pQueryMsg, pQueryMsg->intervalTime);
5001
    return false;
5002 5003
  }

H
hjxilinx 已提交
5004
  if (pQueryMsg->numOfTables <= 0) {
S
slguan 已提交
5005
    qError("qmsg:%p illegal value of numOfTables %d", pQueryMsg, pQueryMsg->numOfTables);
5006
    return false;
5007 5008
  }

H
hjxilinx 已提交
5009
  if (pQueryMsg->numOfGroupCols < 0) {
S
slguan 已提交
5010
    qError("qmsg:%p illegal value of numOfGroupbyCols %d", pQueryMsg, pQueryMsg->numOfGroupCols);
5011
    return false;
5012 5013
  }

5014 5015
  if (pQueryMsg->numOfOutput > TSDB_MAX_COLUMNS || pQueryMsg->numOfOutput <= 0) {
    qError("qmsg:%p illegal value of output columns %d", pQueryMsg, pQueryMsg->numOfOutput);
5016
    return false;
5017 5018
  }

5019 5020 5021 5022 5023 5024 5025 5026 5027 5028
  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) {
H
Haojun Liao 已提交
5029 5030 5031 5032 5033
      SSqlFuncMsg* pFuncMsg = pExprMsg[i];

      if ((pFuncMsg->functionId == TSDB_FUNC_TAGPRJ) ||
          (pFuncMsg->functionId == TSDB_FUNC_TID_TAG && pFuncMsg->colInfo.colId == TSDB_TBNAME_COLUMN_INDEX) ||
          (pFuncMsg->functionId == TSDB_FUNC_COUNT && pFuncMsg->colInfo.colId == TSDB_TBNAME_COLUMN_INDEX)) {
5034
        continue;
5035
      }
5036

5037
      return false;
5038 5039
    }
  }
5040

5041
  return true;
5042 5043
}

5044
static char *createTableIdList(SQueryTableMsg *pQueryMsg, char *pMsg, SArray **pTableIdList) {
H
hjxilinx 已提交
5045
  assert(pQueryMsg->numOfTables > 0);
5046

weixin_48148422's avatar
weixin_48148422 已提交
5047
  *pTableIdList = taosArrayInit(pQueryMsg->numOfTables, sizeof(STableIdInfo));
5048

weixin_48148422's avatar
weixin_48148422 已提交
5049 5050
  for (int32_t j = 0; j < pQueryMsg->numOfTables; ++j) {
    STableIdInfo* pTableIdInfo = (STableIdInfo *)pMsg;
5051

5052
    pTableIdInfo->tid = htonl(pTableIdInfo->tid);
H
hjxilinx 已提交
5053 5054
    pTableIdInfo->uid = htobe64(pTableIdInfo->uid);
    pTableIdInfo->key = htobe64(pTableIdInfo->key);
5055

H
hjxilinx 已提交
5056 5057 5058
    taosArrayPush(*pTableIdList, pTableIdInfo);
    pMsg += sizeof(STableIdInfo);
  }
5059

H
hjxilinx 已提交
5060 5061
  return pMsg;
}
5062

5063
/**
H
hjxilinx 已提交
5064
 * pQueryMsg->head has been converted before this function is called.
5065
 *
H
hjxilinx 已提交
5066
 * @param pQueryMsg
5067 5068 5069 5070
 * @param pTableIdList
 * @param pExpr
 * @return
 */
5071
static int32_t convertQueryMsg(SQueryTableMsg *pQueryMsg, SArray **pTableIdList, SSqlFuncMsg ***pExpr,
weixin_48148422's avatar
weixin_48148422 已提交
5072
                               char **tagCond, char** tbnameCond, SColIndex **groupbyCols, SColumnInfo** tagCols) {
5073 5074
  int32_t code = TSDB_CODE_SUCCESS;

5075 5076 5077 5078 5079 5080 5081 5082
  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 已提交
5083

5084 5085
  pQueryMsg->order = htons(pQueryMsg->order);
  pQueryMsg->orderColId = htons(pQueryMsg->orderColId);
H
Haojun Liao 已提交
5086
  pQueryMsg->queryType = htonl(pQueryMsg->queryType);
weixin_48148422's avatar
weixin_48148422 已提交
5087
  pQueryMsg->tagNameRelType = htons(pQueryMsg->tagNameRelType);
5088 5089

  pQueryMsg->numOfCols = htons(pQueryMsg->numOfCols);
5090
  pQueryMsg->numOfOutput = htons(pQueryMsg->numOfOutput);
H
hjxilinx 已提交
5091
  pQueryMsg->numOfGroupCols = htons(pQueryMsg->numOfGroupCols);
5092 5093 5094
  pQueryMsg->tagCondLen = htons(pQueryMsg->tagCondLen);
  pQueryMsg->tsOffset = htonl(pQueryMsg->tsOffset);
  pQueryMsg->tsLen = htonl(pQueryMsg->tsLen);
H
hjxilinx 已提交
5095
  pQueryMsg->tsNumOfBlocks = htonl(pQueryMsg->tsNumOfBlocks);
5096
  pQueryMsg->tsOrder = htonl(pQueryMsg->tsOrder);
5097
  pQueryMsg->numOfTags = htonl(pQueryMsg->numOfTags);
5098

5099
  // query msg safety check
5100
  if (!validateQueryMsg(pQueryMsg)) {
5101 5102
    code = TSDB_CODE_QRY_INVALID_MSG;
    goto _cleanup;
5103 5104
  }

H
hjxilinx 已提交
5105 5106
  char *pMsg = (char *)(pQueryMsg->colList) + sizeof(SColumnInfo) * pQueryMsg->numOfCols;
  for (int32_t col = 0; col < pQueryMsg->numOfCols; ++col) {
5107 5108
    SColumnInfo *pColInfo = &pQueryMsg->colList[col];

H
hjxilinx 已提交
5109
    pColInfo->colId = htons(pColInfo->colId);
5110
    pColInfo->type = htons(pColInfo->type);
H
hjxilinx 已提交
5111 5112
    pColInfo->bytes = htons(pColInfo->bytes);
    pColInfo->numOfFilters = htons(pColInfo->numOfFilters);
5113

H
hjxilinx 已提交
5114
    assert(pColInfo->type >= TSDB_DATA_TYPE_BOOL && pColInfo->type <= TSDB_DATA_TYPE_NCHAR);
5115

H
hjxilinx 已提交
5116
    int32_t numOfFilters = pColInfo->numOfFilters;
5117
    if (numOfFilters > 0) {
H
hjxilinx 已提交
5118
      pColInfo->filters = calloc(numOfFilters, sizeof(SColumnFilterInfo));
5119 5120 5121
    }

    for (int32_t f = 0; f < numOfFilters; ++f) {
5122 5123 5124 5125
      SColumnFilterInfo *pFilterMsg = (SColumnFilterInfo *)pMsg;
      
      SColumnFilterInfo *pColFilter = &pColInfo->filters[f];
      pColFilter->filterstr = htons(pFilterMsg->filterstr);
5126 5127 5128

      pMsg += sizeof(SColumnFilterInfo);

5129 5130
      if (pColFilter->filterstr) {
        pColFilter->len = htobe64(pFilterMsg->len);
5131

5132
        pColFilter->pz = (int64_t) calloc(1, pColFilter->len + 1 * TSDB_NCHAR_SIZE); // note: null-terminator
5133 5134
        memcpy((void *)pColFilter->pz, pMsg, pColFilter->len);
        pMsg += (pColFilter->len + 1);
5135
      } else {
5136 5137
        pColFilter->lowerBndi = htobe64(pFilterMsg->lowerBndi);
        pColFilter->upperBndi = htobe64(pFilterMsg->upperBndi);
5138 5139
      }

5140 5141
      pColFilter->lowerRelOptr = htons(pFilterMsg->lowerRelOptr);
      pColFilter->upperRelOptr = htons(pFilterMsg->upperRelOptr);
5142 5143 5144
    }
  }

5145 5146
  *pExpr = calloc(pQueryMsg->numOfOutput, POINTER_BYTES);
  SSqlFuncMsg *pExprMsg = (SSqlFuncMsg *)pMsg;
5147

5148
  for (int32_t i = 0; i < pQueryMsg->numOfOutput; ++i) {
5149
    (*pExpr)[i] = pExprMsg;
5150

5151
    pExprMsg->colInfo.colIndex = htons(pExprMsg->colInfo.colIndex);
5152 5153 5154 5155
    pExprMsg->colInfo.colId = htons(pExprMsg->colInfo.colId);
    pExprMsg->colInfo.flag = htons(pExprMsg->colInfo.flag);
    pExprMsg->functionId = htons(pExprMsg->functionId);
    pExprMsg->numOfParams = htons(pExprMsg->numOfParams);
5156

5157
    pMsg += sizeof(SSqlFuncMsg);
5158 5159

    for (int32_t j = 0; j < pExprMsg->numOfParams; ++j) {
5160
      pExprMsg->arg[j].argType = htons(pExprMsg->arg[j].argType);
5161 5162 5163 5164
      pExprMsg->arg[j].argBytes = htons(pExprMsg->arg[j].argBytes);

      if (pExprMsg->arg[j].argType == TSDB_DATA_TYPE_BINARY) {
        pExprMsg->arg[j].argValue.pz = pMsg;
5165
        pMsg += pExprMsg->arg[j].argBytes;  // one more for the string terminated char.
5166 5167 5168 5169 5170
      } else {
        pExprMsg->arg[j].argValue.i64 = htobe64(pExprMsg->arg[j].argValue.i64);
      }
    }

H
Haojun Liao 已提交
5171 5172
    int16_t functionId = pExprMsg->functionId;
    if (functionId == TSDB_FUNC_TAG || functionId == TSDB_FUNC_TAGPRJ || functionId == TSDB_FUNC_TAG_DUMMY) {
5173
      if (pExprMsg->colInfo.flag != TSDB_COL_TAG) {  // ignore the column  index check for arithmetic expression.
5174 5175
        code = TSDB_CODE_QRY_INVALID_MSG;
        goto _cleanup;
5176 5177
      }
    } else {
5178
//      if (!validateExprColumnInfo(pQueryMsg, pExprMsg)) {
5179
//        return TSDB_CODE_QRY_INVALID_MSG;
5180
//      }
5181 5182
    }

5183
    pExprMsg = (SSqlFuncMsg *)pMsg;
5184
  }
5185

5186
  if (!validateQuerySourceCols(pQueryMsg, *pExpr)) {
5187
    code = TSDB_CODE_QRY_INVALID_MSG;
dengyihao's avatar
dengyihao 已提交
5188
    goto _cleanup;
5189
  }
5190

H
hjxilinx 已提交
5191
  pMsg = createTableIdList(pQueryMsg, pMsg, pTableIdList);
5192

H
hjxilinx 已提交
5193
  if (pQueryMsg->numOfGroupCols > 0) {  // group by tag columns
5194
    *groupbyCols = malloc(pQueryMsg->numOfGroupCols * sizeof(SColIndex));
5195 5196 5197 5198
    if (*groupbyCols == NULL) {
      code = TSDB_CODE_QRY_OUT_OF_MEMORY;
      goto _cleanup;
    }
5199 5200 5201

    for (int32_t i = 0; i < pQueryMsg->numOfGroupCols; ++i) {
      (*groupbyCols)[i].colId = *(int16_t *)pMsg;
5202
      pMsg += sizeof((*groupbyCols)[i].colId);
5203 5204

      (*groupbyCols)[i].colIndex = *(int16_t *)pMsg;
5205 5206
      pMsg += sizeof((*groupbyCols)[i].colIndex);

5207
      (*groupbyCols)[i].flag = *(int16_t *)pMsg;
5208 5209 5210 5211 5212
      pMsg += sizeof((*groupbyCols)[i].flag);

      memcpy((*groupbyCols)[i].name, pMsg, tListLen(groupbyCols[i]->name));
      pMsg += tListLen((*groupbyCols)[i].name);
    }
5213

H
hjxilinx 已提交
5214 5215
    pQueryMsg->orderByIdx = htons(pQueryMsg->orderByIdx);
    pQueryMsg->orderType = htons(pQueryMsg->orderType);
5216 5217
  }

5218 5219
  pQueryMsg->fillType = htons(pQueryMsg->fillType);
  if (pQueryMsg->fillType != TSDB_FILL_NONE) {
5220
    pQueryMsg->fillVal = (uint64_t)(pMsg);
5221 5222

    int64_t *v = (int64_t *)pMsg;
5223
    for (int32_t i = 0; i < pQueryMsg->numOfOutput; ++i) {
5224 5225
      v[i] = htobe64(v[i]);
    }
5226

5227
    pMsg += sizeof(int64_t) * pQueryMsg->numOfOutput;
5228
  }
5229

5230 5231 5232 5233
  if (pQueryMsg->numOfTags > 0) {
    (*tagCols) = calloc(1, sizeof(SColumnInfo) * pQueryMsg->numOfTags);
    for (int32_t i = 0; i < pQueryMsg->numOfTags; ++i) {
      SColumnInfo* pTagCol = (SColumnInfo*) pMsg;
5234

5235 5236 5237 5238
      pTagCol->colId = htons(pTagCol->colId);
      pTagCol->bytes = htons(pTagCol->bytes);
      pTagCol->type  = htons(pTagCol->type);
      pTagCol->numOfFilters = 0;
5239

5240
      (*tagCols)[i] = *pTagCol;
5241
      pMsg += sizeof(SColumnInfo);
5242
    }
H
hjxilinx 已提交
5243
  }
5244

5245 5246 5247 5248 5249 5250
  // 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;
  }
5251

weixin_48148422's avatar
weixin_48148422 已提交
5252
  if (*pMsg != 0) {
5253
    size_t len = strlen(pMsg) + 1;
5254

5255
    *tbnameCond = malloc(len);
5256 5257 5258 5259 5260
    if (*tbnameCond == NULL) {
      code = TSDB_CODE_QRY_OUT_OF_MEMORY;
      goto _cleanup;
    }

weixin_48148422's avatar
weixin_48148422 已提交
5261
    strcpy(*tbnameCond, pMsg);
5262
    pMsg += len;
weixin_48148422's avatar
weixin_48148422 已提交
5263
  }
5264

5265
  qDebug("qmsg:%p query %d tables, type:%d, qrange:%" PRId64 "-%" PRId64 ", numOfGroupbyTagCols:%d, order:%d, "
H
Haojun Liao 已提交
5266 5267
         "outputCols:%d, numOfCols:%d, interval:%" PRId64 ", fillType:%d, comptsLen:%d, compNumOfBlocks:%d, limit:%" PRId64 ", offset:%" PRId64,
         pQueryMsg, pQueryMsg->numOfTables, pQueryMsg->queryType, pQueryMsg->window.skey, pQueryMsg->window.ekey, pQueryMsg->numOfGroupCols,
5268
         pQueryMsg->order, pQueryMsg->numOfOutput, pQueryMsg->numOfCols, pQueryMsg->intervalTime,
H
Haojun Liao 已提交
5269
         pQueryMsg->fillType, pQueryMsg->tsLen, pQueryMsg->tsNumOfBlocks, pQueryMsg->limit, pQueryMsg->offset);
5270 5271

  return TSDB_CODE_SUCCESS;
dengyihao's avatar
dengyihao 已提交
5272 5273 5274 5275 5276 5277 5278 5279 5280

_cleanup:
  tfree(*pExpr);
  taosArrayDestroy(*pTableIdList);
  *pTableIdList = NULL;
  tfree(*tbnameCond);
  tfree(*groupbyCols);
  tfree(*tagCols);
  tfree(*tagCond);
5281 5282

  return code;
5283 5284
}

H
hjxilinx 已提交
5285
static int32_t buildAirthmeticExprFromMsg(SExprInfo *pArithExprInfo, SQueryTableMsg *pQueryMsg) {
5286
  qDebug("qmsg:%p create arithmetic expr from binary string: %s", pQueryMsg, pArithExprInfo->base.arg[0].argValue.pz);
weixin_48148422's avatar
weixin_48148422 已提交
5287 5288 5289 5290 5291 5292 5293 5294 5295

  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 已提交
5296
  if (pExprNode == NULL) {
5297
    qError("qmsg:%p failed to create arithmetic expression string from:%s", pQueryMsg, pArithExprInfo->base.arg[0].argValue.pz);
5298
    return TSDB_CODE_QRY_APP_ERROR;
5299
  }
5300

5301
  pArithExprInfo->pExpr = pExprNode;
5302 5303 5304
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
5305
static int32_t createQFunctionExprFromMsg(SQueryTableMsg *pQueryMsg, SExprInfo **pExprInfo, SSqlFuncMsg **pExprMsg,
5306 5307
    SColumnInfo* pTagCols) {
  *pExprInfo = NULL;
H
hjxilinx 已提交
5308
  int32_t code = TSDB_CODE_SUCCESS;
5309

H
Haojun Liao 已提交
5310
  SExprInfo *pExprs = (SExprInfo *)calloc(pQueryMsg->numOfOutput, sizeof(SExprInfo));
5311
  if (pExprs == NULL) {
5312
    return TSDB_CODE_QRY_OUT_OF_MEMORY;
5313 5314 5315 5316 5317
  }

  bool    isSuperTable = QUERY_IS_STABLE_QUERY(pQueryMsg->queryType);
  int16_t tagLen = 0;

5318
  for (int32_t i = 0; i < pQueryMsg->numOfOutput; ++i) {
5319
    pExprs[i].base = *pExprMsg[i];
5320
    pExprs[i].bytes = 0;
5321 5322 5323 5324

    int16_t type = 0;
    int16_t bytes = 0;

5325
    // parse the arithmetic expression
5326
    if (pExprs[i].base.functionId == TSDB_FUNC_ARITHM) {
5327
      code = buildAirthmeticExprFromMsg(&pExprs[i], pQueryMsg);
5328

5329 5330 5331
      if (code != TSDB_CODE_SUCCESS) {
        tfree(pExprs);
        return code;
5332 5333
      }

5334
      type  = TSDB_DATA_TYPE_DOUBLE;
5335
      bytes = tDataTypeDesc[type].nSize;
H
Haojun Liao 已提交
5336
    } else if (pExprs[i].base.colInfo.colId == TSDB_TBNAME_COLUMN_INDEX && pExprs[i].base.functionId == TSDB_FUNC_TAGPRJ) {  // parse the normal column
H
Haojun Liao 已提交
5337 5338 5339
      SSchema s = tGetTableNameColumnSchema();
      type  = s.type;
      bytes = s.bytes;
B
Bomin Zhang 已提交
5340
    } else{
5341
      int32_t j = getColumnIndexInSource(pQueryMsg, &pExprs[i].base, pTagCols);
dengyihao's avatar
dengyihao 已提交
5342
      assert(j < pQueryMsg->numOfCols || j < pQueryMsg->numOfTags);
H
Haojun Liao 已提交
5343

dengyihao's avatar
dengyihao 已提交
5344
      if (pExprs[i].base.colInfo.colId != TSDB_TBNAME_COLUMN_INDEX && j >= 0) {
H
Haojun Liao 已提交
5345 5346 5347 5348
        SColumnInfo* pCol = (TSDB_COL_IS_TAG(pExprs[i].base.colInfo.flag))? &pTagCols[j]:&pQueryMsg->colList[j];
        type = pCol->type;
        bytes = pCol->bytes;
      } else {
H
Haojun Liao 已提交
5349
        SSchema s = tGetTableNameColumnSchema();
H
hjxilinx 已提交
5350

H
Haojun Liao 已提交
5351 5352 5353
        type  = s.type;
        bytes = s.bytes;
      }
5354 5355
    }

5356 5357
    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,
5358
                          &pExprs[i].interBytes, 0, isSuperTable) != TSDB_CODE_SUCCESS) {
5359
      tfree(pExprs);
5360
      return TSDB_CODE_QRY_INVALID_MSG;
5361 5362
    }

5363
    if (pExprs[i].base.functionId == TSDB_FUNC_TAG_DUMMY || pExprs[i].base.functionId == TSDB_FUNC_TS_DUMMY) {
5364
      tagLen += pExprs[i].bytes;
5365
    }
5366
    assert(isValidDataType(pExprs[i].type));
5367 5368 5369
  }

  // TODO refactor
5370
  for (int32_t i = 0; i < pQueryMsg->numOfOutput; ++i) {
5371 5372
    pExprs[i].base = *pExprMsg[i];
    int16_t functId = pExprs[i].base.functionId;
5373

5374
    if (functId == TSDB_FUNC_TOP || functId == TSDB_FUNC_BOTTOM) {
5375
      int32_t j = getColumnIndexInSource(pQueryMsg, &pExprs[i].base, pTagCols);
5376 5377 5378 5379 5380
      assert(j < pQueryMsg->numOfCols);

      SColumnInfo *pCol = &pQueryMsg->colList[j];

      int32_t ret =
5381
          getResultDataInfo(pCol->type, pCol->bytes, functId, pExprs[i].base.arg[0].argValue.i64,
5382
                            &pExprs[i].type, &pExprs[i].bytes, &pExprs[i].interBytes, tagLen, isSuperTable);
5383 5384 5385
      assert(ret == TSDB_CODE_SUCCESS);
    }
  }
5386
  *pExprInfo = pExprs;
5387 5388 5389 5390

  return TSDB_CODE_SUCCESS;
}

5391
static SSqlGroupbyExpr *createGroupbyExprFromMsg(SQueryTableMsg *pQueryMsg, SColIndex *pColIndex, int32_t *code) {
5392 5393 5394 5395 5396
  if (pQueryMsg->numOfGroupCols == 0) {
    return NULL;
  }

  // using group by tag columns
5397
  SSqlGroupbyExpr *pGroupbyExpr = (SSqlGroupbyExpr *)calloc(1, sizeof(SSqlGroupbyExpr));
5398
  if (pGroupbyExpr == NULL) {
5399
    *code = TSDB_CODE_QRY_OUT_OF_MEMORY;
5400 5401 5402 5403 5404 5405 5406
    return NULL;
  }

  pGroupbyExpr->numOfGroupCols = pQueryMsg->numOfGroupCols;
  pGroupbyExpr->orderType = pQueryMsg->orderType;
  pGroupbyExpr->orderIndex = pQueryMsg->orderByIdx;

5407 5408 5409 5410
  pGroupbyExpr->columnInfo = taosArrayInit(pQueryMsg->numOfGroupCols, sizeof(SColIndex));
  for(int32_t i = 0; i < pQueryMsg->numOfGroupCols; ++i) {
    taosArrayPush(pGroupbyExpr->columnInfo, &pColIndex[i]);
  }
5411

5412 5413 5414
  return pGroupbyExpr;
}

5415
static int32_t createFilterInfo(void *pQInfo, SQuery *pQuery) {
5416
  for (int32_t i = 0; i < pQuery->numOfCols; ++i) {
5417
    if (pQuery->colList[i].numOfFilters > 0) {
5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428
      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) {
5429
    if (pQuery->colList[i].numOfFilters > 0) {
5430 5431
      SSingleColumnFilterInfo *pFilterInfo = &pQuery->pFilterInfo[j];

B
Bomin Zhang 已提交
5432
      memcpy(&pFilterInfo->info, &pQuery->colList[i], sizeof(SColumnInfo));
5433
      pFilterInfo->info = pQuery->colList[i];
5434

5435
      pFilterInfo->numOfFilters = pQuery->colList[i].numOfFilters;
5436 5437 5438 5439
      pFilterInfo->pFilters = calloc(pFilterInfo->numOfFilters, sizeof(SColumnFilterElem));

      for (int32_t f = 0; f < pFilterInfo->numOfFilters; ++f) {
        SColumnFilterElem *pSingleColFilter = &pFilterInfo->pFilters[f];
5440
        pSingleColFilter->filterInfo = pQuery->colList[i].filters[f];
5441 5442 5443 5444 5445

        int32_t lower = pSingleColFilter->filterInfo.lowerRelOptr;
        int32_t upper = pSingleColFilter->filterInfo.upperRelOptr;

        if (lower == TSDB_RELATION_INVALID && upper == TSDB_RELATION_INVALID) {
S
slguan 已提交
5446
          qError("QInfo:%p invalid filter info", pQInfo);
5447
          return TSDB_CODE_QRY_INVALID_MSG;
5448 5449
        }

5450 5451
        int16_t type  = pQuery->colList[i].type;
        int16_t bytes = pQuery->colList[i].bytes;
5452

5453 5454 5455
        // todo refactor
        __filter_func_t *rangeFilterArray = getRangeFilterFuncArray(type);
        __filter_func_t *filterArray = getValueFilterFuncArray(type);
5456 5457

        if (rangeFilterArray == NULL && filterArray == NULL) {
S
slguan 已提交
5458
          qError("QInfo:%p failed to get filter function, invalid data type:%d", pQInfo, type);
5459
          return TSDB_CODE_QRY_INVALID_MSG;
5460 5461
        }

5462
        if ((lower == TSDB_RELATION_GREATER_EQUAL || lower == TSDB_RELATION_GREATER) &&
5463
            (upper == TSDB_RELATION_LESS_EQUAL || upper == TSDB_RELATION_LESS)) {
dengyihao's avatar
dengyihao 已提交
5464
          assert(rangeFilterArray != NULL);
5465
          if (lower == TSDB_RELATION_GREATER_EQUAL) {
5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478
            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
dengyihao's avatar
dengyihao 已提交
5479
          assert(filterArray != NULL);
5480 5481 5482 5483
          if (lower != TSDB_RELATION_INVALID) {
            pSingleColFilter->fp = filterArray[lower];

            if (upper != TSDB_RELATION_INVALID) {
dengyihao's avatar
dengyihao 已提交
5484
              qError("pQInfo:%p failed to get filter function, invalid filter condition: %d", pQInfo, type);
5485
              return TSDB_CODE_QRY_INVALID_MSG;
5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501
            }
          } else {
            pSingleColFilter->fp = filterArray[upper];
          }
        }
        assert(pSingleColFilter->fp != NULL);
        pSingleColFilter->bytes = bytes;
      }

      j++;
    }
  }

  return TSDB_CODE_SUCCESS;
}

5502
static void doUpdateExprColumnIndex(SQuery *pQuery) {
5503
  assert(pQuery->pSelectExpr != NULL && pQuery != NULL);
5504

5505
  for (int32_t k = 0; k < pQuery->numOfOutput; ++k) {
5506
    SSqlFuncMsg *pSqlExprMsg = &pQuery->pSelectExpr[k].base;
5507
    if (pSqlExprMsg->functionId == TSDB_FUNC_ARITHM) {
5508 5509
      continue;
    }
5510

5511
    // todo opt performance
H
Haojun Liao 已提交
5512 5513
    SColIndex *pColIndex = &pSqlExprMsg->colInfo;
    if (!TSDB_COL_IS_TAG(pColIndex->flag)) {
5514 5515
      int32_t f = 0;
      for (f = 0; f < pQuery->numOfCols; ++f) {
H
Haojun Liao 已提交
5516 5517
        if (pColIndex->colId == pQuery->colList[f].colId) {
          pColIndex->colIndex = f;
5518 5519 5520
          break;
        }
      }
5521 5522
      
      assert (f < pQuery->numOfCols);
5523
    } else {
5524 5525
      int32_t f = 0;
      for (f = 0; f < pQuery->numOfTags; ++f) {
H
Haojun Liao 已提交
5526 5527
        if (pColIndex->colId == pQuery->tagColList[f].colId) {
          pColIndex->colIndex = f;
5528 5529
          break;
        }
5530
      }
5531 5532
      
      assert(f < pQuery->numOfTags || pColIndex->colId == TSDB_TBNAME_COLUMN_INDEX);
5533 5534 5535 5536
    }
  }
}

weixin_48148422's avatar
weixin_48148422 已提交
5537

5538
static int compareTableIdInfo(const void* a, const void* b) {
weixin_48148422's avatar
weixin_48148422 已提交
5539 5540 5541 5542 5543 5544 5545
  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;
}

dengyihao's avatar
dengyihao 已提交
5546 5547
static void freeQInfo(SQInfo *pQInfo);

weixin_48148422's avatar
weixin_48148422 已提交
5548
static SQInfo *createQInfoImpl(SQueryTableMsg *pQueryMsg, SArray* pTableIdList, SSqlGroupbyExpr *pGroupbyExpr, SExprInfo *pExprs,
5549
                               STableGroupInfo *pTableGroupInfo, SColumnInfo* pTagCols) {
5550 5551
  SQInfo *pQInfo = (SQInfo *)calloc(1, sizeof(SQInfo));
  if (pQInfo == NULL) {
5552
    return NULL;
5553 5554 5555 5556 5557 5558
  }

  SQuery *pQuery = calloc(1, sizeof(SQuery));
  pQInfo->runtimeEnv.pQuery = pQuery;

  int16_t numOfCols = pQueryMsg->numOfCols;
5559
  int16_t numOfOutput = pQueryMsg->numOfOutput;
5560

5561
  pQuery->numOfCols       = numOfCols;
H
hjxilinx 已提交
5562
  pQuery->numOfOutput     = numOfOutput;
5563 5564 5565
  pQuery->limit.limit     = pQueryMsg->limit;
  pQuery->limit.offset    = pQueryMsg->offset;
  pQuery->order.order     = pQueryMsg->order;
5566
  pQuery->order.orderColId = pQueryMsg->orderColId;
5567 5568 5569 5570
  pQuery->pSelectExpr     = pExprs;
  pQuery->pGroupbyExpr    = pGroupbyExpr;
  pQuery->intervalTime    = pQueryMsg->intervalTime;
  pQuery->slidingTime     = pQueryMsg->slidingTime;
5571
  pQuery->slidingTimeUnit = pQueryMsg->slidingTimeUnit;
5572
  pQuery->fillType        = pQueryMsg->fillType;
5573
  pQuery->numOfTags       = pQueryMsg->numOfTags;
5574
  
5575
  // todo do not allocate ??
5576
  pQuery->colList = calloc(numOfCols, sizeof(SSingleColumnFilterInfo));
5577
  if (pQuery->colList == NULL) {
5578
    goto _cleanup;
5579
  }
5580

H
hjxilinx 已提交
5581
  for (int16_t i = 0; i < numOfCols; ++i) {
5582
    pQuery->colList[i] = pQueryMsg->colList[i];
5583
    pQuery->colList[i].filters = tscFilterInfoClone(pQueryMsg->colList[i].filters, pQuery->colList[i].numOfFilters);
H
hjxilinx 已提交
5584
  }
5585

5586
  pQuery->tagColList = pTagCols;
5587

5588
  // calculate the result row size
5589 5590 5591
  for (int16_t col = 0; col < numOfOutput; ++col) {
    assert(pExprs[col].bytes > 0);
    pQuery->rowSize += pExprs[col].bytes;
5592
  }
5593

5594
  doUpdateExprColumnIndex(pQuery);
5595

5596
  int32_t ret = createFilterInfo(pQInfo, pQuery);
5597
  if (ret != TSDB_CODE_SUCCESS) {
5598
    goto _cleanup;
5599 5600 5601
  }

  // prepare the result buffer
5602
  pQuery->sdata = (tFilePage **)calloc(pQuery->numOfOutput, POINTER_BYTES);
5603
  if (pQuery->sdata == NULL) {
5604
    goto _cleanup;
5605 5606
  }

H
hjxilinx 已提交
5607
  // set the output buffer capacity
H
hjxilinx 已提交
5608
  pQuery->rec.capacity = 4096;
5609
  pQuery->rec.threshold = 4000;
5610

5611
  for (int32_t col = 0; col < pQuery->numOfOutput; ++col) {
5612
    assert(pExprs[col].interBytes >= pExprs[col].bytes);
5613 5614

    // allocate additional memory for interResults that are usually larger then final results
5615 5616
    size_t size = (pQuery->rec.capacity + 1) * pExprs[col].bytes + pExprs[col].interBytes + sizeof(tFilePage);
    pQuery->sdata[col] = (tFilePage *)calloc(1, size);
5617
    if (pQuery->sdata[col] == NULL) {
5618
      goto _cleanup;
5619 5620 5621
    }
  }

5622
  if (pQuery->fillType != TSDB_FILL_NONE) {
5623 5624
    pQuery->fillVal = malloc(sizeof(int64_t) * pQuery->numOfOutput);
    if (pQuery->fillVal == NULL) {
5625
      goto _cleanup;
5626 5627 5628
    }

    // the first column is the timestamp
5629
    memcpy(pQuery->fillVal, (char *)pQueryMsg->fillVal, pQuery->numOfOutput * sizeof(int64_t));
5630 5631 5632
  }

  // to make sure third party won't overwrite this structure
5633
  pQInfo->signature = pQInfo;
5634

5635
  pQInfo->tableGroupInfo = *pTableGroupInfo;
dengyihao's avatar
dengyihao 已提交
5636 5637 5638 5639 5640 5641
  size_t numOfGroups = 0;
  if (pTableGroupInfo->pGroupList != NULL) {
    numOfGroups = taosArrayGetSize(pTableGroupInfo->pGroupList);

    pQInfo->tableqinfoGroupInfo.pGroupList = taosArrayInit(numOfGroups, POINTER_BYTES);
    pQInfo->tableqinfoGroupInfo.numOfTables = pTableGroupInfo->numOfTables;
H
Haojun Liao 已提交
5642 5643 5644
    pQInfo->tableqinfoGroupInfo.map = taosHashInit(pTableGroupInfo->numOfTables,
                                                   taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), false);
  }
5645

weixin_48148422's avatar
weixin_48148422 已提交
5646 5647
  int tableIndex = 0;
  STimeWindow window = pQueryMsg->window;
5648
  taosArraySort(pTableIdList, compareTableIdInfo);
5649

H
hjxilinx 已提交
5650
  for(int32_t i = 0; i < numOfGroups; ++i) {
5651
    SArray* pa = taosArrayGetP(pTableGroupInfo->pGroupList, i);
H
hjxilinx 已提交
5652
    size_t s = taosArrayGetSize(pa);
5653

5654
    SArray* p1 = taosArrayInit(s, POINTER_BYTES);
5655

H
hjxilinx 已提交
5656
    for(int32_t j = 0; j < s; ++j) {
5657 5658
      void* pTable = taosArrayGetP(pa, j);

weixin_48148422's avatar
weixin_48148422 已提交
5659
      // NOTE: compare STableIdInfo with STableId
5660 5661
      STableId id = tsdbGetTableId(pTable);
      STableIdInfo* pTableId = taosArraySearch(pTableIdList, &id, compareTableIdInfo);
weixin_48148422's avatar
weixin_48148422 已提交
5662 5663 5664
      if (pTableId != NULL ) {
        window.skey = pTableId->key;
      } else {
B
Bomin Zhang 已提交
5665
        window.skey = pQueryMsg->window.skey;
weixin_48148422's avatar
weixin_48148422 已提交
5666
      }
5667 5668 5669

      STableQueryInfo* item = createTableQueryInfo(&pQInfo->runtimeEnv, pTable, window);
      item->groupIndex = i;
H
hjxilinx 已提交
5670
      taosArrayPush(p1, &item);
H
Haojun Liao 已提交
5671
      taosHashPut(pQInfo->tableqinfoGroupInfo.map, &id.tid, sizeof(id.tid), &item, POINTER_BYTES);
H
hjxilinx 已提交
5672
    }
5673

5674
    taosArrayPush(pQInfo->tableqinfoGroupInfo.pGroupList, &p1);
H
hjxilinx 已提交
5675
  }
5676

weixin_48148422's avatar
weixin_48148422 已提交
5677 5678
  pQInfo->arrTableIdInfo = taosArrayInit(tableIndex, sizeof(STableIdInfo));

5679
  pQuery->pos = -1;
5680
  pQuery->window = pQueryMsg->window;
5681

5682
  if (sem_init(&pQInfo->dataReady, 0, 0) != 0) {
5683 5684
    int32_t code = TAOS_SYSTEM_ERROR(errno);
    qError("QInfo:%p init dataReady sem failed, reason:%s", pQInfo, tstrerror(code));
5685
    goto _cleanup;
5686
  }
5687

5688
  colIdCheck(pQuery);
5689

5690
  qDebug("qmsg:%p QInfo:%p created", pQueryMsg, pQInfo);
5691 5692
  return pQInfo;

5693
_cleanup:
dengyihao's avatar
dengyihao 已提交
5694
  freeQInfo(pQInfo);
5695 5696 5697
  return NULL;
}

H
hjxilinx 已提交
5698
static bool isValidQInfo(void *param) {
H
hjxilinx 已提交
5699 5700 5701 5702
  SQInfo *pQInfo = (SQInfo *)param;
  if (pQInfo == NULL) {
    return false;
  }
5703

H
hjxilinx 已提交
5704 5705 5706 5707
  /*
   * pQInfo->signature may be changed by another thread, so we assign value of signature
   * into local variable, then compare by using local variable
   */
5708
  uint64_t sig = (uint64_t)pQInfo->signature;
H
hjxilinx 已提交
5709 5710 5711
  return (sig == (uint64_t)pQInfo);
}

H
Haojun Liao 已提交
5712
static int32_t initQInfo(SQueryTableMsg *pQueryMsg, void *tsdb, int32_t vgId, SQInfo *pQInfo, bool isSTable, void* param, _qinfo_free_fn_t fn) {
H
hjxilinx 已提交
5713
  int32_t code = TSDB_CODE_SUCCESS;
5714
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
5715

H
hjxilinx 已提交
5716 5717
  STSBuf *pTSBuf = NULL;
  if (pQueryMsg->tsLen > 0) {  // open new file to save the result
H
Haojun Liao 已提交
5718
    char *tsBlock = (char *) pQueryMsg + pQueryMsg->tsOffset;
H
hjxilinx 已提交
5719
    pTSBuf = tsBufCreateFromCompBlocks(tsBlock, pQueryMsg->tsNumOfBlocks, pQueryMsg->tsLen, pQueryMsg->tsOrder);
5720

H
hjxilinx 已提交
5721
    tsBufResetPos(pTSBuf);
dengyihao's avatar
dengyihao 已提交
5722 5723
    bool ret = tsBufNextPos(pTSBuf);
    UNUSED(ret);
H
hjxilinx 已提交
5724
  }
5725

5726 5727
  if ((QUERY_IS_ASC_QUERY(pQuery) && (pQuery->window.skey > pQuery->window.ekey)) ||
      (!QUERY_IS_ASC_QUERY(pQuery) && (pQuery->window.ekey > pQuery->window.skey))) {
5728
    qDebug("QInfo:%p no result in time range %" PRId64 "-%" PRId64 ", order %d", pQInfo, pQuery->window.skey,
5729
           pQuery->window.ekey, pQuery->order.order);
5730
    setQueryStatus(pQuery, QUERY_COMPLETED);
5731

5732 5733 5734
    sem_post(&pQInfo->dataReady);
    return TSDB_CODE_SUCCESS;
  }
5735

5736 5737 5738
  pQInfo->param = param;
  pQInfo->freeFn = fn;

5739
  if (pQInfo->tableqinfoGroupInfo.numOfTables == 0) {
5740
    qDebug("QInfo:%p no table qualified for tag filter, abort query", pQInfo);
5741 5742 5743 5744 5745
    setQueryStatus(pQuery, QUERY_COMPLETED);
  
    sem_post(&pQInfo->dataReady);
    return TSDB_CODE_SUCCESS;
  }
H
hjxilinx 已提交
5746 5747

  // filter the qualified
5748
  if ((code = doInitQInfo(pQInfo, pTSBuf, tsdb, vgId, isSTable)) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
5749 5750
    goto _error;
  }
H
hjxilinx 已提交
5751
  
H
hjxilinx 已提交
5752 5753 5754 5755
  return code;

_error:
  // table query ref will be decrease during error handling
5756
  freeQInfo(pQInfo);
H
hjxilinx 已提交
5757 5758 5759 5760 5761 5762 5763
  return code;
}

static void freeQInfo(SQInfo *pQInfo) {
  if (!isValidQInfo(pQInfo)) {
    return;
  }
5764 5765

  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
H
hjxilinx 已提交
5766
  setQueryKilled(pQInfo);
5767

5768
  qDebug("QInfo:%p start to free QInfo", pQInfo);
5769
  for (int32_t col = 0; col < pQuery->numOfOutput; ++col) {
H
hjxilinx 已提交
5770 5771
    tfree(pQuery->sdata[col]);
  }
5772

H
hjxilinx 已提交
5773
  sem_destroy(&(pQInfo->dataReady));
5774
  teardownQueryRuntimeEnv(&pQInfo->runtimeEnv);
5775

H
hjxilinx 已提交
5776 5777 5778 5779 5780 5781
  for (int32_t i = 0; i < pQuery->numOfFilterCols; ++i) {
    SSingleColumnFilterInfo *pColFilter = &pQuery->pFilterInfo[i];
    if (pColFilter->numOfFilters > 0) {
      tfree(pColFilter->pFilters);
    }
  }
5782

H
hjxilinx 已提交
5783
  if (pQuery->pSelectExpr != NULL) {
5784
    for (int32_t i = 0; i < pQuery->numOfOutput; ++i) {
H
hjxilinx 已提交
5785
      SExprInfo* pExprInfo = &pQuery->pSelectExpr[i];
5786

H
hjxilinx 已提交
5787 5788 5789
      if (pExprInfo->pExpr != NULL) {
        tExprTreeDestroy(&pExprInfo->pExpr, NULL);
      }
H
hjxilinx 已提交
5790
    }
5791

H
hjxilinx 已提交
5792 5793
    tfree(pQuery->pSelectExpr);
  }
5794

5795 5796
  if (pQuery->fillVal != NULL) {
    tfree(pQuery->fillVal);
H
hjxilinx 已提交
5797
  }
5798

5799
  // todo refactor, extract method to destroytableDataInfo
H
Haojun Liao 已提交
5800
  int32_t numOfGroups = GET_NUM_OF_TABLEGROUP(pQInfo);
5801
  for (int32_t i = 0; i < numOfGroups; ++i) {
H
Haojun Liao 已提交
5802
    SArray *p = GET_TABLEGROUP(pQInfo, i);;
5803

5804 5805
    size_t num = taosArrayGetSize(p);
    for(int32_t j = 0; j < num; ++j) {
5806 5807 5808
      STableQueryInfo* item = taosArrayGetP(p, j);
      if (item != NULL) {
        destroyTableQueryInfo(item, pQuery->numOfOutput);
5809 5810
      }
    }
5811

H
hjxilinx 已提交
5812 5813
    taosArrayDestroy(p);
  }
5814

5815
  taosArrayDestroy(pQInfo->tableqinfoGroupInfo.pGroupList);
H
Haojun Liao 已提交
5816
  taosHashCleanup(pQInfo->tableqinfoGroupInfo.map);
5817
  tsdbDestoryTableGroup(&pQInfo->tableGroupInfo);
weixin_48148422's avatar
weixin_48148422 已提交
5818
  taosArrayDestroy(pQInfo->arrTableIdInfo);
H
hjxilinx 已提交
5819
  
5820 5821 5822 5823
  if (pQuery->pGroupbyExpr != NULL) {
    taosArrayDestroy(pQuery->pGroupbyExpr->columnInfo);
    tfree(pQuery->pGroupbyExpr);
  }
5824

5825 5826 5827 5828
  tfree(pQuery->tagColList);
  tfree(pQuery->pFilterInfo);
  tfree(pQuery->colList);
  tfree(pQuery->sdata);
5829

5830
  tfree(pQuery);
5831

5832
  qDebug("QInfo:%p QInfo is freed", pQInfo);
5833

5834
  // destroy signature, in order to avoid the query process pass the object safety check
H
hjxilinx 已提交
5835 5836 5837 5838
  memset(pQInfo, 0, sizeof(SQInfo));
  tfree(pQInfo);
}

H
hjxilinx 已提交
5839
static size_t getResultSize(SQInfo *pQInfo, int64_t *numOfRows) {
5840 5841
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;

H
hjxilinx 已提交
5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852
  /*
   * 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 已提交
5853
      qError("QInfo:%p failed to get file info, path:%s, reason:%s", pQInfo, pQuery->sdata[0]->data, strerror(errno));
H
hjxilinx 已提交
5854 5855 5856 5857
      return 0;
    }
  } else {
    return pQuery->rowSize * (*numOfRows);
5858
  }
H
hjxilinx 已提交
5859
}
5860

H
hjxilinx 已提交
5861 5862 5863
static int32_t doDumpQueryResult(SQInfo *pQInfo, char *data) {
  // the remained number of retrieved rows, not the interpolated result
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
5864

H
hjxilinx 已提交
5865 5866 5867
  // load data from file to msg buffer
  if (isTSCompQuery(pQuery)) {
    int32_t fd = open(pQuery->sdata[0]->data, O_RDONLY, 0666);
5868

H
hjxilinx 已提交
5869 5870
    // make sure file exist
    if (FD_VALID(fd)) {
dengyihao's avatar
dengyihao 已提交
5871 5872
      int32_t s = lseek(fd, 0, SEEK_END);
      UNUSED(s);
5873
      qDebug("QInfo:%p ts comp data return, file:%s, size:%d", pQInfo, pQuery->sdata[0]->data, s);
H
Haojun Liao 已提交
5874
      if (lseek(fd, 0, SEEK_SET) >= 0) {
dengyihao's avatar
dengyihao 已提交
5875 5876
        size_t sz = read(fd, data, s);
        UNUSED(sz);
H
Haojun Liao 已提交
5877 5878
      } else {
        // todo handle error
dengyihao's avatar
dengyihao 已提交
5879
      }
H
Haojun Liao 已提交
5880

H
hjxilinx 已提交
5881 5882 5883
      close(fd);
      unlink(pQuery->sdata[0]->data);
    } else {
dengyihao's avatar
dengyihao 已提交
5884
      // todo return the error code to client and handle invalid fd
S
slguan 已提交
5885
      qError("QInfo:%p failed to open tmp file to send ts-comp data to client, path:%s, reason:%s", pQInfo,
H
hjxilinx 已提交
5886
             pQuery->sdata[0]->data, strerror(errno));
dengyihao's avatar
dengyihao 已提交
5887 5888 5889
      if (fd != -1) {
        close(fd); 
      }
H
hjxilinx 已提交
5890
    }
5891

H
hjxilinx 已提交
5892 5893 5894 5895
    // all data returned, set query over
    if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
      setQueryStatus(pQuery, QUERY_OVER);
    }
H
hjxilinx 已提交
5896
  } else {
5897
    doCopyQueryResultToMsg(pQInfo, pQuery->rec.rows, data);
5898
  }
5899

5900
  pQuery->rec.total += pQuery->rec.rows;
5901
  qDebug("QInfo:%p current numOfRes rows:%" PRId64 ", total:%" PRId64, pQInfo, pQuery->rec.rows, pQuery->rec.total);
5902

5903
  if (pQuery->limit.limit > 0 && pQuery->limit.limit == pQuery->rec.total) {
5904
    qDebug("QInfo:%p results limitation reached, limitation:%"PRId64, pQInfo, pQuery->limit.limit);
5905 5906 5907
    setQueryStatus(pQuery, QUERY_OVER);
  }
  
H
hjxilinx 已提交
5908
  return TSDB_CODE_SUCCESS;
5909 5910
}

H
Haojun Liao 已提交
5911 5912
int32_t qCreateQueryInfo(void* tsdb, int32_t vgId, SQueryTableMsg* pQueryMsg, void* param, _qinfo_free_fn_t fn,
    qinfo_t* pQInfo) {
H
hjxilinx 已提交
5913
  assert(pQueryMsg != NULL);
5914 5915

  int32_t code = TSDB_CODE_SUCCESS;
5916

weixin_48148422's avatar
weixin_48148422 已提交
5917
  char *        tagCond = NULL, *tbnameCond = NULL;
5918
  SArray *      pTableIdList = NULL;
5919
  SSqlFuncMsg **pExprMsg = NULL;
5920 5921
  SColIndex *   pGroupColIndex = NULL;
  SColumnInfo*  pTagColumnInfo = NULL;
dengyihao's avatar
dengyihao 已提交
5922 5923
  SExprInfo     *pExprs = NULL;
  SSqlGroupbyExpr *pGroupbyExpr = NULL;
5924

weixin_48148422's avatar
weixin_48148422 已提交
5925
  if ((code = convertQueryMsg(pQueryMsg, &pTableIdList, &pExprMsg, &tagCond, &tbnameCond, &pGroupColIndex, &pTagColumnInfo)) !=
5926
         TSDB_CODE_SUCCESS) {
B
Bomin Zhang 已提交
5927
    goto _over;
5928 5929
  }

H
hjxilinx 已提交
5930
  if (pQueryMsg->numOfTables <= 0) {
S
slguan 已提交
5931
    qError("Invalid number of tables to query, numOfTables:%d", pQueryMsg->numOfTables);
5932
    code = TSDB_CODE_QRY_INVALID_MSG;
H
hjxilinx 已提交
5933
    goto _over;
5934 5935
  }

H
hjxilinx 已提交
5936
  if (pTableIdList == NULL || taosArrayGetSize(pTableIdList) == 0) {
S
slguan 已提交
5937
    qError("qmsg:%p, SQueryTableMsg wrong format", pQueryMsg);
5938
    code = TSDB_CODE_QRY_INVALID_MSG;
H
hjxilinx 已提交
5939
    goto _over;
5940 5941
  }

H
Haojun Liao 已提交
5942
  if ((code = createQFunctionExprFromMsg(pQueryMsg, &pExprs, pExprMsg, pTagColumnInfo)) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
5943
    goto _over;
5944 5945
  }

dengyihao's avatar
dengyihao 已提交
5946
  pGroupbyExpr = createGroupbyExprFromMsg(pQueryMsg, pGroupColIndex, &code);
H
hjxilinx 已提交
5947
  if ((pGroupbyExpr == NULL && pQueryMsg->numOfGroupCols != 0) || code != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
5948
    goto _over;
5949
  }
5950

H
hjxilinx 已提交
5951
  bool isSTableQuery = false;
5952
  STableGroupInfo tableGroupInfo = {0};
5953
  
H
Haojun Liao 已提交
5954
  if (TSDB_QUERY_HAS_TYPE(pQueryMsg->queryType, TSDB_QUERY_TYPE_TABLE_QUERY)) {
weixin_48148422's avatar
weixin_48148422 已提交
5955
    STableIdInfo *id = taosArrayGet(pTableIdList, 0);
H
Haojun Liao 已提交
5956

5957
    qDebug("qmsg:%p query normal table, uid:%"PRId64", tid:%d", pQueryMsg, id->uid, id->tid);
5958
    if ((code = tsdbGetOneTableGroup(tsdb, id->uid, &tableGroupInfo)) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
5959
      goto _over;
5960
    }
H
Haojun Liao 已提交
5961
  } else if (TSDB_QUERY_HAS_TYPE(pQueryMsg->queryType, TSDB_QUERY_TYPE_MULTITABLE_QUERY|TSDB_QUERY_TYPE_STABLE_QUERY)) {
5962
    isSTableQuery = true;
H
Haojun Liao 已提交
5963 5964 5965 5966
    // TODO: need a macro from TSDB to check if table is super table

    // also note there's possibility that only one table in the super table
    if (!TSDB_QUERY_HAS_TYPE(pQueryMsg->queryType, TSDB_QUERY_TYPE_MULTITABLE_QUERY)) {
weixin_48148422's avatar
weixin_48148422 已提交
5967 5968 5969 5970 5971 5972 5973 5974
      STableIdInfo *id = taosArrayGet(pTableIdList, 0);

      // 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;
      }
      
5975
      code = tsdbQuerySTableByTagCond(tsdb, id->uid, tagCond, pQueryMsg->tagCondLen, pQueryMsg->tagNameRelType, tbnameCond, &tableGroupInfo, pGroupColIndex,
weixin_48148422's avatar
weixin_48148422 已提交
5976
                                          numOfGroupByCols);
5977 5978 5979
      if (code != TSDB_CODE_SUCCESS) {
        goto _over;
      }
weixin_48148422's avatar
weixin_48148422 已提交
5980
    } else {
5981 5982 5983 5984
      code = tsdbGetTableGroupFromIdList(tsdb, pTableIdList, &tableGroupInfo);
      if (code != TSDB_CODE_SUCCESS) {
        goto _over;
      }
H
Haojun Liao 已提交
5985

5986
      qDebug("qmsg:%p query on %zu tables in one group from client", pQueryMsg, tableGroupInfo.numOfTables);
5987
    }
H
hjxilinx 已提交
5988
  } else {
5989
    assert(0);
5990
  }
5991

5992
  (*pQInfo) = createQInfoImpl(pQueryMsg, pTableIdList, pGroupbyExpr, pExprs, &tableGroupInfo, pTagColumnInfo);
dengyihao's avatar
dengyihao 已提交
5993 5994 5995 5996
  pExprs = NULL;
  pGroupbyExpr = NULL;
  pTagColumnInfo = NULL;
  
5997
  if ((*pQInfo) == NULL) {
5998
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
H
hjxilinx 已提交
5999
    goto _over;
6000
  }
6001

H
Haojun Liao 已提交
6002
  code = initQInfo(pQueryMsg, tsdb, vgId, *pQInfo, isSTableQuery, param, fn);
6003

H
hjxilinx 已提交
6004
_over:
dengyihao's avatar
dengyihao 已提交
6005 6006 6007
  free(tagCond);
  free(tbnameCond);
  free(pGroupColIndex);
dengyihao's avatar
dengyihao 已提交
6008 6009
  if (pGroupbyExpr != NULL) {
    taosArrayDestroy(pGroupbyExpr->columnInfo);
dengyihao's avatar
dengyihao 已提交
6010
    free(pGroupbyExpr);
dengyihao's avatar
dengyihao 已提交
6011
  } 
dengyihao's avatar
dengyihao 已提交
6012 6013
  free(pTagColumnInfo);
  free(pExprs);
dengyihao's avatar
dengyihao 已提交
6014
  free(pExprMsg);
H
hjxilinx 已提交
6015
  taosArrayDestroy(pTableIdList);
6016

H
Haojun Liao 已提交
6017
  //pQInfo already freed in initQInfo, but *pQInfo may not pointer to null;
6018 6019
  if (code != TSDB_CODE_SUCCESS) {
    *pQInfo = NULL;
H
Haojun Liao 已提交
6020 6021 6022 6023 6024
  } else {
    SQInfo* pq = (SQInfo*) (*pQInfo);

    T_REF_INC(pq);
    T_REF_INC(pq);
6025 6026
  }

6027
  // if failed to add ref for all meters in this query, abort current query
6028
  return code;
H
hjxilinx 已提交
6029 6030
}

H
Haojun Liao 已提交
6031 6032
static void doDestoryQueryInfo(SQInfo* pQInfo) {
  assert(pQInfo != NULL);
6033
  qDebug("QInfo:%p query completed", pQInfo);
H
Haojun Liao 已提交
6034
  queryCostStatis(pQInfo);   // print the query cost summary
6035 6036 6037
  freeQInfo(pQInfo);
}

H
Haojun Liao 已提交
6038
void qDestroyQueryInfo(qinfo_t qHandle) {
H
Haojun Liao 已提交
6039 6040 6041 6042 6043
  SQInfo* pQInfo = (SQInfo*) qHandle;
  if (!isValidQInfo(pQInfo)) {
    return;
  }

dengyihao's avatar
dengyihao 已提交
6044
  int32_t ref = T_REF_DEC(pQInfo);
6045
  qDebug("QInfo:%p dec refCount, value:%d", pQInfo, ref);
H
Haojun Liao 已提交
6046

H
Haojun Liao 已提交
6047
  if (ref == 0) {
6048
    _qinfo_free_fn_t freeFp = pQInfo->freeFn;
H
Hongze Cheng 已提交
6049
    void* param = pQInfo->param;
H
Haojun Liao 已提交
6050 6051

    doDestoryQueryInfo(pQInfo);
6052
    if (freeFp != NULL) {
H
Hongze Cheng 已提交
6053
      assert(param != NULL);
6054
      freeFp(param);
H
Hongze Cheng 已提交
6055 6056
    }

H
Haojun Liao 已提交
6057 6058 6059
  }
}

6060
void qTableQuery(qinfo_t qinfo) {
6061 6062
  SQInfo *pQInfo = (SQInfo *)qinfo;

H
hjxilinx 已提交
6063
  if (pQInfo == NULL || pQInfo->signature != pQInfo) {
6064
    qDebug("QInfo:%p has been freed, no need to execute", pQInfo);
H
hjxilinx 已提交
6065 6066
    return;
  }
6067

H
hjxilinx 已提交
6068
  if (isQueryKilled(pQInfo)) {
6069
    qDebug("QInfo:%p it is already killed, abort", pQInfo);
6070 6071

    sem_post(&pQInfo->dataReady);
H
Haojun Liao 已提交
6072
    qDestroyQueryInfo(pQInfo);
H
hjxilinx 已提交
6073 6074
    return;
  }
6075

6076 6077
  if (pQInfo->tableqinfoGroupInfo.numOfTables == 0) {
    qDebug("QInfo:%p no table exists for query, abort", pQInfo);
6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091

    sem_post(&pQInfo->dataReady);
    qDestroyQueryInfo(pQInfo);
    return;
  }

  int32_t ret = setjmp(pQInfo->env);
  // error occurs, record the error code and return to client
  if (ret != TSDB_CODE_SUCCESS) {
    pQInfo->code = ret;
    qDebug("QInfo:%p query abort due to error occurs, code:%s", pQInfo, tstrerror(pQInfo->code));
    sem_post(&pQInfo->dataReady);
    qDestroyQueryInfo(pQInfo);

6092 6093 6094
    return;
  }

6095
  qDebug("QInfo:%p query task is launched", pQInfo);
6096

6097
  SQueryRuntimeEnv* pRuntimeEnv = &pQInfo->runtimeEnv;
H
hjxilinx 已提交
6098
  if (onlyQueryTags(pQInfo->runtimeEnv.pQuery)) {
H
Haojun Liao 已提交
6099
    assert(pQInfo->runtimeEnv.pQueryHandle == NULL);
H
hjxilinx 已提交
6100
    buildTagQueryResult(pQInfo);   // todo support the limit/offset
H
hjxilinx 已提交
6101
  } else if (pQInfo->runtimeEnv.stableQuery) {
6102
    stableQueryImpl(pQInfo);
H
hjxilinx 已提交
6103
  } else {
6104
    tableQueryImpl(pQInfo);
H
hjxilinx 已提交
6105
  }
6106

6107 6108 6109 6110 6111 6112 6113 6114 6115 6116
  SQuery* pQuery = pRuntimeEnv->pQuery;
  if (isQueryKilled(pQInfo)) {
    qDebug("QInfo:%p query is killed", pQInfo);
  } else if (pQuery->rec.rows == 0) {
    qDebug("QInfo:%p over, %zu tables queried, %"PRId64" rows are returned", pQInfo, pQInfo->tableqinfoGroupInfo.numOfTables, pQuery->rec.total);
  } else {
    qDebug("QInfo:%p query paused, %" PRId64 " rows returned, numOfTotal:%" PRId64 " rows",
           pQInfo, pQuery->rec.rows, pQuery->rec.total + pQuery->rec.rows);
  }

H
hjxilinx 已提交
6117
  sem_post(&pQInfo->dataReady);
H
Haojun Liao 已提交
6118
  qDestroyQueryInfo(pQInfo);
H
hjxilinx 已提交
6119 6120
}

H
hjxilinx 已提交
6121
int32_t qRetrieveQueryResultInfo(qinfo_t qinfo) {
6122 6123
  SQInfo *pQInfo = (SQInfo *)qinfo;

H
hjxilinx 已提交
6124
  if (pQInfo == NULL || !isValidQInfo(pQInfo)) {
6125
    return TSDB_CODE_QRY_INVALID_QHANDLE;
H
hjxilinx 已提交
6126
  }
6127

H
hjxilinx 已提交
6128
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
6129
  if (isQueryKilled(pQInfo)) {
6130
    qDebug("QInfo:%p query is killed, code:%d", pQInfo, pQInfo->code);
H
hjxilinx 已提交
6131
    return pQInfo->code;
H
hjxilinx 已提交
6132
  }
6133

H
hjxilinx 已提交
6134
  sem_wait(&pQInfo->dataReady);
6135
  qDebug("QInfo:%p retrieve result info, rowsize:%d, rows:%"PRId64", code:%d", pQInfo, pQuery->rowSize, pQuery->rec.rows,
6136 6137
         pQInfo->code);

H
hjxilinx 已提交
6138
  return pQInfo->code;
H
hjxilinx 已提交
6139
}
6140

H
hjxilinx 已提交
6141
bool qHasMoreResultsToRetrieve(qinfo_t qinfo) {
6142 6143
  SQInfo *pQInfo = (SQInfo *)qinfo;

H
Haojun Liao 已提交
6144
  if (!isValidQInfo(pQInfo) || pQInfo->code != TSDB_CODE_SUCCESS) {
6145
    qDebug("QInfo:%p invalid qhandle or error occurs, abort query, code:%x", pQInfo, pQInfo->code);
H
hjxilinx 已提交
6146 6147
    return false;
  }
6148 6149

  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
H
Haojun Liao 已提交
6150
  bool ret = false;
H
hjxilinx 已提交
6151
  if (Q_STATUS_EQUAL(pQuery->status, QUERY_OVER)) {
H
Haojun Liao 已提交
6152
    ret = false;
H
hjxilinx 已提交
6153
  } else if (Q_STATUS_EQUAL(pQuery->status, QUERY_RESBUF_FULL)) {
H
Haojun Liao 已提交
6154
    ret = true;
H
hjxilinx 已提交
6155
  } else if (Q_STATUS_EQUAL(pQuery->status, QUERY_COMPLETED)) {
H
Haojun Liao 已提交
6156
    ret = true;
H
hjxilinx 已提交
6157 6158
  } else {
    assert(0);
6159
  }
H
Haojun Liao 已提交
6160 6161 6162

  if (ret) {
    T_REF_INC(pQInfo);
6163
    qDebug("QInfo:%p has more results waits for client retrieve", pQInfo);
H
Haojun Liao 已提交
6164 6165 6166
  }

  return ret;
6167 6168
}

6169 6170 6171
int32_t qDumpRetrieveResult(qinfo_t qinfo, SRetrieveTableRsp **pRsp, int32_t *contLen) {
  SQInfo *pQInfo = (SQInfo *)qinfo;

H
hjxilinx 已提交
6172
  if (pQInfo == NULL || !isValidQInfo(pQInfo)) {
6173
    return TSDB_CODE_QRY_INVALID_QHANDLE;
6174
  }
6175

6176
  SQueryRuntimeEnv* pRuntimeEnv = &pQInfo->runtimeEnv;
6177 6178
  SQuery *pQuery = pQInfo->runtimeEnv.pQuery;
  size_t  size = getResultSize(pQInfo, &pQuery->rec.rows);
weixin_48148422's avatar
weixin_48148422 已提交
6179 6180
  size += sizeof(int32_t);
  size += sizeof(STableIdInfo) * taosArrayGetSize(pQInfo->arrTableIdInfo);
6181
  *contLen = size + sizeof(SRetrieveTableRsp);
6182

6183 6184
  // todo handle failed to allocate memory
  *pRsp = (SRetrieveTableRsp *)rpcMallocCont(*contLen);
6185
  (*pRsp)->numOfRows = htonl(pQuery->rec.rows);
6186

6187 6188 6189
  int32_t code = pQInfo->code;
  if (code == TSDB_CODE_SUCCESS) {
    (*pRsp)->offset = htobe64(pQuery->limit.offset);
6190
    (*pRsp)->useconds = htobe64(pRuntimeEnv->summary.elapsedTime);
6191 6192 6193 6194
  } else {
    (*pRsp)->offset = 0;
    (*pRsp)->useconds = 0;
  }
6195 6196
  
  (*pRsp)->precision = htons(pQuery->precision);
6197
  if (pQuery->rec.rows > 0 && code == TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
6198
    code = doDumpQueryResult(pQInfo, (*pRsp)->data);
6199
  } else {
H
hjxilinx 已提交
6200
    setQueryStatus(pQuery, QUERY_OVER);
6201
    code = pQInfo->code;
6202
  }
6203

H
hjxilinx 已提交
6204
  if (isQueryKilled(pQInfo) || Q_STATUS_EQUAL(pQuery->status, QUERY_OVER)) {
6205
    (*pRsp)->completed = 1;  // notify no more result to client
H
hjxilinx 已提交
6206
  }
6207

H
hjxilinx 已提交
6208
  return code;
6209
}
H
hjxilinx 已提交
6210

H
Haojun Liao 已提交
6211
int32_t qKillQuery(qinfo_t qinfo) {
H
Haojun Liao 已提交
6212 6213 6214 6215 6216 6217 6218
  SQInfo *pQInfo = (SQInfo *)qinfo;

  if (pQInfo == NULL || !isValidQInfo(pQInfo)) {
    return TSDB_CODE_QRY_INVALID_QHANDLE;
  }

  setQueryKilled(pQInfo);
H
Haojun Liao 已提交
6219
  qDestroyQueryInfo(pQInfo);
H
Haojun Liao 已提交
6220 6221 6222
  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
6223 6224 6225
static void buildTagQueryResult(SQInfo* pQInfo) {
  SQueryRuntimeEnv *pRuntimeEnv = &pQInfo->runtimeEnv;
  SQuery *          pQuery = pRuntimeEnv->pQuery;
6226

H
Haojun Liao 已提交
6227
  size_t numOfGroup = GET_NUM_OF_TABLEGROUP(pQInfo);
H
Haojun Liao 已提交
6228
  assert(numOfGroup == 0 || numOfGroup == 1);
6229

H
Haojun Liao 已提交
6230
  if (numOfGroup == 0) {
6231 6232
    return;
  }
H
hjxilinx 已提交
6233
  
H
Haojun Liao 已提交
6234
  SArray* pa = GET_TABLEGROUP(pQInfo, 0);
6235

H
Haojun Liao 已提交
6236
  size_t num = taosArrayGetSize(pa);
6237
  assert(num == pQInfo->tableqinfoGroupInfo.numOfTables);
6238

H
Haojun Liao 已提交
6239
  int32_t count = 0;
6240 6241 6242
  int32_t functionId = pQuery->pSelectExpr[0].base.functionId;
  if (functionId == TSDB_FUNC_TID_TAG) { // return the tags & table Id
    assert(pQuery->numOfOutput == 1);
6243

6244 6245
    SExprInfo* pExprInfo = &pQuery->pSelectExpr[0];
    int32_t rsize = pExprInfo->bytes;
H
Haojun Liao 已提交
6246
    count = 0;
6247

H
Haojun Liao 已提交
6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258
    int16_t bytes = pExprInfo->bytes;
    int16_t type = pExprInfo->type;

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

H
Haojun Liao 已提交
6259 6260
    while(pQInfo->tableIndex < num && count < pQuery->rec.capacity) {
      int32_t i = pQInfo->tableIndex++;
6261
      STableQueryInfo *item = taosArrayGetP(pa, i);
6262

6263
      char *output = pQuery->sdata[0]->data + i * rsize;
6264
      varDataSetLen(output, rsize - VARSTR_HEADER_SIZE);
6265

6266
      output = varDataVal(output);
6267 6268 6269 6270
      STableId id = tsdbGetTableId(item->pTable);

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

6272 6273
      *(int32_t *)output = id.tid;
      output += sizeof(id.tid);
6274

6275
      *(int32_t *)output = pQInfo->vgId;
6276
      output += sizeof(pQInfo->vgId);
6277

6278
      if (pExprInfo->base.colInfo.colId == TSDB_TBNAME_COLUMN_INDEX) {
6279
        char *data = tsdbGetTableName(item->pTable);
6280
        memcpy(output, data, varDataTLen(data));
H
[td-90]  
Haojun Liao 已提交
6281
      } else {
6282
        char *val = tsdbGetTableTagVal(item->pTable, pExprInfo->base.colInfo.colId, type, bytes);
6283 6284 6285 6286 6287 6288 6289 6290

        // todo refactor
        if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
          if (val == NULL) {
            setVardataNull(output, type);
          } else {
            memcpy(output, val, varDataTLen(val));
          }
H
[td-90]  
Haojun Liao 已提交
6291
        } else {
6292 6293
          if (val == NULL) {
            setNull(output, type, bytes);
H
Haojun Liao 已提交
6294
          } else {  // todo here stop will cause client crash
6295 6296
            memcpy(output, val, bytes);
          }
H
[td-90]  
Haojun Liao 已提交
6297 6298
        }
      }
6299

H
Haojun Liao 已提交
6300
      count += 1;
6301
    }
6302

6303
    qDebug("QInfo:%p create (tableId, tag) info completed, rows:%d", pQInfo, count);
6304

H
Haojun Liao 已提交
6305 6306 6307 6308 6309
  } else if (functionId == TSDB_FUNC_COUNT) {// handle the "count(tbname)" query
    *(int64_t*) pQuery->sdata[0]->data = num;

    count = 1;
    pQInfo->tableIndex = num;  //set query completed
6310
    qDebug("QInfo:%p create count(tbname) query, res:%d rows:1", pQInfo, count);
6311
  } else {  // return only the tags|table name etc.
H
Haojun Liao 已提交
6312
    count = 0;
H
Haojun Liao 已提交
6313
    SSchema tbnameSchema = tGetTableNameColumnSchema();
H
Haojun Liao 已提交
6314 6315
    while(pQInfo->tableIndex < num && count < pQuery->rec.capacity) {
      int32_t i = pQInfo->tableIndex++;
6316

6317
      SExprInfo* pExprInfo = pQuery->pSelectExpr;
6318
      STableQueryInfo* item = taosArrayGetP(pa, i);
6319

6320 6321
      for(int32_t j = 0; j < pQuery->numOfOutput; ++j) {
        if (pExprInfo[j].base.colInfo.colId == TSDB_TBNAME_COLUMN_INDEX) {
6322
          char* data = tsdbGetTableName(item->pTable);
H
Haojun Liao 已提交
6323
          char* dst = pQuery->sdata[j]->data + count * tbnameSchema.bytes;
H
hjxilinx 已提交
6324
          memcpy(dst, data, varDataTLen(data));
H
[td-90]  
Haojun Liao 已提交
6325 6326 6327 6328
        } else {// todo refactor
          int16_t type = pExprInfo[j].type;
          int16_t bytes = pExprInfo[j].bytes;
          
6329
          char* data = tsdbGetTableTagVal(item->pTable, pExprInfo[j].base.colInfo.colId, type, bytes);
H
Haojun Liao 已提交
6330
          char* dst = pQuery->sdata[j]->data + count * pExprInfo[j].bytes;
6331

H
hjxilinx 已提交
6332
          if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
H
[td-90]  
Haojun Liao 已提交
6333 6334 6335 6336 6337
            if (data == NULL) {
              setVardataNull(dst, type);
            } else {
              memcpy(dst, data, varDataTLen(data));
            }
H
hjxilinx 已提交
6338
          } else {
H
[td-90]  
Haojun Liao 已提交
6339 6340 6341 6342 6343
            if (data == NULL) {
              setNull(dst, type, bytes);
            } else {
              memcpy(dst, data, pExprInfo[j].bytes);
            }
H
hjxilinx 已提交
6344
          }
6345
        }
H
hjxilinx 已提交
6346
      }
H
Haojun Liao 已提交
6347
      count += 1;
H
hjxilinx 已提交
6348
    }
6349

6350
    qDebug("QInfo:%p create tag values results completed, rows:%d", pQInfo, count);
H
hjxilinx 已提交
6351
  }
6352

H
Haojun Liao 已提交
6353
  pQuery->rec.rows = count;
H
hjxilinx 已提交
6354
  setQueryStatus(pQuery, QUERY_COMPLETED);
H
hjxilinx 已提交
6355 6356
}