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

16 17 18 19 20 21 22
#include "tsdb.h"
#include "tsdbDef.h"
#include "tsdbFS.h"
#include "tsdbLog.h"
#include "tsdbReadImpl.h"
#include "ttime.h"
#include "exception.h"
H
hjxilinx 已提交
23
#include "os.h"
24
#include "talgo.h"
25
#include "tcompare.h"
26 27
#include "tdataformat.h"
#include "tskiplist.h"
28

29
#include "taosdef.h"
30
#include "tlosertree.h"
H
Hongze Cheng 已提交
31
#include "tsdbDef.h"
32
#include "tmsg.h"
33

34
#define EXTRA_BYTES 2
35
#define ASCENDING_TRAVERSE(o)   (o == TSDB_ORDER_ASC)
36
#define QH_GET_NUM_OF_COLS(handle) ((size_t)(taosArrayGetSize((handle)->pColumns)))
H
hjxilinx 已提交
37

H
Haojun Liao 已提交
38 39 40 41
#define GET_FILE_DATA_BLOCK_INFO(_checkInfo, _block)                                   \
  ((SDataBlockInfo){.window = {.skey = (_block)->keyFirst, .ekey = (_block)->keyLast}, \
                    .numOfCols = (_block)->numOfCols,                                  \
                    .rows = (_block)->numOfRows,                                       \
42
                    .uid = (_checkInfo)->tableId})
H
Haojun Liao 已提交
43

H
hjxilinx 已提交
44
enum {
45 46
  TSDB_QUERY_TYPE_ALL      = 1,
  TSDB_QUERY_TYPE_LAST     = 2,
H
hjxilinx 已提交
47 48
};

49 50 51 52 53 54
enum {
  TSDB_CACHED_TYPE_NONE    = 0,
  TSDB_CACHED_TYPE_LASTROW = 1,
  TSDB_CACHED_TYPE_LAST    = 2,
};

55 56
typedef struct SQueryFilePos {
  int32_t fid;
57 58
  int32_t slot;
  int32_t pos;
59
  int64_t lastKey;
60 61
  int32_t rows;
  bool    mixBlock;
62
  bool    blockCompleted;
63
  STimeWindow win;
64
} SQueryFilePos;
H
hjxilinx 已提交
65

66
typedef struct SDataBlockLoadInfo {
H
Hongze Cheng 已提交
67
  SDFileSet*  fileGroup;
68
  int32_t     slot;
69
  uint64_t    uid;
70
  SArray*     pLoadedCols;
71
} SDataBlockLoadInfo;
H
hjxilinx 已提交
72

73
typedef struct SLoadCompBlockInfo {
H
hjLiao 已提交
74
  int32_t tid; /* table tid */
75 76
  int32_t fileId;
} SLoadCompBlockInfo;
H
hjxilinx 已提交
77

78 79 80 81 82 83
enum {
  CHECKINFO_CHOSEN_MEM  = 0,
  CHECKINFO_CHOSEN_IMEM = 1,
  CHECKINFO_CHOSEN_BOTH = 2    //for update=2(merge case)
};

D
init  
dapan1121 已提交
84

85
typedef struct STableCheckInfo {
86
  uint64_t      tableId;
H
Haojun Liao 已提交
87 88
  TSKEY         lastKey;
  STable*       pTableObj;
H
Haojun Liao 已提交
89
  SBlockInfo*   pCompInfo;
H
Haojun Liao 已提交
90
  int32_t       compSize;
91
  int32_t       numOfBlocks:29; // number of qualified data blocks not the original blocks
92
  uint8_t       chosen:2;       // indicate which iterator should move forward
H
Haojun Liao 已提交
93 94 95
  bool          initBuf;        // whether to initialize the in-memory skip list iterator or not
  SSkipListIterator* iter;      // mem buffer skip list iterator
  SSkipListIterator* iiter;     // imem buffer skip list iterator
96
} STableCheckInfo;
97

98
typedef struct STableBlockInfo {
H
Haojun Liao 已提交
99 100
  SBlock          *compBlock;
  STableCheckInfo *pTableCheckInfo;
101
} STableBlockInfo;
102

103 104
typedef struct SBlockOrderSupporter {
  int32_t             numOfTables;
H
Haojun Liao 已提交
105
  STableBlockInfo**   pDataBlockInfo;
106
  int32_t*            blockIndexArray;
107
  int32_t*            numOfBlocksPerTable;
108 109
} SBlockOrderSupporter;

H
Haojun Liao 已提交
110 111 112
typedef struct SIOCostSummary {
  int64_t blockLoadTime;
  int64_t statisInfoLoadTime;
H
Haojun Liao 已提交
113
  int64_t checkForNextTime;
114 115
  int64_t headFileLoad;
  int64_t headFileLoadTime;
H
Haojun Liao 已提交
116 117
} SIOCostSummary;

118 119
typedef struct STsdbReadHandle {
  STsdb*     pTsdb;
H
Haojun Liao 已提交
120 121 122 123 124 125 126 127 128
  SQueryFilePos  cur;              // current position
  int16_t        order;
  STimeWindow    window;           // the primary query time window that applies to all queries
  SDataStatis*   statis;           // query level statistics, only one table block statistics info exists at any time
  int32_t        numOfBlocks;
  SArray*        pColumns;         // column list, SColumnInfoData array list
  bool           locateStart;
  int32_t        outputCapacity;
  int32_t        realNumOfRows;
H
Haojun Liao 已提交
129
  SArray*        pTableCheckInfo;  // SArray<STableCheckInfo>
H
Haojun Liao 已提交
130 131
  int32_t        activeIndex;
  bool           checkFiles;       // check file stage
D
init  
dapan1121 已提交
132
  int8_t         cachelastrow;     // check if last row cached
133
  bool           loadExternalRow;  // load time window external data rows
H
Haojun Liao 已提交
134 135
  bool           currentLoadExternalRows; // current load external rows
  int32_t        loadType;         // block load type
H
Haojun Liao 已提交
136
  uint64_t       qId;              // query info handle, for debug purpose
H
Haojun Liao 已提交
137
  int32_t        type;             // query type: retrieve all data blocks, 2. retrieve only last row, 3. retrieve direct prev|next rows
H
Hongze Cheng 已提交
138 139 140
  SDFileSet*     pFileGroup;
  SFSIter        fileIter;
  SReadH         rhelper;
H
Haojun Liao 已提交
141
  STableBlockInfo* pDataBlockInfo;
H
Haojun Liao 已提交
142
  SDataCols     *pDataCols;        // in order to hold current file data block
H
Haojun Liao 已提交
143
  int32_t        allocSize;        // allocated data block size
144 145
//  STsdb
//  STsdbMemTable *     pMemTable;
H
Haojun Liao 已提交
146
  SArray        *defaultLoadColumn;// default load column
H
Haojun Liao 已提交
147
  SDataBlockLoadInfo dataBlockLoadInfo; /* record current block load information */
H
Haojun Liao 已提交
148
  SLoadCompBlockInfo compBlockLoadInfo; /* record current compblock information in SQueryAttr */
H
Haojun Liao 已提交
149

150 151
  SArray        *prev;             // previous row which is before than time window
  SArray        *next;             // next row which is after the query time window
H
Haojun Liao 已提交
152
  SIOCostSummary cost;
153
} STsdbReadHandle;
154

H
Haojun Liao 已提交
155 156 157 158 159 160
typedef struct STableGroupSupporter {
  int32_t    numOfCols;
  SColIndex* pCols;
  STSchema*  pTagSchema;
} STableGroupSupporter;

161
static STimeWindow updateLastrowForEachGroup(STableGroupInfo *groupList);
162 163 164
static int32_t checkForCachedLastRow(STsdbReadHandle* pTsdbReadHandle, STableGroupInfo *groupList);
static int32_t checkForCachedLast(STsdbReadHandle* pTsdbReadHandle);
//static int32_t tsdbGetCachedLastRow(STable* pTable, SMemRow* pRes, TSKEY* lastKey);
H
Haojun Liao 已提交
165

166 167
static void    changeQueryHandleForInterpQuery(tsdbReadHandleT pHandle);
static void    doMergeTwoLevelData(STsdbReadHandle* pTsdbReadHandle, STableCheckInfo* pCheckInfo, SBlock* pBlock);
168
static int32_t binarySearchForKey(char* pValue, int num, TSKEY key, int order);
169
static int32_t tsdbReadRowsFromCache(STableCheckInfo* pCheckInfo, TSKEY maxKey, int maxRowsToRead, STimeWindow* win, STsdbReadHandle* pTsdbReadHandle);
170
static int32_t tsdbCheckInfoCompar(const void* key1, const void* key2);
171 172 173 174
//static int32_t doGetExternalRow(STsdbReadHandle* pTsdbReadHandle, int16_t type, void* pMemRef);
//static void*   doFreeColumnInfoData(SArray* pColumnInfoData);
//static void*   destroyTableCheckInfo(SArray* pTableCheckInfo);
static bool    tsdbGetExternalRow(tsdbReadHandleT pHandle);
Y
TD-1733  
yihaoDeng 已提交
175

176
static void tsdbInitDataBlockLoadInfo(SDataBlockLoadInfo* pBlockLoadInfo) {
H
hjxilinx 已提交
177
  pBlockLoadInfo->slot = -1;
178
  pBlockLoadInfo->uid  = 0;
H
hjxilinx 已提交
179
  pBlockLoadInfo->fileGroup = NULL;
H
hjxilinx 已提交
180 181
}

182
static void tsdbInitCompBlockLoadInfo(SLoadCompBlockInfo* pCompBlockLoadInfo) {
H
hjLiao 已提交
183
  pCompBlockLoadInfo->tid = -1;
184 185
  pCompBlockLoadInfo->fileId = -1;
}
H
hjxilinx 已提交
186

187 188
static SArray* getColumnIdList(STsdbReadHandle* pTsdbReadHandle) {
  size_t numOfCols = QH_GET_NUM_OF_COLS(pTsdbReadHandle);
H
Haojun Liao 已提交
189 190 191 192
  assert(numOfCols <= TSDB_MAX_COLUMNS);

  SArray* pIdList = taosArrayInit(numOfCols, sizeof(int16_t));
  for (int32_t i = 0; i < numOfCols; ++i) {
193
    SColumnInfoData* pCol = taosArrayGet(pTsdbReadHandle->pColumns, i);
H
Haojun Liao 已提交
194 195 196 197 198 199
    taosArrayPush(pIdList, &pCol->info.colId);
  }

  return pIdList;
}

200 201
static SArray* getDefaultLoadColumns(STsdbReadHandle* pTsdbReadHandle, bool loadTS) {
  SArray* pLocalIdList = getColumnIdList(pTsdbReadHandle);
H
Haojun Liao 已提交
202 203 204 205 206 207 208 209 210 211 212 213 214

  // check if the primary time stamp column needs to load
  int16_t colId = *(int16_t*)taosArrayGet(pLocalIdList, 0);

  // the primary timestamp column does not be included in the the specified load column list, add it
  if (loadTS && colId != 0) {
    int16_t columnId = 0;
    taosArrayInsert(pLocalIdList, 0, &columnId);
  }

  return pLocalIdList;
}

215 216 217 218 219 220 221 222 223
static void tsdbMayTakeMemSnapshot(STsdbReadHandle* pTsdbReadHandle, SArray* psTable) {
//  assert(pTsdbReadHandle != NULL && pTsdbReadHandle->pMemRef != NULL);
//
//  STsdbMemTable* pMemRef = pTsdbReadHandle->pMemRef;
//  if (pTsdbReadHandle->pMemRef->ref++ == 0) {
//    tsdbTakeMemSnapshot(pTsdbReadHandle->pTsdb, &(pMemRef->snapshot), psTable);
//  }
//
//  taosArrayDestroy(psTable);
Y
TD-1733  
yihaoDeng 已提交
224
}
225

226 227 228 229 230 231 232 233 234 235 236 237
static void tsdbMayUnTakeMemSnapshot(STsdbReadHandle* pTsdbReadHandle) {
//  assert(pTsdbReadHandle != NULL);
//  STsdbMemTable* pMemRef = pTsdbReadHandle->pMemRef;
//  if (pMemRef == NULL) { // it has been freed
//    return;
//  }
//
//  if (--pMemRef->ref == 0) {
//    tsdbUnTakeMemSnapShot(pTsdbReadHandle->pTsdb, &(pMemRef->snapshot));
//  }
//
//  pTsdbReadHandle->pMemRef = NULL;
Y
yihaoDeng 已提交
238 239
}

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
//int64_t tsdbGetNumOfRowsInMemTable(tsdbReadHandleT* pHandle) {
//  STsdbReadHandle* pTsdbReadHandle = (STsdbReadHandle*) pHandle;
//
//  int64_t rows = 0;
//  STsdbMemTable* pMemTable = pTsdbReadHandle->pMemTable;
//  if (pMemTable == NULL) { return rows; }
//
////  STableData* pMem  = NULL;
////  STableData* pIMem = NULL;
//
////  SMemTable* pMemT = pMemRef->snapshot.mem;
////  SMemTable* pIMemT = pMemRef->snapshot.imem;
//
//  size_t size = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
//  for (int32_t i = 0; i < size; ++i) {
//    STableCheckInfo* pCheckInfo = taosArrayGet(pTsdbReadHandle->pTableCheckInfo, i);
//
////    if (pMemT && pCheckInfo->tableId < pMemT->maxTables) {
////      pMem = pMemT->tData[pCheckInfo->tableId];
////      rows += (pMem && pMem->uid == pCheckInfo->tableId) ? pMem->numOfRows : 0;
////    }
////    if (pIMemT && pCheckInfo->tableId < pIMemT->maxTables) {
////      pIMem = pIMemT->tData[pCheckInfo->tableId];
////      rows += (pIMem && pIMem->uid == pCheckInfo->tableId) ? pIMem->numOfRows : 0;
////    }
//  }
//  return rows;
//}

static SArray* createCheckInfoFromTableGroup(STsdbReadHandle* pTsdbReadHandle, STableGroupInfo* pGroupList, SArray** psTable) {
H
Haojun Liao 已提交
270
  size_t sizeOfGroup = taosArrayGetSize(pGroupList->pGroupList);
271
  assert(sizeOfGroup >= 1);
H
Haojun Liao 已提交
272 273 274 275 276 277 278

  // allocate buffer in order to load data blocks from file
  SArray* pTableCheckInfo = taosArrayInit(pGroupList->numOfTables, sizeof(STableCheckInfo));
  if (pTableCheckInfo == NULL) {
    return NULL;
  }

D
fix bug  
dapan1121 已提交
279 280 281 282 283 284
  SArray* pTable = taosArrayInit(4, sizeof(STable*));
  if (pTable == NULL) {
    taosArrayDestroy(pTableCheckInfo);
    return NULL;
  }

H
Haojun Liao 已提交
285 286 287 288 289 290 291 292 293 294 295
  // todo apply the lastkey of table check to avoid to load header file
  for (int32_t i = 0; i < sizeOfGroup; ++i) {
    SArray* group = *(SArray**) taosArrayGet(pGroupList->pGroupList, i);

    size_t gsize = taosArrayGetSize(group);
    assert(gsize > 0);

    for (int32_t j = 0; j < gsize; ++j) {
      STableKeyInfo* pKeyInfo = (STableKeyInfo*) taosArrayGet(group, j);

      STableCheckInfo info = { .lastKey = pKeyInfo->lastKey, .pTableObj = pKeyInfo->pTable };
296 297
//      assert(info.pTableObj != NULL && (info.pTableObj->type == TSDB_NORMAL_TABLE ||
//                                        info.pTableObj->type == TSDB_CHILD_TABLE || info.pTableObj->type == TSDB_STREAM_TABLE));
H
Haojun Liao 已提交
298

299
      info.tableId = pKeyInfo->uid;
H
Haojun Liao 已提交
300

301 302 303
      if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
        if (info.lastKey == INT64_MIN || info.lastKey < pTsdbReadHandle->window.skey) {
          info.lastKey = pTsdbReadHandle->window.skey;
304 305
        }

306
        assert(info.lastKey >= pTsdbReadHandle->window.skey && info.lastKey <= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
307
      } else {
308
        assert(info.lastKey >= pTsdbReadHandle->window.ekey && info.lastKey <= pTsdbReadHandle->window.skey);
H
Haojun Liao 已提交
309 310 311
      }

      taosArrayPush(pTableCheckInfo, &info);
312
      tsdbDebug("%p check table uid:%"PRId64" from lastKey:%"PRId64" 0x%"PRIx64, pTsdbReadHandle, info.tableId, info.lastKey, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
313 314 315
    }
  }

316
//  taosArraySort(pTableCheckInfo, tsdbCheckInfoCompar);
D
dapan1121 已提交
317 318 319 320 321 322 323
  size_t gsize = taosArrayGetSize(pTableCheckInfo);
  for (int32_t i = 0; i < gsize; ++i) {
    STableCheckInfo* pInfo = (STableCheckInfo*) taosArrayGet(pTableCheckInfo, i);
    taosArrayPush(pTable, &pInfo->pTableObj);
  }

  *psTable = pTable;
H
Haojun Liao 已提交
324 325 326
  return pTableCheckInfo;
}

327 328
static void resetCheckInfo(STsdbReadHandle* pTsdbReadHandle) {
  size_t numOfTables = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
H
Haojun Liao 已提交
329 330 331 332
  assert(numOfTables >= 1);

  // todo apply the lastkey of table check to avoid to load header file
  for (int32_t i = 0; i < numOfTables; ++i) {
333 334
    STableCheckInfo* pCheckInfo = (STableCheckInfo*) taosArrayGet(pTsdbReadHandle->pTableCheckInfo, i);
    pCheckInfo->lastKey = pTsdbReadHandle->window.skey;
H
Haojun Liao 已提交
335 336
    pCheckInfo->iter    = tSkipListDestroyIter(pCheckInfo->iter);
    pCheckInfo->iiter   = tSkipListDestroyIter(pCheckInfo->iiter);
337
    pCheckInfo->initBuf = false;
H
Haojun Liao 已提交
338

339 340
    if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
      assert(pCheckInfo->lastKey >= pTsdbReadHandle->window.skey);
341
    } else {
342
      assert(pCheckInfo->lastKey <= pTsdbReadHandle->window.skey);
343
    }
H
Haojun Liao 已提交
344 345 346
  }
}

H
Haojun Liao 已提交
347 348 349 350
// only one table, not need to sort again
static SArray* createCheckInfoFromCheckInfo(STableCheckInfo* pCheckInfo, TSKEY skey, SArray** psTable) {
  SArray* pNew = taosArrayInit(1, sizeof(STableCheckInfo));
  SArray* pTable = taosArrayInit(1, sizeof(STable*));
D
fix bug  
dapan1121 已提交
351

H
Haojun Liao 已提交
352
  STableCheckInfo info = { .lastKey = skey, .pTableObj = pCheckInfo->pTableObj};
H
Haojun Liao 已提交
353

H
Haojun Liao 已提交
354 355 356
  info.tableId = pCheckInfo->tableId;
  taosArrayPush(pNew, &info);
  taosArrayPush(pTable, &pCheckInfo->pTableObj);
H
Haojun Liao 已提交
357

D
fix bug  
dapan1121 已提交
358
  *psTable = pTable;
H
Haojun Liao 已提交
359 360 361
  return pNew;
}

362 363
static bool emptyQueryTimewindow(STsdbReadHandle* pTsdbReadHandle) {
  assert(pTsdbReadHandle != NULL);
364

365 366
  STimeWindow* w = &pTsdbReadHandle->window;
  bool asc = ASCENDING_TRAVERSE(pTsdbReadHandle->order);
367 368 369 370

  return ((asc && w->skey > w->ekey) || (!asc && w->ekey > w->skey));
}

371 372
// Update the query time window according to the data time to live(TTL) information, in order to avoid to return
// the expired data to client, even it is queried already.
373
static int64_t getEarliestValidTimestamp(STsdb* pTsdb) {
374 375 376
  STsdbCfg* pCfg = &pTsdb->config;

  int64_t now = taosGetTimestamp(pCfg->precision);
377
  return now - (tsTickPerDay[pCfg->precision] * pCfg->keep) + 1;  // needs to add one tick
378 379
}

380 381
static void setQueryTimewindow(STsdbReadHandle* pTsdbReadHandle, STsdbQueryCond* pCond) {
  pTsdbReadHandle->window = pCond->twindow;
382

383
  bool    updateTs = false;
384 385 386 387
  int64_t startTs = getEarliestValidTimestamp(pTsdbReadHandle->pTsdb);
  if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
    if (startTs > pTsdbReadHandle->window.skey) {
      pTsdbReadHandle->window.skey = startTs;
388 389
      pCond->twindow.skey = startTs;
      updateTs = true;
390 391
    }
  } else {
392 393
    if (startTs > pTsdbReadHandle->window.ekey) {
      pTsdbReadHandle->window.ekey = startTs;
394 395
      pCond->twindow.ekey = startTs;
      updateTs = true;
396 397 398
    }
  }

399 400
  if (updateTs) {
    tsdbDebug("%p update the query time window, old:%" PRId64 " - %" PRId64 ", new:%" PRId64 " - %" PRId64
401 402
              ", 0x%" PRIx64, pTsdbReadHandle, pCond->twindow.skey, pCond->twindow.ekey, pTsdbReadHandle->window.skey,
              pTsdbReadHandle->window.ekey, pTsdbReadHandle->qId);
403
  }
404 405
}

406 407 408
static STsdbReadHandle* tsdbQueryTablesImpl(STsdb* tsdb, STsdbQueryCond* pCond, uint64_t qId, STsdbMemTable* pMemRef) {
  STsdbReadHandle* pReadHandle = calloc(1, sizeof(STsdbReadHandle));
  if (pReadHandle == NULL) {
409
    goto _end;
410
  }
H
Haojun Liao 已提交
411

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
  pReadHandle->order       = pCond->order;
  pReadHandle->pTsdb       = tsdb;
  pReadHandle->type        = TSDB_QUERY_TYPE_ALL;
  pReadHandle->cur.fid     = INT32_MIN;
  pReadHandle->cur.win     = TSWINDOW_INITIALIZER;
  pReadHandle->checkFiles  = true;
  pReadHandle->activeIndex = 0;   // current active table index
  pReadHandle->qId         = qId;
  pReadHandle->allocSize   = 0;
  pReadHandle->locateStart = false;
  pReadHandle->loadType    = pCond->type;

  pReadHandle->outputCapacity  = 4096;//((STsdb*)tsdb)->config.maxRowsPerFileBlock;
  pReadHandle->loadExternalRow = pCond->loadExternalRows;
  pReadHandle->currentLoadExternalRows = pCond->loadExternalRows;

  if (tsdbInitReadH(&pReadHandle->rhelper, (STsdb*)tsdb) != 0) {
429
    goto _end;
B
Bomin Zhang 已提交
430
  }
H
Haojun Liao 已提交
431

432 433
  assert(pCond != NULL);
  setQueryTimewindow(pReadHandle, pCond);
434

435 436
  if (pCond->numOfCols > 0) {
    // allocate buffer in order to load data blocks from file
437 438
    pReadHandle->statis = calloc(pCond->numOfCols, sizeof(SDataStatis));
    if (pReadHandle->statis == NULL) {
439
      goto _end;
440
    }
H
Haojun Liao 已提交
441

442
    // todo: use list instead of array?
443 444
    pReadHandle->pColumns = taosArrayInit(pCond->numOfCols, sizeof(SColumnInfoData));
    if (pReadHandle->pColumns == NULL) {
445
      goto _end;
446
    }
H
Haojun Liao 已提交
447

448 449
    for (int32_t i = 0; i < pCond->numOfCols; ++i) {
      SColumnInfoData colInfo = {{0}, 0};
H
Haojun Liao 已提交
450

451
      colInfo.info = pCond->colList[i];
452
      colInfo.pData = calloc(1, EXTRA_BYTES + pReadHandle->outputCapacity * pCond->colList[i].bytes);
453
      if (colInfo.pData == NULL) {
454
        goto _end;
455
      }
456

457 458
      taosArrayPush(pReadHandle->pColumns, &colInfo);
      pReadHandle->statis[i].colId = colInfo.info.colId;
B
Bomin Zhang 已提交
459
    }
H
Haojun Liao 已提交
460

461
    pReadHandle->defaultLoadColumn = getDefaultLoadColumns(pReadHandle, true);
H
Haojun Liao 已提交
462
  }
463

464 465
//  STsdbMeta* pMeta = NULL;//tsdbGetMeta(tsdb);
//  assert(pMeta != NULL);
H
Haojun Liao 已提交
466

467 468 469
  pReadHandle->pDataCols = tdNewDataCols(1000, pReadHandle->pTsdb->config.maxRowsPerFileBlock);
  if (pReadHandle->pDataCols == NULL) {
    tsdbError("%p failed to malloc buf for pDataCols, %"PRIu64, pReadHandle, pReadHandle->qId);
H
Haojun Liao 已提交
470
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
471
    goto _end;
H
hjxilinx 已提交
472
  }
473

474 475
  tsdbInitDataBlockLoadInfo(&pReadHandle->dataBlockLoadInfo);
  tsdbInitCompBlockLoadInfo(&pReadHandle->compBlockLoadInfo);
476

477
  return (tsdbReadHandleT)pReadHandle;
478

479
  _end:
480
//  tsdbCleanupQueryHandle(pTsdbReadHandle);
481
  terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
482
  return NULL;
H
hjxilinx 已提交
483 484
}

485 486 487
tsdbReadHandleT* tsdbQueryTables(STsdb* tsdb, STsdbQueryCond* pCond, STableGroupInfo* groupList, uint64_t qId, void* pRef) {
  STsdbReadHandle* pTsdbReadHandle = tsdbQueryTablesImpl(tsdb, pCond, qId, pRef);
  if (pTsdbReadHandle == NULL) {
488 489 490
    return NULL;
  }

491 492
  if (emptyQueryTimewindow(pTsdbReadHandle)) {
    return (tsdbReadHandleT*) pTsdbReadHandle;
493
  }
H
Haojun Liao 已提交
494

D
fix bug  
dapan1121 已提交
495 496
  SArray* psTable = NULL;

H
Haojun Liao 已提交
497
  // todo apply the lastkey of table check to avoid to load header file
498 499 500
  pTsdbReadHandle->pTableCheckInfo = createCheckInfoFromTableGroup(pTsdbReadHandle, groupList, &psTable);
  if (pTsdbReadHandle->pTableCheckInfo == NULL) {
//    tsdbCleanupQueryHandle(pTsdbReadHandle);
H
Haojun Liao 已提交
501
    taosArrayDestroy(psTable);
H
Haojun Liao 已提交
502 503 504 505
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return NULL;
  }

506
//  tsdbMayTakeMemSnapshot(pTsdbReadHandle, psTable);
D
fix bug  
dapan1121 已提交
507

508 509
  tsdbDebug("%p total numOfTable:%" PRIzu " in query, 0x%"PRIx64, pTsdbReadHandle, taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo), pTsdbReadHandle->qId);
  return (tsdbReadHandleT) pTsdbReadHandle;
H
Haojun Liao 已提交
510 511
}

512 513
void tsdbResetQueryHandle(tsdbReadHandleT queryHandle, STsdbQueryCond *pCond) {
  STsdbReadHandle* pTsdbReadHandle = queryHandle;
H
Haojun Liao 已提交
514

515 516 517 518
  if (emptyQueryTimewindow(pTsdbReadHandle)) {
    if (pCond->order != pTsdbReadHandle->order) {
      pTsdbReadHandle->order = pCond->order;
      SWAP(pTsdbReadHandle->window.skey, pTsdbReadHandle->window.ekey, int64_t);
519 520 521 522 523
    }

    return;
  }

524 525 526 527 528 529 530 531 532
  pTsdbReadHandle->order       = pCond->order;
  pTsdbReadHandle->window      = pCond->twindow;
  pTsdbReadHandle->type        = TSDB_QUERY_TYPE_ALL;
  pTsdbReadHandle->cur.fid     = -1;
  pTsdbReadHandle->cur.win     = TSWINDOW_INITIALIZER;
  pTsdbReadHandle->checkFiles  = true;
  pTsdbReadHandle->activeIndex = 0;   // current active table index
  pTsdbReadHandle->locateStart = false;
  pTsdbReadHandle->loadExternalRow = pCond->loadExternalRows;
H
Haojun Liao 已提交
533 534

  if (ASCENDING_TRAVERSE(pCond->order)) {
535
    assert(pTsdbReadHandle->window.skey <= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
536
  } else {
537
    assert(pTsdbReadHandle->window.skey >= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
538 539 540
  }

  // allocate buffer in order to load data blocks from file
541
  memset(pTsdbReadHandle->statis, 0, sizeof(SDataStatis));
H
Haojun Liao 已提交
542

543 544
  tsdbInitDataBlockLoadInfo(&pTsdbReadHandle->dataBlockLoadInfo);
  tsdbInitCompBlockLoadInfo(&pTsdbReadHandle->compBlockLoadInfo);
H
Haojun Liao 已提交
545

546
  resetCheckInfo(pTsdbReadHandle);
H
Haojun Liao 已提交
547 548
}

549 550
void tsdbResetQueryHandleForNewTable(tsdbReadHandleT queryHandle, STsdbQueryCond *pCond, STableGroupInfo* groupList) {
  STsdbReadHandle* pTsdbReadHandle = queryHandle;
H
Haojun Liao 已提交
551

552 553 554 555 556 557 558 559 560
  pTsdbReadHandle->order       = pCond->order;
  pTsdbReadHandle->window      = pCond->twindow;
  pTsdbReadHandle->type        = TSDB_QUERY_TYPE_ALL;
  pTsdbReadHandle->cur.fid     = -1;
  pTsdbReadHandle->cur.win     = TSWINDOW_INITIALIZER;
  pTsdbReadHandle->checkFiles  = true;
  pTsdbReadHandle->activeIndex = 0;   // current active table index
  pTsdbReadHandle->locateStart = false;
  pTsdbReadHandle->loadExternalRow = pCond->loadExternalRows;
H
Haojun Liao 已提交
561 562

  if (ASCENDING_TRAVERSE(pCond->order)) {
563
    assert(pTsdbReadHandle->window.skey <= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
564
  } else {
565
    assert(pTsdbReadHandle->window.skey >= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
566 567 568
  }

  // allocate buffer in order to load data blocks from file
569
  memset(pTsdbReadHandle->statis, 0, sizeof(SDataStatis));
H
Haojun Liao 已提交
570

571 572
  tsdbInitDataBlockLoadInfo(&pTsdbReadHandle->dataBlockLoadInfo);
  tsdbInitCompBlockLoadInfo(&pTsdbReadHandle->compBlockLoadInfo);
H
Haojun Liao 已提交
573

H
Haojun Liao 已提交
574
  SArray* pTable = NULL;
575
//  STsdbMeta* pMeta = tsdbGetMeta(pTsdbReadHandle->pTsdb);
H
Haojun Liao 已提交
576

577
//  pTsdbReadHandle->pTableCheckInfo = destroyTableCheckInfo(pTsdbReadHandle->pTableCheckInfo);
H
Haojun Liao 已提交
578

579 580 581
  pTsdbReadHandle->pTableCheckInfo = NULL;//createCheckInfoFromTableGroup(pTsdbReadHandle, groupList, pMeta, &pTable);
  if (pTsdbReadHandle->pTableCheckInfo == NULL) {
//    tsdbCleanupQueryHandle(pTsdbReadHandle);
H
Haojun Liao 已提交
582 583
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
584

585 586
//  pTsdbReadHandle->prev = doFreeColumnInfoData(pTsdbReadHandle->prev);
//  pTsdbReadHandle->next = doFreeColumnInfoData(pTsdbReadHandle->next);
H
Haojun Liao 已提交
587 588
}

589
tsdbReadHandleT tsdbQueryLastRow(STsdb *tsdb, STsdbQueryCond *pCond, STableGroupInfo *groupList, uint64_t qId, STsdbMemTable* pMemRef) {
590
  pCond->twindow = updateLastrowForEachGroup(groupList);
H
Haojun Liao 已提交
591 592 593 594 595 596

  // no qualified table
  if (groupList->numOfTables == 0) {
    return NULL;
  }

597 598
  STsdbReadHandle *pTsdbReadHandle = (STsdbReadHandle*) tsdbQueryTables(tsdb, pCond, groupList, qId, pMemRef);
  if (pTsdbReadHandle == NULL) {
599 600 601
    return NULL;
  }

602
  int32_t code = checkForCachedLastRow(pTsdbReadHandle, groupList);
H
Haojun Liao 已提交
603 604 605 606
  if (code != TSDB_CODE_SUCCESS) { // set the numOfTables to be 0
    terrno = code;
    return NULL;
  }
H
Haojun Liao 已提交
607 608

  assert(pCond->order == TSDB_ORDER_ASC && pCond->twindow.skey <= pCond->twindow.ekey);
609 610
  if (pTsdbReadHandle->cachelastrow) {
    pTsdbReadHandle->type = TSDB_QUERY_TYPE_LAST;
D
init  
dapan1121 已提交
611 612
  }
  
613
  return pTsdbReadHandle;
D
init  
dapan1121 已提交
614 615
}

616 617 618 619
#if 0
tsdbReadHandleT tsdbQueryCacheLast(STsdb *tsdb, STsdbQueryCond *pCond, STableGroupInfo *groupList, uint64_t qId, STsdbMemTable* pMemRef) {
  STsdbReadHandle *pTsdbReadHandle = (STsdbReadHandle*) tsdbQueryTables(tsdb, pCond, groupList, qId, pMemRef);
  if (pTsdbReadHandle == NULL) {
620 621 622
    return NULL;
  }

623
  int32_t code = checkForCachedLast(pTsdbReadHandle);
D
init  
dapan1121 已提交
624 625 626 627 628
  if (code != TSDB_CODE_SUCCESS) { // set the numOfTables to be 0
    terrno = code;
    return NULL;
  }

629 630
  if (pTsdbReadHandle->cachelastrow) {
    pTsdbReadHandle->type = TSDB_QUERY_TYPE_LAST;
D
fix bug  
dapan1121 已提交
631
  }
D
init  
dapan1121 已提交
632
  
633
  return pTsdbReadHandle;
H
hjxilinx 已提交
634 635
}

636 637
#endif
SArray* tsdbGetQueriedTableList(tsdbReadHandleT *pHandle) {
638
  assert(pHandle != NULL);
H
Haojun Liao 已提交
639

640
  STsdbReadHandle *pTsdbReadHandle = (STsdbReadHandle*) pHandle;
H
Haojun Liao 已提交
641

642
  size_t size = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
643
  SArray* res = taosArrayInit(size, POINTER_BYTES);
H
Haojun Liao 已提交
644

645
  for(int32_t i = 0; i < size; ++i) {
646
    STableCheckInfo* pCheckInfo = taosArrayGet(pTsdbReadHandle->pTableCheckInfo, i);
647
    taosArrayPush(res, &pCheckInfo->pTableObj);
648
  }
H
Haojun Liao 已提交
649

650 651 652
  return res;
}

H
Haojun Liao 已提交
653 654 655 656 657 658
// leave only one table for each group
static STableGroupInfo* trimTableGroup(STimeWindow* window, STableGroupInfo* pGroupList) {
  assert(pGroupList);
  size_t numOfGroup = taosArrayGetSize(pGroupList->pGroupList);

  STableGroupInfo* pNew = calloc(1, sizeof(STableGroupInfo));
Y
yihaoDeng 已提交
659
  pNew->pGroupList = taosArrayInit(numOfGroup, POINTER_BYTES);
H
Haojun Liao 已提交
660 661 662 663 664 665 666 667

  for(int32_t i = 0; i < numOfGroup; ++i) {
    SArray* oneGroup = taosArrayGetP(pGroupList->pGroupList, i);
    size_t numOfTables = taosArrayGetSize(oneGroup);

    SArray* px = taosArrayInit(4, sizeof(STableKeyInfo));
    for (int32_t j = 0; j < numOfTables; ++j) {
      STableKeyInfo* pInfo = (STableKeyInfo*)taosArrayGet(oneGroup, j);
668 669 670 671 672
//      if (window->skey <= pInfo->lastKey && ((STable*)pInfo->pTable)->lastKey != TSKEY_INITIAL_VAL) {
//        taosArrayPush(px, pInfo);
//        pNew->numOfTables += 1;
//        break;
//      }
H
Haojun Liao 已提交
673 674 675 676 677 678 679 680 681 682 683 684 685
    }

    // there are no data in this group
    if (taosArrayGetSize(px) == 0) {
      taosArrayDestroy(px);
    } else {
      taosArrayPush(pNew->pGroupList, &px);
    }
  }

  return pNew;
}

686
tsdbReadHandleT tsdbQueryRowsInExternalWindow(STsdb *tsdb, STsdbQueryCond* pCond, STableGroupInfo *groupList, uint64_t qId, STsdbMemTable* pRef) {
H
Haojun Liao 已提交
687 688
  STableGroupInfo* pNew = trimTableGroup(&pCond->twindow, groupList);

689 690 691 692 693 694 695 696 697 698 699 700
  if (pNew->numOfTables == 0) {
    tsdbDebug("update query time range to invalidate time window");

    assert(taosArrayGetSize(pNew->pGroupList) == 0);
    bool asc = ASCENDING_TRAVERSE(pCond->order);
    if (asc) {
      pCond->twindow.ekey = pCond->twindow.skey - 1;
    } else {
      pCond->twindow.skey = pCond->twindow.ekey - 1;
    }
  }

701 702 703
  STsdbReadHandle *pTsdbReadHandle = (STsdbReadHandle*) tsdbQueryTables(tsdb, pCond, pNew, qId, pRef);
  pTsdbReadHandle->loadExternalRow = true;
  pTsdbReadHandle->currentLoadExternalRows = true;
704

705
  return pTsdbReadHandle;
706 707
}

708
static bool initTableMemIterator(STsdbReadHandle* pHandle, STableCheckInfo* pCheckInfo) {
709
  if (pCheckInfo->initBuf) {
710 711
    return true;
  }
H
Haojun Liao 已提交
712

713
  pCheckInfo->initBuf = true;
714
  int32_t order = pHandle->order;
H
Haojun Liao 已提交
715

716 717 718 719 720 721 722
  STbData** pMem = NULL;
  STbData** pIMem = NULL;

  TKEY tLastKey = 0;  /// keyToTkey(pCheckInfo->lastKey);
  if (pHandle->pTsdb->mem != NULL) {
    pMem = taosHashGet(pHandle->pTsdb->mem->pHashIdx, &pCheckInfo->tableId, sizeof(pCheckInfo->tableId));
    if (pMem != NULL) {
H
Haojun Liao 已提交
723
      pCheckInfo->iter =
724
          tSkipListCreateIterFromVal((*pMem)->pData, (const char*)&tLastKey, TSDB_DATA_TYPE_TIMESTAMP, order);
H
Haojun Liao 已提交
725
    }
726
  }
H
Haojun Liao 已提交
727

728 729 730
  if (pHandle->pTsdb->imem != NULL) {
    pIMem = taosHashGet(pHandle->pTsdb->imem->pHashIdx, &pCheckInfo->tableId, sizeof(pCheckInfo->tableId));
    if (pIMem != NULL) {
H
Haojun Liao 已提交
731
      pCheckInfo->iiter =
732
          tSkipListCreateIterFromVal((*pIMem)->pData, (const char*)&tLastKey, TSDB_DATA_TYPE_TIMESTAMP, order);
H
Haojun Liao 已提交
733
    }
734
  }
H
Haojun Liao 已提交
735

736 737 738 739
  // both iterators are NULL, no data in buffer right now
  if (pCheckInfo->iter == NULL && pCheckInfo->iiter == NULL) {
    return false;
  }
H
Haojun Liao 已提交
740

741 742 743 744 745
  bool memEmpty  = (pCheckInfo->iter == NULL) || (pCheckInfo->iter != NULL && !tSkipListIterNext(pCheckInfo->iter));
  bool imemEmpty = (pCheckInfo->iiter == NULL) || (pCheckInfo->iiter != NULL && !tSkipListIterNext(pCheckInfo->iiter));
  if (memEmpty && imemEmpty) { // buffer is empty
    return false;
  }
H
Haojun Liao 已提交
746

747 748 749
  if (!memEmpty) {
    SSkipListNode* node = tSkipListIterGet(pCheckInfo->iter);
    assert(node != NULL);
H
Haojun Liao 已提交
750

C
Cary Xu 已提交
751 752
    SMemRow row = (SMemRow)SL_GET_NODE_DATA(node);
    TSKEY   key = memRowKey(row);  // first timestamp in buffer
753
    tsdbDebug("%p uid:%" PRId64 ", check data in mem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
H
Haojun Liao 已提交
754
              "-%" PRId64 ", lastKey:%" PRId64 ", numOfRows:%"PRId64", 0x%"PRIx64,
755
              pHandle, pCheckInfo->tableId, key, order, (*pMem)->keyMin, (*pMem)->keyMax, pCheckInfo->lastKey, (*pMem)->nrows, pHandle->qId);
H
Haojun Liao 已提交
756 757 758 759 760 761 762

    if (ASCENDING_TRAVERSE(order)) {
      assert(pCheckInfo->lastKey <= key);
    } else {
      assert(pCheckInfo->lastKey >= key);
    }

763
  } else {
764
    tsdbDebug("%p uid:%"PRId64", no data in mem, 0x%"PRIx64, pHandle, pCheckInfo->tableId, pHandle->qId);
765
  }
H
Haojun Liao 已提交
766

767 768 769
  if (!imemEmpty) {
    SSkipListNode* node = tSkipListIterGet(pCheckInfo->iiter);
    assert(node != NULL);
H
Haojun Liao 已提交
770

C
Cary Xu 已提交
771 772
    SMemRow row = (SMemRow)SL_GET_NODE_DATA(node);
    TSKEY   key = memRowKey(row);  // first timestamp in buffer
773
    tsdbDebug("%p uid:%" PRId64 ", check data in imem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
H
Haojun Liao 已提交
774
              "-%" PRId64 ", lastKey:%" PRId64 ", numOfRows:%"PRId64", 0x%"PRIx64,
775
              pHandle, pCheckInfo->tableId, key, order, (*pIMem)->keyMin, (*pIMem)->keyMax, pCheckInfo->lastKey, (*pIMem)->nrows, pHandle->qId);
H
Haojun Liao 已提交
776 777 778 779 780 781

    if (ASCENDING_TRAVERSE(order)) {
      assert(pCheckInfo->lastKey <= key);
    } else {
      assert(pCheckInfo->lastKey >= key);
    }
782
  } else {
H
Haojun Liao 已提交
783
    tsdbDebug("%p uid:%"PRId64", no data in imem, 0x%"PRIx64, pHandle, pCheckInfo->tableId, pHandle->qId);
784
  }
H
Haojun Liao 已提交
785

786 787 788
  return true;
}

H
Haojun Liao 已提交
789 790 791 792 793
static void destroyTableMemIterator(STableCheckInfo* pCheckInfo) {
  tSkipListDestroyIter(pCheckInfo->iter);
  tSkipListDestroyIter(pCheckInfo->iiter);
}

794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
static TSKEY extractFirstTraverseKey(STableCheckInfo* pCheckInfo, int32_t order, int32_t update) {
  SMemRow rmem = NULL, rimem = NULL;
  if (pCheckInfo->iter) {
    SSkipListNode* node = tSkipListIterGet(pCheckInfo->iter);
    if (node != NULL) {
      rmem = (SMemRow)SL_GET_NODE_DATA(node);
    }
  }

  if (pCheckInfo->iiter) {
    SSkipListNode* node = tSkipListIterGet(pCheckInfo->iiter);
    if (node != NULL) {
      rimem = (SMemRow)SL_GET_NODE_DATA(node);
    }
  }

  if (rmem == NULL && rimem == NULL) {
    return TSKEY_INITIAL_VAL;
  }

  if (rmem != NULL && rimem == NULL) {
    pCheckInfo->chosen = CHECKINFO_CHOSEN_MEM;
    return memRowKey(rmem);
  }

  if (rmem == NULL && rimem != NULL) {
    pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
    return memRowKey(rimem);
  }

  TSKEY r1 = memRowKey(rmem);
  TSKEY r2 = memRowKey(rimem);

  if (r1 == r2) {
    if(update == TD_ROW_DISCARD_UPDATE){
      pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
      tSkipListIterNext(pCheckInfo->iter);
    }
    else if(update == TD_ROW_OVERWRITE_UPDATE) {
      pCheckInfo->chosen = CHECKINFO_CHOSEN_MEM;
      tSkipListIterNext(pCheckInfo->iiter);
    } else {
      pCheckInfo->chosen = CHECKINFO_CHOSEN_BOTH;
    }
    return r1;
  } else if (r1 < r2 && ASCENDING_TRAVERSE(order)) {
    pCheckInfo->chosen = CHECKINFO_CHOSEN_MEM;
    return r1;
  }
  else {
    pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
    return r2;
  }
}

static SMemRow getSMemRowInTableMem(STableCheckInfo* pCheckInfo, int32_t order, int32_t update, SMemRow* extraRow) {
C
Cary Xu 已提交
850
  SMemRow rmem = NULL, rimem = NULL;
H
Haojun Liao 已提交
851 852 853
  if (pCheckInfo->iter) {
    SSkipListNode* node = tSkipListIterGet(pCheckInfo->iter);
    if (node != NULL) {
C
Cary Xu 已提交
854
      rmem = (SMemRow)SL_GET_NODE_DATA(node);
H
Haojun Liao 已提交
855 856
    }
  }
857

H
Haojun Liao 已提交
858 859 860
  if (pCheckInfo->iiter) {
    SSkipListNode* node = tSkipListIterGet(pCheckInfo->iiter);
    if (node != NULL) {
C
Cary Xu 已提交
861
      rimem = (SMemRow)SL_GET_NODE_DATA(node);
H
Haojun Liao 已提交
862 863
    }
  }
864

H
Haojun Liao 已提交
865 866
  if (rmem == NULL && rimem == NULL) {
    return NULL;
H
Haojun Liao 已提交
867
  }
868

H
Haojun Liao 已提交
869
  if (rmem != NULL && rimem == NULL) {
H
Haojun Liao 已提交
870 871 872
    pCheckInfo->chosen = 0;
    return rmem;
  }
873

H
Haojun Liao 已提交
874
  if (rmem == NULL && rimem != NULL) {
H
Haojun Liao 已提交
875 876 877
    pCheckInfo->chosen = 1;
    return rimem;
  }
878

C
Cary Xu 已提交
879 880
  TSKEY r1 = memRowKey(rmem);
  TSKEY r2 = memRowKey(rimem);
H
Haojun Liao 已提交
881

882 883
  if (r1 == r2) {
    if (update == TD_ROW_DISCARD_UPDATE) {
H
TD-1439  
Hongze Cheng 已提交
884
      tSkipListIterNext(pCheckInfo->iter);
885
      pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
H
TD-1439  
Hongze Cheng 已提交
886
      return rimem;
887
    } else if(update == TD_ROW_OVERWRITE_UPDATE){
H
TD-1439  
Hongze Cheng 已提交
888
      tSkipListIterNext(pCheckInfo->iiter);
889 890 891 892 893
      pCheckInfo->chosen = CHECKINFO_CHOSEN_MEM;
      return rmem;
    } else {
      pCheckInfo->chosen = CHECKINFO_CHOSEN_BOTH;
      extraRow = rimem;
H
TD-1439  
Hongze Cheng 已提交
894 895
      return rmem;
    }
H
Haojun Liao 已提交
896 897 898
  } else {
    if (ASCENDING_TRAVERSE(order)) {
      if (r1 < r2) {
899
        pCheckInfo->chosen = CHECKINFO_CHOSEN_MEM;
H
Haojun Liao 已提交
900 901
        return rmem;
      } else {
902
        pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
H
Haojun Liao 已提交
903 904 905 906
        return rimem;
      }
    } else {
      if (r1 < r2) {
907
        pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
H
Haojun Liao 已提交
908 909
        return rimem;
      } else {
910
        pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
H
Haojun Liao 已提交
911 912 913 914
        return rmem;
      }
    }
  }
H
Haojun Liao 已提交
915 916
}

917
static bool moveToNextRowInMem(STableCheckInfo* pCheckInfo) {
H
Haojun Liao 已提交
918
  bool hasNext = false;
919
  if (pCheckInfo->chosen == CHECKINFO_CHOSEN_MEM) {
H
Haojun Liao 已提交
920 921 922
    if (pCheckInfo->iter != NULL) {
      hasNext = tSkipListIterNext(pCheckInfo->iter);
    }
923

H
Haojun Liao 已提交
924 925 926
    if (hasNext) {
      return hasNext;
    }
927

H
Haojun Liao 已提交
928 929 930
    if (pCheckInfo->iiter != NULL) {
      return tSkipListIterGet(pCheckInfo->iiter) != NULL;
    }
931
  } else if (pCheckInfo->chosen == CHECKINFO_CHOSEN_IMEM){
932 933 934
    if (pCheckInfo->iiter != NULL) {
      hasNext = tSkipListIterNext(pCheckInfo->iiter);
    }
935

936 937 938
    if (hasNext) {
      return hasNext;
    }
939

940 941
    if (pCheckInfo->iter != NULL) {
      return tSkipListIterGet(pCheckInfo->iter) != NULL;
H
Haojun Liao 已提交
942
    }
943 944 945 946 947 948 949
  } else {
    if (pCheckInfo->iter != NULL) {
      hasNext = tSkipListIterNext(pCheckInfo->iter);
    }
    if (pCheckInfo->iiter != NULL) {
      hasNext = tSkipListIterNext(pCheckInfo->iiter) || hasNext;
    }
H
Haojun Liao 已提交
950
  }
951

H
Haojun Liao 已提交
952 953 954
  return hasNext;
}

955
static bool hasMoreDataInCache(STsdbReadHandle* pHandle) {
H
TD-1439  
Hongze Cheng 已提交
956
  STsdbCfg *pCfg = &pHandle->pTsdb->config;
957 958
  size_t size = taosArrayGetSize(pHandle->pTableCheckInfo);
  assert(pHandle->activeIndex < size && pHandle->activeIndex >= 0 && size >= 1);
D
dapan1121 已提交
959
  pHandle->cur.fid = INT32_MIN;
H
Haojun Liao 已提交
960

961
  STableCheckInfo* pCheckInfo = taosArrayGet(pHandle->pTableCheckInfo, pHandle->activeIndex);
H
Haojun Liao 已提交
962 963 964 965
  if (!pCheckInfo->initBuf) {
    initTableMemIterator(pHandle, pCheckInfo);
  }

966
  SMemRow row = getSMemRowInTableMem(pCheckInfo, pHandle->order, pCfg->update, NULL);
H
Haojun Liao 已提交
967
  if (row == NULL) {
968 969
    return false;
  }
970

C
Cary Xu 已提交
971
  pCheckInfo->lastKey = memRowKey(row);  // first timestamp in buffer
972 973
  tsdbDebug("%p uid:%" PRId64", check data in buffer from skey:%" PRId64 ", order:%d, 0x%"PRIx64, pHandle,
      pCheckInfo->tableId,  pCheckInfo->lastKey, pHandle->order, pHandle->qId);
H
Haojun Liao 已提交
974

975
  // all data in mem are checked already.
976 977
  if ((pCheckInfo->lastKey > pHandle->window.ekey && ASCENDING_TRAVERSE(pHandle->order)) ||
      (pCheckInfo->lastKey < pHandle->window.ekey && !ASCENDING_TRAVERSE(pHandle->order))) {
978 979
    return false;
  }
H
Haojun Liao 已提交
980

981 982
  int32_t step = ASCENDING_TRAVERSE(pHandle->order)? 1:-1;
  STimeWindow* win = &pHandle->cur.win;
H
Haojun Liao 已提交
983
  pHandle->cur.rows = tsdbReadRowsFromCache(pCheckInfo, pHandle->window.ekey, pHandle->outputCapacity, win, pHandle);
H
Haojun Liao 已提交
984

985 986 987 988
  // update the last key value
  pCheckInfo->lastKey = win->ekey + step;
  pHandle->cur.lastKey = win->ekey + step;
  pHandle->cur.mixBlock = true;
989

990 991 992
  if (!ASCENDING_TRAVERSE(pHandle->order)) {
    SWAP(win->skey, win->ekey, TSKEY);
  }
H
Haojun Liao 已提交
993

994
  return true;
995
}
H
hjxilinx 已提交
996

997 998
static int32_t getFileIdFromKey(TSKEY key, int32_t daysPerFile, int32_t precision) {
  assert(precision >= TSDB_TIME_PRECISION_MICRO || precision <= TSDB_TIME_PRECISION_NANO);
999 1000 1001
  if (key == TSKEY_INITIAL_VAL) {
    return INT32_MIN;
  }
H
Haojun Liao 已提交
1002

D
dapan1121 已提交
1003
  if (key < 0) {
1004
    key -= (daysPerFile * tsTickPerDay[precision]);
D
dapan1121 已提交
1005 1006
  }
  
1007
  int64_t fid = (int64_t)(key / (daysPerFile * tsTickPerDay[precision]));  // set the starting fileId
1008 1009 1010
  if (fid < 0L && llabs(fid) > INT32_MAX) { // data value overflow for INT32
    fid = INT32_MIN;
  }
H
Haojun Liao 已提交
1011

1012
  if (fid > 0L && fid > INT32_MAX) {
1013 1014
    fid = INT32_MAX;
  }
H
Haojun Liao 已提交
1015

S
TD-1057  
Shengliang Guan 已提交
1016
  return (int32_t)fid;
1017 1018
}

H
refact  
Hongze Cheng 已提交
1019
static int32_t binarySearchForBlock(SBlock* pBlock, int32_t numOfBlocks, TSKEY skey, int32_t order) {
1020 1021
  int32_t firstSlot = 0;
  int32_t lastSlot = numOfBlocks - 1;
H
Haojun Liao 已提交
1022

1023
  int32_t midSlot = firstSlot;
H
Haojun Liao 已提交
1024

1025 1026 1027
  while (1) {
    numOfBlocks = lastSlot - firstSlot + 1;
    midSlot = (firstSlot + (numOfBlocks >> 1));
H
Haojun Liao 已提交
1028

1029
    if (numOfBlocks == 1) break;
H
Haojun Liao 已提交
1030

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
    if (skey > pBlock[midSlot].keyLast) {
      if (numOfBlocks == 2) break;
      if ((order == TSDB_ORDER_DESC) && (skey < pBlock[midSlot + 1].keyFirst)) break;
      firstSlot = midSlot + 1;
    } else if (skey < pBlock[midSlot].keyFirst) {
      if ((order == TSDB_ORDER_ASC) && (skey > pBlock[midSlot - 1].keyLast)) break;
      lastSlot = midSlot - 1;
    } else {
      break;  // got the slot
    }
  }
H
Haojun Liao 已提交
1042

1043 1044
  return midSlot;
}
1045

1046
static int32_t loadBlockInfo(STsdbReadHandle * pTsdbReadHandle, int32_t index, int32_t* numOfBlocks) {
H
Haojun Liao 已提交
1047
  int32_t code = 0;
H
Haojun Liao 已提交
1048

1049
  STableCheckInfo* pCheckInfo = taosArrayGet(pTsdbReadHandle->pTableCheckInfo, index);
H
Haojun Liao 已提交
1050
  pCheckInfo->numOfBlocks = 0;
1051

1052
  if (tsdbSetReadTable(&pTsdbReadHandle->rhelper, pCheckInfo->pTableObj) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1053 1054 1055
    code = terrno;
    return code;
  }
1056

1057
  SBlockIdx* compIndex = pTsdbReadHandle->rhelper.pBlkIdx;
H
Hongze Cheng 已提交
1058

H
Haojun Liao 已提交
1059
  // no data block in this file, try next file
1060
  if (compIndex == NULL || compIndex->uid != pCheckInfo->tableId) {
H
Haojun Liao 已提交
1061 1062
    return 0;  // no data blocks in the file belongs to pCheckInfo->pTable
  }
1063

H
Haojun Liao 已提交
1064 1065 1066 1067 1068 1069 1070 1071
  if (pCheckInfo->compSize < (int32_t)compIndex->len) {
    assert(compIndex->len > 0);

    char* t = realloc(pCheckInfo->pCompInfo, compIndex->len);
    if (t == NULL) {
      terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
      code = TSDB_CODE_TDB_OUT_OF_MEMORY;
      return code;
1072 1073
    }

H
Haojun Liao 已提交
1074 1075 1076
    pCheckInfo->pCompInfo = (SBlockInfo*)t;
    pCheckInfo->compSize = compIndex->len;
  }
1077

1078
  if (tsdbLoadBlockInfo(&(pTsdbReadHandle->rhelper), (void*)(pCheckInfo->pCompInfo)) < 0) {
H
Hongze Cheng 已提交
1079 1080
    return terrno;
  }
H
Haojun Liao 已提交
1081
  SBlockInfo* pCompInfo = pCheckInfo->pCompInfo;
1082

H
Haojun Liao 已提交
1083
  TSKEY s = TSKEY_INITIAL_VAL, e = TSKEY_INITIAL_VAL;
1084

1085 1086
  if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
    assert(pCheckInfo->lastKey <= pTsdbReadHandle->window.ekey && pTsdbReadHandle->window.skey <= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
1087
  } else {
1088
    assert(pCheckInfo->lastKey >= pTsdbReadHandle->window.ekey && pTsdbReadHandle->window.skey >= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
1089
  }
1090

1091 1092
  s = MIN(pCheckInfo->lastKey, pTsdbReadHandle->window.ekey);
  e = MAX(pCheckInfo->lastKey, pTsdbReadHandle->window.ekey);
1093

H
Haojun Liao 已提交
1094 1095 1096
  // discard the unqualified data block based on the query time window
  int32_t start = binarySearchForBlock(pCompInfo->blocks, compIndex->numOfBlocks, s, TSDB_ORDER_ASC);
  int32_t end = start;
H
TD-100  
hzcheng 已提交
1097

H
Haojun Liao 已提交
1098 1099 1100
  if (s > pCompInfo->blocks[start].keyLast) {
    return 0;
  }
1101

H
Haojun Liao 已提交
1102 1103 1104 1105
  // todo speedup the procedure of located end block
  while (end < (int32_t)compIndex->numOfBlocks && (pCompInfo->blocks[end].keyFirst <= e)) {
    end += 1;
  }
1106

H
Haojun Liao 已提交
1107
  pCheckInfo->numOfBlocks = (end - start);
1108

H
Haojun Liao 已提交
1109 1110 1111
  if (start > 0) {
    memmove(pCompInfo->blocks, &pCompInfo->blocks[start], pCheckInfo->numOfBlocks * sizeof(SBlock));
  }
1112

H
Haojun Liao 已提交
1113 1114 1115
  (*numOfBlocks) += pCheckInfo->numOfBlocks;
  return 0;
}
1116

1117
static int32_t getFileCompInfo(STsdbReadHandle* pTsdbReadHandle, int32_t* numOfBlocks) {
H
Haojun Liao 已提交
1118 1119 1120 1121
  // load all the comp offset value for all tables in this file
  int32_t code = TSDB_CODE_SUCCESS;
  *numOfBlocks = 0;

1122
  pTsdbReadHandle->cost.headFileLoad += 1;
1123 1124
  int64_t s = taosGetTimestampUs();

H
Haojun Liao 已提交
1125
  size_t numOfTables = 0;
1126 1127 1128 1129
  if (pTsdbReadHandle->loadType == BLOCK_LOAD_TABLE_SEQ_ORDER) {
    code = loadBlockInfo(pTsdbReadHandle, pTsdbReadHandle->activeIndex, numOfBlocks);
  } else if (pTsdbReadHandle->loadType == BLOCK_LOAD_OFFSET_SEQ_ORDER) {
    numOfTables = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
1130

H
Haojun Liao 已提交
1131
    for (int32_t i = 0; i < numOfTables; ++i) {
1132
      code = loadBlockInfo(pTsdbReadHandle, i, numOfBlocks);
H
Haojun Liao 已提交
1133
      if (code != TSDB_CODE_SUCCESS) {
1134 1135
        int64_t e = taosGetTimestampUs();

1136
        pTsdbReadHandle->cost.headFileLoadTime += (e - s);
H
Haojun Liao 已提交
1137 1138 1139 1140 1141
        return code;
      }
    }
  } else {
    assert(0);
1142
  }
1143

1144
  int64_t e = taosGetTimestampUs();
1145
  pTsdbReadHandle->cost.headFileLoadTime += (e - s);
H
Haojun Liao 已提交
1146
  return code;
1147 1148
}

1149
static int32_t doLoadFileDataBlock(STsdbReadHandle* pTsdbReadHandle, SBlock* pBlock, STableCheckInfo* pCheckInfo, int32_t slotIndex) {
H
Haojun Liao 已提交
1150
  int64_t st = taosGetTimestampUs();
1151

1152 1153
  STSchema *pSchema = NULL;//tsdbGetTableSchema(pCheckInfo->pTableObj);
  int32_t   code = tdInitDataCols(pTsdbReadHandle->pDataCols, pSchema);
H
Haojun Liao 已提交
1154
  if (code != TSDB_CODE_SUCCESS) {
1155
    tsdbError("%p failed to malloc buf for pDataCols, 0x%"PRIx64, pTsdbReadHandle, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
1156 1157 1158 1159
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _error;
  }

1160
  code = tdInitDataCols(pTsdbReadHandle->rhelper.pDCols[0], pSchema);
H
Haojun Liao 已提交
1161
  if (code != TSDB_CODE_SUCCESS) {
1162
    tsdbError("%p failed to malloc buf for rhelper.pDataCols[0], 0x%"PRIx64, pTsdbReadHandle, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
1163 1164 1165 1166
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _error;
  }

1167
  code = tdInitDataCols(pTsdbReadHandle->rhelper.pDCols[1], pSchema);
H
Haojun Liao 已提交
1168
  if (code != TSDB_CODE_SUCCESS) {
1169
    tsdbError("%p failed to malloc buf for rhelper.pDataCols[1], 0x%"PRIx64, pTsdbReadHandle, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
1170 1171 1172
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _error;
  }
1173

1174
  int16_t* colIds = pTsdbReadHandle->defaultLoadColumn->pData;
H
Haojun Liao 已提交
1175

1176
  int32_t ret = tsdbLoadBlockDataCols(&(pTsdbReadHandle->rhelper), pBlock, pCheckInfo->pCompInfo, colIds, (int)(QH_GET_NUM_OF_COLS(pTsdbReadHandle)));
H
Haojun Liao 已提交
1177
  if (ret != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1178 1179 1180
    int32_t c = terrno;
    assert(c != TSDB_CODE_SUCCESS);
    goto _error;
H
Haojun Liao 已提交
1181
  }
1182

1183
  SDataBlockLoadInfo* pBlockLoadInfo = &pTsdbReadHandle->dataBlockLoadInfo;
1184

1185 1186 1187
  pBlockLoadInfo->fileGroup = pTsdbReadHandle->pFileGroup;
  pBlockLoadInfo->slot = pTsdbReadHandle->cur.slot;
  pBlockLoadInfo->uid = pCheckInfo->pTableObj->uid;
1188

1189
  SDataCols* pCols = pTsdbReadHandle->rhelper.pDCols[0];
1190
  assert(pCols->numOfRows != 0 && pCols->numOfRows <= pBlock->numOfRows);
1191

1192
  pBlock->numOfRows = pCols->numOfRows;
H
Haojun Liao 已提交
1193

1194
  // Convert from TKEY to TSKEY for primary timestamp column if current block has timestamp before 1970-01-01T00:00:00Z
1195
  if(pBlock->keyFirst < 0 && colIds[0] == PRIMARYKEY_TIMESTAMP_COL_ID) {
1196 1197 1198 1199 1200 1201
    int64_t* src = pCols->cols[0].pData;
    for(int32_t i = 0; i < pBlock->numOfRows; ++i) {
      src[i] = tdGetKey(src[i]);
    }
  }

H
Haojun Liao 已提交
1202
  int64_t elapsedTime = (taosGetTimestampUs() - st);
1203
  pTsdbReadHandle->cost.blockLoadTime += elapsedTime;
1204

H
Haojun Liao 已提交
1205
  tsdbDebug("%p load file block into buffer, index:%d, brange:%"PRId64"-%"PRId64", rows:%d, elapsed time:%"PRId64 " us, 0x%"PRIx64,
1206
      pTsdbReadHandle, slotIndex, pBlock->keyFirst, pBlock->keyLast, pBlock->numOfRows, elapsedTime, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
1207
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1208 1209 1210 1211

_error:
  pBlock->numOfRows = 0;

H
Haojun Liao 已提交
1212
  tsdbError("%p error occurs in loading file block, index:%d, brange:%"PRId64"-%"PRId64", rows:%d, 0x%"PRIx64,
1213
            pTsdbReadHandle, slotIndex, pBlock->keyFirst, pBlock->keyLast, pBlock->numOfRows, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
1214
  return terrno;
H
hjxilinx 已提交
1215 1216
}

1217 1218 1219 1220 1221
static int32_t getEndPosInDataBlock(STsdbReadHandle* pTsdbReadHandle, SDataBlockInfo* pBlockInfo);
static int32_t doCopyRowsFromFileBlock(STsdbReadHandle* pTsdbReadHandle, int32_t capacity, int32_t numOfRows, int32_t start, int32_t end);
static void moveDataToFront(STsdbReadHandle* pTsdbReadHandle, int32_t numOfRows, int32_t numOfCols);
static void doCheckGeneratedBlockRange(STsdbReadHandle* pTsdbReadHandle);
static void copyAllRemainRowsFromFileBlock(STsdbReadHandle* pTsdbReadHandle, STableCheckInfo* pCheckInfo, SDataBlockInfo* pBlockInfo, int32_t endPos);
1222

1223 1224 1225
static int32_t handleDataMergeIfNeeded(STsdbReadHandle* pTsdbReadHandle, SBlock* pBlock, STableCheckInfo* pCheckInfo){
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
  STsdbCfg*      pCfg = &pTsdbReadHandle->pTsdb->config;
H
Haojun Liao 已提交
1226
  SDataBlockInfo binfo = GET_FILE_DATA_BLOCK_INFO(pCheckInfo, pBlock);
1227
  TSKEY          key;
H
Haojun Liao 已提交
1228
  int32_t code = TSDB_CODE_SUCCESS;
1229

1230
  /*bool hasData = */ initTableMemIterator(pTsdbReadHandle, pCheckInfo);
H
Haojun Liao 已提交
1231 1232
  assert(cur->pos >= 0 && cur->pos <= binfo.rows);

1233
  key = extractFirstTraverseKey(pCheckInfo, pTsdbReadHandle->order, pCfg->update);
1234

H
Haojun Liao 已提交
1235
  if (key != TSKEY_INITIAL_VAL) {
1236
    tsdbDebug("%p key in mem:%"PRId64", 0x%"PRIx64, pTsdbReadHandle, key, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
1237
  } else {
1238
    tsdbDebug("%p no data in mem, 0x%"PRIx64, pTsdbReadHandle, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
1239
  }
H
Haojun Liao 已提交
1240

1241 1242
  if ((ASCENDING_TRAVERSE(pTsdbReadHandle->order) && (key != TSKEY_INITIAL_VAL && key <= binfo.window.ekey)) ||
      (!ASCENDING_TRAVERSE(pTsdbReadHandle->order) && (key != TSKEY_INITIAL_VAL && key >= binfo.window.skey))) {
H
Haojun Liao 已提交
1243

1244 1245
    if ((ASCENDING_TRAVERSE(pTsdbReadHandle->order) && (key != TSKEY_INITIAL_VAL && key < binfo.window.skey)) ||
        (!ASCENDING_TRAVERSE(pTsdbReadHandle->order) && (key != TSKEY_INITIAL_VAL && key > binfo.window.ekey))) {
1246

H
Haojun Liao 已提交
1247
      // do not load file block into buffer
1248
      int32_t step = ASCENDING_TRAVERSE(pTsdbReadHandle->order) ? 1 : -1;
H
Haojun Liao 已提交
1249

1250 1251 1252
      TSKEY maxKey = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? (binfo.window.skey - step):(binfo.window.ekey - step);
      cur->rows = tsdbReadRowsFromCache(pCheckInfo, maxKey, pTsdbReadHandle->outputCapacity, &cur->win, pTsdbReadHandle);
      pTsdbReadHandle->realNumOfRows = cur->rows;
H
Haojun Liao 已提交
1253 1254 1255

      // update the last key value
      pCheckInfo->lastKey = cur->win.ekey + step;
1256
      if (!ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
H
Haojun Liao 已提交
1257 1258
        SWAP(cur->win.skey, cur->win.ekey, TSKEY);
      }
H
Haojun Liao 已提交
1259

H
Haojun Liao 已提交
1260 1261
      cur->mixBlock = true;
      cur->blockCompleted = false;
H
Haojun Liao 已提交
1262
      return code;
H
Haojun Liao 已提交
1263
    }
H
Haojun Liao 已提交
1264

1265

1266
    // return error, add test cases
1267
    if ((code = doLoadFileDataBlock(pTsdbReadHandle, pBlock, pCheckInfo, cur->slot)) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1268
      return code;
1269 1270
    }

1271
    doMergeTwoLevelData(pTsdbReadHandle, pCheckInfo, pBlock);
1272
  } else {
1273 1274 1275 1276 1277 1278
    /*
     * no data in cache, only load data from file
     * during the query processing, data in cache will not be checked anymore.
     *
     * Here the buffer is not enough, so only part of file block can be loaded into memory buffer
     */
1279 1280
    assert(pTsdbReadHandle->outputCapacity >= binfo.rows);
    int32_t endPos = getEndPosInDataBlock(pTsdbReadHandle, &binfo);
1281

1282 1283 1284
    if ((cur->pos == 0 && endPos == binfo.rows -1 && ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
        (cur->pos == (binfo.rows - 1) && endPos == 0 && (!ASCENDING_TRAVERSE(pTsdbReadHandle->order)))) {
      pTsdbReadHandle->realNumOfRows = binfo.rows;
1285 1286 1287 1288

      cur->rows = binfo.rows;
      cur->win  = binfo.window;
      cur->mixBlock = false;
H
Haojun Liao 已提交
1289 1290
      cur->blockCompleted = true;

1291
      if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
H
Haojun Liao 已提交
1292 1293 1294 1295 1296 1297
        cur->lastKey = binfo.window.ekey + 1;
        cur->pos = binfo.rows;
      } else {
        cur->lastKey = binfo.window.skey - 1;
        cur->pos = -1;
      }
H
Haojun Liao 已提交
1298
    } else { // partially copy to dest buffer
1299
      copyAllRemainRowsFromFileBlock(pTsdbReadHandle, pCheckInfo, &binfo, endPos);
1300 1301
      cur->mixBlock = true;
    }
1302

H
Haojun Liao 已提交
1303
    assert(cur->blockCompleted);
H
Haojun Liao 已提交
1304 1305
    if (cur->rows == binfo.rows) {
      tsdbDebug("%p whole file block qualified, brange:%"PRId64"-%"PRId64", rows:%d, lastKey:%"PRId64", %"PRIx64,
1306
                pTsdbReadHandle, cur->win.skey, cur->win.ekey, cur->rows, cur->lastKey, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
1307 1308
    } else {
      tsdbDebug("%p create data block from remain file block, brange:%"PRId64"-%"PRId64", rows:%d, total:%d, lastKey:%"PRId64", %"PRIx64,
1309
                pTsdbReadHandle, cur->win.skey, cur->win.ekey, cur->rows, binfo.rows, cur->lastKey, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
1310 1311
    }

1312
  }
H
Haojun Liao 已提交
1313 1314

  return code;
1315 1316
}

1317 1318
static int32_t loadFileDataBlock(STsdbReadHandle* pTsdbReadHandle, SBlock* pBlock, STableCheckInfo* pCheckInfo, bool* exists) {
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
H
Haojun Liao 已提交
1319
  int32_t code = TSDB_CODE_SUCCESS;
1320
  bool asc = ASCENDING_TRAVERSE(pTsdbReadHandle->order);
1321

1322
  if (asc) {
H
Haojun Liao 已提交
1323
    // query ended in/started from current block
1324 1325
    if (pTsdbReadHandle->window.ekey < pBlock->keyLast || pCheckInfo->lastKey > pBlock->keyFirst) {
      if ((code = doLoadFileDataBlock(pTsdbReadHandle, pBlock, pCheckInfo, cur->slot)) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1326 1327
        *exists = false;
        return code;
1328
      }
1329

1330
      SDataCols* pTSCol = pTsdbReadHandle->rhelper.pDCols[0];
H
Haojun Liao 已提交
1331
      assert(pTSCol->cols->type == TSDB_DATA_TYPE_TIMESTAMP && pTSCol->numOfRows == pBlock->numOfRows);
H
Haojun Liao 已提交
1332

1333 1334
      if (pCheckInfo->lastKey > pBlock->keyFirst) {
        cur->pos =
1335
            binarySearchForKey(pTSCol->cols[0].pData, pBlock->numOfRows, pCheckInfo->lastKey, pTsdbReadHandle->order);
1336 1337 1338
      } else {
        cur->pos = 0;
      }
H
Haojun Liao 已提交
1339

H
Haojun Liao 已提交
1340
      assert(pCheckInfo->lastKey <= pBlock->keyLast);
1341
      doMergeTwoLevelData(pTsdbReadHandle, pCheckInfo, pBlock);
1342
    } else {  // the whole block is loaded in to buffer
1343
      cur->pos = asc? 0:(pBlock->numOfRows - 1);
1344
      code = handleDataMergeIfNeeded(pTsdbReadHandle, pBlock, pCheckInfo);
H
[td-32]  
hjxilinx 已提交
1345
    }
1346
  } else {  //desc order, query ended in current block
1347 1348
    if (pTsdbReadHandle->window.ekey > pBlock->keyFirst || pCheckInfo->lastKey < pBlock->keyLast) {
      if ((code = doLoadFileDataBlock(pTsdbReadHandle, pBlock, pCheckInfo, cur->slot)) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1349 1350
        *exists = false;
        return code;
1351
      }
H
Haojun Liao 已提交
1352

1353
      SDataCols* pTsCol = pTsdbReadHandle->rhelper.pDCols[0];
1354
      if (pCheckInfo->lastKey < pBlock->keyLast) {
1355
        cur->pos = binarySearchForKey(pTsCol->cols[0].pData, pBlock->numOfRows, pCheckInfo->lastKey, pTsdbReadHandle->order);
1356
      } else {
H
Haojun Liao 已提交
1357
        cur->pos = pBlock->numOfRows - 1;
1358
      }
H
Haojun Liao 已提交
1359

H
Haojun Liao 已提交
1360
      assert(pCheckInfo->lastKey >= pBlock->keyFirst);
1361
      doMergeTwoLevelData(pTsdbReadHandle, pCheckInfo, pBlock);
1362
    } else {
1363
      cur->pos = asc? 0:(pBlock->numOfRows-1);
1364
      code = handleDataMergeIfNeeded(pTsdbReadHandle, pBlock, pCheckInfo);
H
[td-32]  
hjxilinx 已提交
1365
    }
1366
  }
1367

1368
  *exists = pTsdbReadHandle->realNumOfRows > 0;
H
Haojun Liao 已提交
1369
  return code;
H
[td-32]  
hjxilinx 已提交
1370 1371
}

1372
static int doBinarySearchKey(char* pValue, int num, TSKEY key, int order) {
1373
  int    firstPos, lastPos, midPos = -1;
H
Haojun Liao 已提交
1374
  int    numOfRows;
1375 1376
  TSKEY* keyList;

1377
  assert(order == TSDB_ORDER_ASC || order == TSDB_ORDER_DESC);
H
Haojun Liao 已提交
1378

1379
  if (num <= 0) return -1;
1380 1381

  keyList = (TSKEY*)pValue;
1382 1383
  firstPos = 0;
  lastPos = num - 1;
1384

1385
  if (order == TSDB_ORDER_DESC) {
1386 1387 1388 1389 1390
    // 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;
1391

H
Haojun Liao 已提交
1392 1393
      numOfRows = lastPos - firstPos + 1;
      midPos = (numOfRows >> 1) + firstPos;
1394

1395 1396 1397 1398 1399 1400 1401 1402
      if (key < keyList[midPos]) {
        lastPos = midPos - 1;
      } else if (key > keyList[midPos]) {
        firstPos = midPos + 1;
      } else {
        break;
      }
    }
1403

1404 1405 1406 1407 1408
  } 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;
1409

1410 1411 1412 1413 1414 1415 1416
      if (key > keyList[lastPos]) {
        lastPos = lastPos + 1;
        if (lastPos >= num)
          return -1;
        else
          return lastPos;
      }
1417

H
Haojun Liao 已提交
1418 1419
      numOfRows = lastPos - firstPos + 1;
      midPos = (numOfRows >> 1) + firstPos;
1420

1421 1422 1423 1424 1425 1426 1427 1428 1429
      if (key < keyList[midPos]) {
        lastPos = midPos - 1;
      } else if (key > keyList[midPos]) {
        firstPos = midPos + 1;
      } else {
        break;
      }
    }
  }
1430

1431 1432 1433
  return midPos;
}

1434
static int32_t doCopyRowsFromFileBlock(STsdbReadHandle* pTsdbReadHandle, int32_t capacity, int32_t numOfRows, int32_t start, int32_t end) {
1435
  char* pData = NULL;
1436
  int32_t step = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? 1 : -1;
H
Haojun Liao 已提交
1437

1438
  SDataCols* pCols = pTsdbReadHandle->rhelper.pDCols[0];
1439
  TSKEY* tsArray = pCols->cols[0].pData;
H
Haojun Liao 已提交
1440

1441
  int32_t num = end - start + 1;
H
Haojun Liao 已提交
1442 1443 1444 1445 1446 1447
  assert(num >= 0);

  if (num == 0) {
    return numOfRows;
  }

1448
  int32_t requiredNumOfCols = (int32_t)taosArrayGetSize(pTsdbReadHandle->pColumns);
H
Haojun Liao 已提交
1449

1450
  //data in buffer has greater timestamp, copy data in file block
1451 1452
  int32_t i = 0, j = 0;
  while(i < requiredNumOfCols && j < pCols->numOfCols) {
1453
    SColumnInfoData* pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, i);
1454 1455 1456 1457 1458 1459 1460 1461 1462

    SDataCol* src = &pCols->cols[j];
    if (src->colId < pColInfo->info.colId) {
      j++;
      continue;
    }

    int32_t bytes = pColInfo->info.bytes;

1463
    if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
S
TD-1057  
Shengliang Guan 已提交
1464
      pData = (char*)pColInfo->pData + numOfRows * pColInfo->info.bytes;
1465
    } else {
S
TD-1057  
Shengliang Guan 已提交
1466
      pData = (char*)pColInfo->pData + (capacity - numOfRows - num) * pColInfo->info.bytes;
1467
    }
1468

L
Liu Jicong 已提交
1469
    if (!isAllRowsNull(src) && pColInfo->info.colId == src->colId) {
1470
      if (pColInfo->info.type != TSDB_DATA_TYPE_BINARY && pColInfo->info.type != TSDB_DATA_TYPE_NCHAR) {
S
TD-1057  
Shengliang Guan 已提交
1471
        memmove(pData, (char*)src->pData + bytes * start, bytes * num);
1472 1473 1474 1475 1476
      } else {  // handle the var-string
        char* dst = pData;

        // todo refactor, only copy one-by-one
        for (int32_t k = start; k < num + start; ++k) {
K
kailixu 已提交
1477
          const char* p = tdGetColDataOfRow(src, k);
1478 1479
          memcpy(dst, p, varDataTLen(p));
          dst += bytes;
1480 1481
        }
      }
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496

      j++;
      i++;
    } else { // pColInfo->info.colId < src->colId, it is a NULL data
      if (pColInfo->info.type == TSDB_DATA_TYPE_BINARY || pColInfo->info.type == TSDB_DATA_TYPE_NCHAR) {
        char* dst = pData;

        for(int32_t k = start; k < num + start; ++k) {
          setVardataNull(dst, pColInfo->info.type);
          dst += bytes;
        }
      } else {
        setNullN(pData, pColInfo->info.type, pColInfo->info.bytes, num);
      }
      i++;
1497 1498
    }
  }
1499 1500

  while (i < requiredNumOfCols) { // the remain columns are all null data
1501 1502
    SColumnInfoData* pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, i);
    if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
S
TD-1057  
Shengliang Guan 已提交
1503
      pData = (char*)pColInfo->pData + numOfRows * pColInfo->info.bytes;
1504
    } else {
S
TD-1057  
Shengliang Guan 已提交
1505
      pData = (char*)pColInfo->pData + (capacity - numOfRows - num) * pColInfo->info.bytes;
1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
    }

    if (pColInfo->info.type == TSDB_DATA_TYPE_BINARY || pColInfo->info.type == TSDB_DATA_TYPE_NCHAR) {
      char* dst = pData;

      for(int32_t k = start; k < num + start; ++k) {
        setVardataNull(dst, pColInfo->info.type);
        dst += pColInfo->info.bytes;
      }
    } else {
      setNullN(pData, pColInfo->info.type, pColInfo->info.bytes, num);
1517
    }
1518 1519

    i++;
1520
  }
H
Haojun Liao 已提交
1521

1522 1523
  pTsdbReadHandle->cur.win.ekey = tsArray[end];
  pTsdbReadHandle->cur.lastKey = tsArray[end] + step;
1524

1525
  return numOfRows + num;
1526 1527
}

1528
// Note: row1 always has high priority
1529 1530
static void mergeTwoRowFromMem(STsdbReadHandle* pTsdbReadHandle, int32_t capacity, int32_t numOfRows,
                               SMemRow row1, SMemRow row2, int32_t numOfCols, uint64_t uid,
1531
                               STSchema* pSchema1, STSchema* pSchema2, bool forceSetNull) {
1532
  char* pData = NULL;
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
  STSchema* pSchema;
  SMemRow row;
  int16_t colId;
  int16_t offset;

  bool isRow1DataRow = isDataRow(row1);
  bool isRow2DataRow;
  bool isChosenRowDataRow;
  int32_t chosen_itr;
  void *value;
1543

1544 1545 1546 1547
  // the schema version info is embeded in SDataRow
  int32_t numOfColsOfRow1 = 0;

  if (pSchema1 == NULL) {
1548
    pSchema1 = metaGetTbTSchema(pTsdbReadHandle->pTsdb->pMeta, uid, 0);
1549
  }
1550

1551 1552
  if(isRow1DataRow) {
    numOfColsOfRow1 = schemaNCols(pSchema1);
H
Haojun Liao 已提交
1553
  } else {
1554
    numOfColsOfRow1 = kvRowNCols(memRowKvBody(row1));
D
fix bug  
dapan1121 已提交
1555
  }
1556

1557 1558 1559 1560
  int32_t numOfColsOfRow2 = 0;
  if(row2) {
    isRow2DataRow = isDataRow(row2);
    if (pSchema2 == NULL) {
1561
      pSchema2 = metaGetTbTSchema(pTsdbReadHandle->pTsdb->pMeta, uid, 0);
1562 1563 1564 1565 1566 1567 1568
    }
    if(isRow2DataRow) {
      numOfColsOfRow2 = schemaNCols(pSchema2);
    } else {
      numOfColsOfRow2 = kvRowNCols(memRowKvBody(row2));
    }
  }
C
Cary Xu 已提交
1569

1570 1571 1572

  int32_t i = 0, j = 0, k = 0;
  while(i < numOfCols && (j < numOfColsOfRow1 || k < numOfColsOfRow2)) {
1573
    SColumnInfoData* pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, i);
1574

1575
    if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
      pData = (char*)pColInfo->pData + numOfRows * pColInfo->info.bytes;
    } else {
      pData = (char*)pColInfo->pData + (capacity - numOfRows - 1) * pColInfo->info.bytes;
    }

    int32_t colIdOfRow1;
    if(j >= numOfColsOfRow1) {
      colIdOfRow1 = INT32_MAX;
    } else if(isRow1DataRow) {
      colIdOfRow1 = pSchema1->columns[j].colId;
    } else {
      void *rowBody = memRowKvBody(row1);
      SColIdx *pColIdx = kvRowColIdxAt(rowBody, j);
      colIdOfRow1 = pColIdx->colId;
    }

    int32_t colIdOfRow2;
    if(k >= numOfColsOfRow2) {
      colIdOfRow2 = INT32_MAX;
    } else if(isRow2DataRow) {
      colIdOfRow2 = pSchema2->columns[k].colId;
    } else {
      void *rowBody = memRowKvBody(row2);
      SColIdx *pColIdx = kvRowColIdxAt(rowBody, k);
      colIdOfRow2 = pColIdx->colId;
    }

    if(colIdOfRow1 == colIdOfRow2) {
      if(colIdOfRow1 < pColInfo->info.colId) {
C
Cary Xu 已提交
1605
        j++;
1606
        k++;
C
Cary Xu 已提交
1607 1608
        continue;
      }
1609 1610 1611 1612 1613 1614 1615 1616
      row = row1;
      pSchema = pSchema1;
      isChosenRowDataRow = isRow1DataRow;
      chosen_itr = j;
    } else if(colIdOfRow1 < colIdOfRow2) {
      if(colIdOfRow1 < pColInfo->info.colId) {
        j++;
        continue;
C
Cary Xu 已提交
1617
      }
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
      row = row1;
      pSchema = pSchema1;
      isChosenRowDataRow = isRow1DataRow;
      chosen_itr = j;
    } else {
      if(colIdOfRow2 < pColInfo->info.colId) {
        k++;
        continue;
      }
      row = row2;
      pSchema = pSchema2;
      chosen_itr = k;
      isChosenRowDataRow = isRow2DataRow;
    }
    if(isChosenRowDataRow) {
      colId = pSchema->columns[chosen_itr].colId;
      offset = pSchema->columns[chosen_itr].offset;
      void *rowBody = memRowDataBody(row);
      value = tdGetRowDataOfCol(rowBody, (int8_t)pColInfo->info.type, TD_DATA_ROW_HEAD_SIZE + offset);
    } else {
      void *rowBody = memRowKvBody(row);
      SColIdx *pColIdx = kvRowColIdxAt(rowBody, chosen_itr);
      colId = pColIdx->colId;
      offset = pColIdx->offset;
      value = tdGetKvRowDataOfCol(rowBody, pColIdx->offset);
    }

C
Cary Xu 已提交
1645

1646 1647
    if (colId == pColInfo->info.colId) {
      if(forceSetNull || (!isNull(value, (int8_t)pColInfo->info.type))) {
C
Cary Xu 已提交
1648 1649 1650 1651 1652 1653 1654 1655 1656
        switch (pColInfo->info.type) {
          case TSDB_DATA_TYPE_BINARY:
          case TSDB_DATA_TYPE_NCHAR:
            memcpy(pData, value, varDataTLen(value));
            break;
          case TSDB_DATA_TYPE_NULL:
          case TSDB_DATA_TYPE_BOOL:
          case TSDB_DATA_TYPE_TINYINT:
          case TSDB_DATA_TYPE_UTINYINT:
1657
            *(uint8_t *)pData = *(uint8_t *)value;
C
Cary Xu 已提交
1658 1659 1660
            break;
          case TSDB_DATA_TYPE_SMALLINT:
          case TSDB_DATA_TYPE_USMALLINT:
1661
            *(uint16_t *)pData = *(uint16_t *)value;
C
Cary Xu 已提交
1662 1663 1664
            break;
          case TSDB_DATA_TYPE_INT:
          case TSDB_DATA_TYPE_UINT:
1665
            *(uint32_t *)pData = *(uint32_t *)value;
C
Cary Xu 已提交
1666 1667 1668
            break;
          case TSDB_DATA_TYPE_BIGINT:
          case TSDB_DATA_TYPE_UBIGINT:
1669
            *(uint64_t *)pData = *(uint64_t *)value;
C
Cary Xu 已提交
1670 1671 1672 1673 1674 1675 1676 1677
            break;
          case TSDB_DATA_TYPE_FLOAT:
            SET_FLOAT_PTR(pData, value);
            break;
          case TSDB_DATA_TYPE_DOUBLE:
            SET_DOUBLE_PTR(pData, value);
            break;
          case TSDB_DATA_TYPE_TIMESTAMP:
1678
            if (pColInfo->info.colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
1679
              *(TSKEY *)pData = tdGetKey(*(TKEY *)value);
C
Cary Xu 已提交
1680
            } else {
1681
              *(TSKEY *)pData = *(TSKEY *)value;
C
Cary Xu 已提交
1682 1683 1684 1685 1686
            }
            break;
          default:
            memcpy(pData, value, pColInfo->info.bytes);
        }
1687 1688
      }
      i++;
C
Cary Xu 已提交
1689

1690
      if(row == row1) {
C
Cary Xu 已提交
1691
        j++;
1692 1693 1694 1695 1696
      } else {
        k++;
      }
    } else {
      if(forceSetNull) {
C
Cary Xu 已提交
1697 1698 1699 1700 1701 1702
        if (pColInfo->info.type == TSDB_DATA_TYPE_BINARY || pColInfo->info.type == TSDB_DATA_TYPE_NCHAR) {
          setVardataNull(pData, pColInfo->info.type);
        } else {
          setNull(pData, pColInfo->info.type, pColInfo->info.bytes);
        }
      }
1703
      i++;
1704
    }
1705
  }
1706

1707 1708
  if(forceSetNull) {
    while (i < numOfCols) { // the remain columns are all null data
1709 1710
      SColumnInfoData* pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, i);
      if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
C
Cary Xu 已提交
1711 1712 1713 1714 1715
        pData = (char*)pColInfo->pData + numOfRows * pColInfo->info.bytes;
      } else {
        pData = (char*)pColInfo->pData + (capacity - numOfRows - 1) * pColInfo->info.bytes;
      }

1716 1717 1718 1719
      if (pColInfo->info.type == TSDB_DATA_TYPE_BINARY || pColInfo->info.type == TSDB_DATA_TYPE_NCHAR) {
        setVardataNull(pData, pColInfo->info.type);
      } else {
        setNull(pData, pColInfo->info.type, pColInfo->info.bytes);
1720
      }
1721

1722
      i++;
1723 1724 1725
    }
  }
}
1726

1727 1728
static void moveDataToFront(STsdbReadHandle* pTsdbReadHandle, int32_t numOfRows, int32_t numOfCols) {
  if (numOfRows == 0 || ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
1729 1730 1731 1732
    return;
  }

  // if the buffer is not full in case of descending order query, move the data in the front of the buffer
1733 1734
  if (numOfRows < pTsdbReadHandle->outputCapacity) {
    int32_t emptySize = pTsdbReadHandle->outputCapacity - numOfRows;
1735
    for(int32_t i = 0; i < numOfCols; ++i) {
1736
      SColumnInfoData* pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, i);
S
TD-1057  
Shengliang Guan 已提交
1737
      memmove((char*)pColInfo->pData, (char*)pColInfo->pData + emptySize * pColInfo->info.bytes, numOfRows * pColInfo->info.bytes);
1738 1739 1740 1741
    }
  }
}

1742
static void getQualifiedRowsPos(STsdbReadHandle* pTsdbReadHandle, int32_t startPos, int32_t endPos, int32_t numOfExisted,
1743
                                int32_t* start, int32_t* end) {
1744 1745
  *start = -1;

1746
  if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
1747
    int32_t remain = endPos - startPos + 1;
1748 1749
    if (remain + numOfExisted > pTsdbReadHandle->outputCapacity) {
      *end = (pTsdbReadHandle->outputCapacity - numOfExisted) + startPos - 1;
H
Haojun Liao 已提交
1750 1751
    } else {
      *end = endPos;
1752 1753 1754 1755 1756
    }

    *start = startPos;
  } else {
    int32_t remain = (startPos - endPos) + 1;
1757 1758
    if (remain + numOfExisted > pTsdbReadHandle->outputCapacity) {
      *end = startPos + 1 - (pTsdbReadHandle->outputCapacity - numOfExisted);
H
Haojun Liao 已提交
1759 1760
    } else {
      *end = endPos;
1761 1762 1763 1764 1765 1766 1767
    }

    *start = *end;
    *end = startPos;
  }
}

1768 1769
static void updateInfoAfterMerge(STsdbReadHandle* pTsdbReadHandle, STableCheckInfo* pCheckInfo, int32_t numOfRows, int32_t endPos) {
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
1770 1771

  pCheckInfo->lastKey = cur->lastKey;
1772
  pTsdbReadHandle->realNumOfRows = numOfRows;
1773 1774 1775 1776
  cur->rows = numOfRows;
  cur->pos = endPos;
}

1777 1778
static void doCheckGeneratedBlockRange(STsdbReadHandle* pTsdbReadHandle) {
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
H
Haojun Liao 已提交
1779 1780

  if (cur->rows > 0) {
1781 1782
    if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
      assert(cur->win.skey >= pTsdbReadHandle->window.skey && cur->win.ekey <= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
1783
    } else {
1784
      assert(cur->win.skey >= pTsdbReadHandle->window.ekey && cur->win.ekey <= pTsdbReadHandle->window.skey);
H
Haojun Liao 已提交
1785 1786
    }

1787
    SColumnInfoData* pColInfoData = taosArrayGet(pTsdbReadHandle->pColumns, 0);
H
Haojun Liao 已提交
1788 1789
    assert(cur->win.skey == ((TSKEY*)pColInfoData->pData)[0] && cur->win.ekey == ((TSKEY*)pColInfoData->pData)[cur->rows-1]);
  } else {
1790
    cur->win = pTsdbReadHandle->window;
H
Haojun Liao 已提交
1791

1792 1793
    int32_t step = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? 1:-1;
    cur->lastKey = pTsdbReadHandle->window.ekey + step;
H
Haojun Liao 已提交
1794 1795 1796
  }
}

1797 1798
static void copyAllRemainRowsFromFileBlock(STsdbReadHandle* pTsdbReadHandle, STableCheckInfo* pCheckInfo, SDataBlockInfo* pBlockInfo, int32_t endPos) {
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
H
Haojun Liao 已提交
1799

1800
  SDataCols* pCols = pTsdbReadHandle->rhelper.pDCols[0];
H
Haojun Liao 已提交
1801 1802
  TSKEY* tsArray = pCols->cols[0].pData;

1803 1804
  int32_t step = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? 1:-1;
  int32_t numOfCols = (int32_t)(QH_GET_NUM_OF_COLS(pTsdbReadHandle));
H
Haojun Liao 已提交
1805 1806 1807 1808 1809 1810

  int32_t pos = cur->pos;

  int32_t start = cur->pos;
  int32_t end = endPos;

1811
  if (!ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
H
Haojun Liao 已提交
1812 1813 1814
    SWAP(start, end, int32_t);
  }

1815 1816
  assert(pTsdbReadHandle->outputCapacity >= (end - start + 1));
  int32_t numOfRows = doCopyRowsFromFileBlock(pTsdbReadHandle, pTsdbReadHandle->outputCapacity, 0, start, end);
H
Haojun Liao 已提交
1817 1818 1819

  // the time window should always be ascending order: skey <= ekey
  cur->win = (STimeWindow) {.skey = tsArray[start], .ekey = tsArray[end]};
H
Haojun Liao 已提交
1820
  cur->mixBlock = (numOfRows != pBlockInfo->rows);
H
Haojun Liao 已提交
1821
  cur->lastKey = tsArray[endPos] + step;
H
Haojun Liao 已提交
1822
  cur->blockCompleted = true;
H
Haojun Liao 已提交
1823 1824

  // if the buffer is not full in case of descending order query, move the data in the front of the buffer
1825
  moveDataToFront(pTsdbReadHandle, numOfRows, numOfCols);
H
Haojun Liao 已提交
1826 1827 1828

  // The value of pos may be -1 or pBlockInfo->rows, and it is invalid in both cases.
  pos = endPos + step;
1829 1830
  updateInfoAfterMerge(pTsdbReadHandle, pCheckInfo, numOfRows, pos);
  doCheckGeneratedBlockRange(pTsdbReadHandle);
H
Haojun Liao 已提交
1831

1832 1833
  tsdbDebug("%p uid:%" PRIu64", data block created, mixblock:%d, brange:%"PRIu64"-%"PRIu64" rows:%d, 0x%"PRIx64,
            pTsdbReadHandle, pCheckInfo->tableId, cur->mixBlock, cur->win.skey, cur->win.ekey, cur->rows, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
1834 1835
}

1836
int32_t getEndPosInDataBlock(STsdbReadHandle* pTsdbReadHandle, SDataBlockInfo* pBlockInfo) {
H
Haojun Liao 已提交
1837 1838
  // NOTE: reverse the order to find the end position in data block
  int32_t endPos = -1;
1839
  int32_t order = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? TSDB_ORDER_DESC : TSDB_ORDER_ASC;
H
Haojun Liao 已提交
1840

1841 1842
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
  SDataCols* pCols = pTsdbReadHandle->rhelper.pDCols[0];
H
Haojun Liao 已提交
1843

1844
  if (ASCENDING_TRAVERSE(pTsdbReadHandle->order) && pTsdbReadHandle->window.ekey >= pBlockInfo->window.ekey) {
H
Haojun Liao 已提交
1845 1846
    endPos = pBlockInfo->rows - 1;
    cur->mixBlock = (cur->pos != 0);
1847
  } else if (!ASCENDING_TRAVERSE(pTsdbReadHandle->order) && pTsdbReadHandle->window.ekey <= pBlockInfo->window.skey) {
H
Haojun Liao 已提交
1848 1849 1850 1851
    endPos = 0;
    cur->mixBlock = (cur->pos != pBlockInfo->rows - 1);
  } else {
    assert(pCols->numOfRows > 0);
1852
    endPos = doBinarySearchKey(pCols->cols[0].pData, pCols->numOfRows, pTsdbReadHandle->window.ekey, order);
H
Haojun Liao 已提交
1853 1854 1855 1856 1857 1858
    cur->mixBlock = true;
  }

  return endPos;
}

H
[td-32]  
hjxilinx 已提交
1859 1860
// only return the qualified data to client in terms of query time window, data rows in the same block but do not
// be included in the query time window will be discarded
1861 1862 1863 1864
static void doMergeTwoLevelData(STsdbReadHandle* pTsdbReadHandle, STableCheckInfo* pCheckInfo, SBlock* pBlock) {
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
  SDataBlockInfo blockInfo = {0};//GET_FILE_DATA_BLOCK_INFO(pCheckInfo, pBlock);
  STsdbCfg*      pCfg = &pTsdbReadHandle->pTsdb->config;
H
Haojun Liao 已提交
1865

1866
  initTableMemIterator(pTsdbReadHandle, pCheckInfo);
1867

1868 1869
  SDataCols* pCols = pTsdbReadHandle->rhelper.pDCols[0];
  assert(pCols->cols[0].type == TSDB_DATA_TYPE_TIMESTAMP && pCols->cols[0].colId == PRIMARYKEY_TIMESTAMP_COL_ID &&
H
Haojun Liao 已提交
1870 1871
      cur->pos >= 0 && cur->pos < pBlock->numOfRows);

1872
  TSKEY* tsArray = pCols->cols[0].pData;
H
Haojun Liao 已提交
1873
  assert(pCols->numOfRows == pBlock->numOfRows && tsArray[0] == pBlock->keyFirst && tsArray[pBlock->numOfRows-1] == pBlock->keyLast);
1874 1875

  // for search the endPos, so the order needs to reverse
1876
  int32_t order = (pTsdbReadHandle->order == TSDB_ORDER_ASC)? TSDB_ORDER_DESC:TSDB_ORDER_ASC;
1877

1878 1879
  int32_t step = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? 1:-1;
  int32_t numOfCols = (int32_t)(QH_GET_NUM_OF_COLS(pTsdbReadHandle));
1880 1881

  STable* pTable = pCheckInfo->pTableObj;
1882
  int32_t endPos = getEndPosInDataBlock(pTsdbReadHandle, &blockInfo);
H
Haojun Liao 已提交
1883

1884
  tsdbDebug("%p uid:%" PRIu64" start merge data block, file block range:%"PRIu64"-%"PRIu64" rows:%d, start:%d,"
H
Haojun Liao 已提交
1885
            "end:%d, 0x%"PRIx64,
1886 1887
            pTsdbReadHandle, pCheckInfo->tableId, blockInfo.window.skey, blockInfo.window.ekey,
            blockInfo.rows, cur->pos, endPos, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
1888

1889 1890
  // compared with the data from in-memory buffer, to generate the correct timestamp array list
  int32_t numOfRows = 0;
H
Haojun Liao 已提交
1891

1892 1893 1894 1895
  int16_t rv1 = -1;
  int16_t rv2 = -1;
  STSchema* pSchema1 = NULL;
  STSchema* pSchema2 = NULL;
D
fix bug  
dapan1121 已提交
1896

H
Haojun Liao 已提交
1897 1898
  int32_t pos = cur->pos;
  cur->win = TSWINDOW_INITIALIZER;
1899

1900 1901
  // no data in buffer, load data from file directly
  if (pCheckInfo->iiter == NULL && pCheckInfo->iter == NULL) {
1902
    copyAllRemainRowsFromFileBlock(pTsdbReadHandle, pCheckInfo, &blockInfo, endPos);
1903
    return;
1904
  } else if (pCheckInfo->iter != NULL || pCheckInfo->iiter != NULL) {
1905 1906
    SSkipListNode* node = NULL;
    do {
1907
      SMemRow row2 = NULL;
1908
      SMemRow row1 = getSMemRowInTableMem(pCheckInfo, pTsdbReadHandle->order, pCfg->update, &row2);
1909
      if (row1 == NULL) {
H
[td-32]  
hjxilinx 已提交
1910
        break;
1911
      }
1912

1913
      TSKEY key = memRowKey(row1);
1914 1915
      if ((key > pTsdbReadHandle->window.ekey && ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
          (key < pTsdbReadHandle->window.ekey && !ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
1916 1917 1918
        break;
      }

1919 1920
      if (((pos > endPos || tsArray[pos] > pTsdbReadHandle->window.ekey) && ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
          ((pos < endPos || tsArray[pos] < pTsdbReadHandle->window.ekey) && !ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
1921 1922 1923
        break;
      }

1924 1925
      if ((key < tsArray[pos] && ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
          (key > tsArray[pos] && !ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
1926
        if (rv1 != memRowVersion(row1)) {
1927
//          pSchema1 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row1));
1928
          rv1 = memRowVersion(row1);
C
Cary Xu 已提交
1929
        }
1930
        if(row2 && rv2 != memRowVersion(row2)) {
1931
//          pSchema2 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row2));
1932 1933 1934
          rv2 = memRowVersion(row2);
        }
        
1935
        mergeTwoRowFromMem(pTsdbReadHandle, pTsdbReadHandle->outputCapacity, numOfRows, row1, row2, numOfCols, pTable, pSchema1, pSchema2, true);
1936 1937 1938 1939
        numOfRows += 1;
        if (cur->win.skey == TSKEY_INITIAL_VAL) {
          cur->win.skey = key;
        }
1940

1941
        cur->win.ekey = key;
1942 1943 1944
        cur->lastKey  = key + step;
        cur->mixBlock = true;

1945
        moveToNextRowInMem(pCheckInfo);
1946
      } else if (key == tsArray[pos]) {  // data in buffer has the same timestamp of data in file block, ignore it
H
TD-1439  
Hongze Cheng 已提交
1947
        if (pCfg->update) {
1948
          if(pCfg->update == TD_ROW_PARTIAL_UPDATE) {
1949
            doCopyRowsFromFileBlock(pTsdbReadHandle, pTsdbReadHandle->outputCapacity, numOfRows, pos, pos);
D
fix bug  
dapan1121 已提交
1950
          }
1951
          if (rv1 != memRowVersion(row1)) {
1952
//            pSchema1 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row1));
1953 1954 1955
            rv1 = memRowVersion(row1);
          }
          if(row2 && rv2 != memRowVersion(row2)) {
1956
//            pSchema2 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row2));
1957 1958 1959 1960
            rv2 = memRowVersion(row2);
          }
          
          bool forceSetNull = pCfg->update != TD_ROW_PARTIAL_UPDATE;
1961
          mergeTwoRowFromMem(pTsdbReadHandle, pTsdbReadHandle->outputCapacity, numOfRows, row1, row2, numOfCols, pTable, pSchema1, pSchema2, forceSetNull);
H
TD-1439  
Hongze Cheng 已提交
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
          numOfRows += 1;
          if (cur->win.skey == TSKEY_INITIAL_VAL) {
            cur->win.skey = key;
          }

          cur->win.ekey = key;
          cur->lastKey = key + step;
          cur->mixBlock = true;

          moveToNextRowInMem(pCheckInfo);
          pos += step;
        } else {
          moveToNextRowInMem(pCheckInfo);
        }
1976 1977
      } else if ((key > tsArray[pos] && ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
                  (key < tsArray[pos] && !ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
1978 1979 1980
        if (cur->win.skey == TSKEY_INITIAL_VAL) {
          cur->win.skey = tsArray[pos];
        }
1981

1982
        int32_t end = doBinarySearchKey(pCols->cols[0].pData, pCols->numOfRows, key, order);
1983 1984
        assert(end != -1);

H
Haojun Liao 已提交
1985
        if (tsArray[end] == key) { // the value of key in cache equals to the end timestamp value, ignore it
1986
          if (pCfg->update == TD_ROW_DISCARD_UPDATE) {
H
Hongze Cheng 已提交
1987 1988 1989 1990
            moveToNextRowInMem(pCheckInfo);
          } else {
            end -= step;
          }
H
Haojun Liao 已提交
1991
        }
1992

1993
        int32_t qstart = 0, qend = 0;
1994
        getQualifiedRowsPos(pTsdbReadHandle, pos, end, numOfRows, &qstart, &qend);
1995

1996
        numOfRows = doCopyRowsFromFileBlock(pTsdbReadHandle, pTsdbReadHandle->outputCapacity, numOfRows, qstart, qend);
1997 1998
        pos += (qend - qstart + 1) * step;

1999
        cur->win.ekey = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? tsArray[qend]:tsArray[qstart];
2000
        cur->lastKey  = cur->win.ekey + step;
2001
      }
2002
    } while (numOfRows < pTsdbReadHandle->outputCapacity);
H
Haojun Liao 已提交
2003

2004
    if (numOfRows < pTsdbReadHandle->outputCapacity) {
H
Haojun Liao 已提交
2005 2006 2007 2008
      /**
       * if cache is empty, load remain file block data. In contrast, if there are remain data in cache, do NOT
       * copy them all to result buffer, since it may be overlapped with file data block.
       */
2009
      if (node == NULL ||
2010 2011 2012 2013
          ((memRowKey((SMemRow)SL_GET_NODE_DATA(node)) > pTsdbReadHandle->window.ekey) &&
           ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
          ((memRowKey((SMemRow)SL_GET_NODE_DATA(node)) < pTsdbReadHandle->window.ekey) &&
           !ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
2014 2015 2016 2017 2018
        // no data in cache or data in cache is greater than the ekey of time window, load data from file block
        if (cur->win.skey == TSKEY_INITIAL_VAL) {
          cur->win.skey = tsArray[pos];
        }

2019
        int32_t start = -1, end = -1;
2020
        getQualifiedRowsPos(pTsdbReadHandle, pos, endPos, numOfRows, &start, &end);
2021

2022
        numOfRows = doCopyRowsFromFileBlock(pTsdbReadHandle, pTsdbReadHandle->outputCapacity, numOfRows, start, end);
2023
        pos += (end - start + 1) * step;
2024

2025
        cur->win.ekey = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? tsArray[end]:tsArray[start];
2026
        cur->lastKey  = cur->win.ekey + step;
H
Haojun Liao 已提交
2027
        cur->mixBlock = true;
2028
      }
2029 2030
    }
  }
H
Haojun Liao 已提交
2031 2032

  cur->blockCompleted =
2033 2034
      (((pos > endPos || cur->lastKey > pTsdbReadHandle->window.ekey) && ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
       ((pos < endPos || cur->lastKey < pTsdbReadHandle->window.ekey) && !ASCENDING_TRAVERSE(pTsdbReadHandle->order)));
2035

2036
  if (!ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
2037 2038
    SWAP(cur->win.skey, cur->win.ekey, TSKEY);
  }
2039

2040 2041 2042
  moveDataToFront(pTsdbReadHandle, numOfRows, numOfCols);
  updateInfoAfterMerge(pTsdbReadHandle, pCheckInfo, numOfRows, pos);
  doCheckGeneratedBlockRange(pTsdbReadHandle);
H
Haojun Liao 已提交
2043

2044 2045
  tsdbDebug("%p uid:%" PRIu64", data block created, mixblock:%d, brange:%"PRIu64"-%"PRIu64" rows:%d, 0x%"PRIx64,
      pTsdbReadHandle, pCheckInfo->tableId, cur->mixBlock, cur->win.skey, cur->win.ekey, cur->rows, pTsdbReadHandle->qId);
2046 2047
}

2048
int32_t binarySearchForKey(char* pValue, int num, TSKEY key, int order) {
H
[td-32]  
hjxilinx 已提交
2049
  int    firstPos, lastPos, midPos = -1;
H
Haojun Liao 已提交
2050
  int    numOfRows;
2051 2052
  TSKEY* keyList;

H
[td-32]  
hjxilinx 已提交
2053
  if (num <= 0) return -1;
2054 2055

  keyList = (TSKEY*)pValue;
H
[td-32]  
hjxilinx 已提交
2056 2057
  firstPos = 0;
  lastPos = num - 1;
2058

2059
  if (order == TSDB_ORDER_DESC) {
H
[td-32]  
hjxilinx 已提交
2060 2061 2062 2063 2064
    // 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;
2065

H
Haojun Liao 已提交
2066 2067
      numOfRows = lastPos - firstPos + 1;
      midPos = (numOfRows >> 1) + firstPos;
2068

H
[td-32]  
hjxilinx 已提交
2069 2070 2071 2072 2073 2074 2075 2076
      if (key < keyList[midPos]) {
        lastPos = midPos - 1;
      } else if (key > keyList[midPos]) {
        firstPos = midPos + 1;
      } else {
        break;
      }
    }
2077

H
[td-32]  
hjxilinx 已提交
2078 2079 2080 2081 2082
  } 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;
2083

H
[td-32]  
hjxilinx 已提交
2084 2085 2086 2087 2088 2089 2090
      if (key > keyList[lastPos]) {
        lastPos = lastPos + 1;
        if (lastPos >= num)
          return -1;
        else
          return lastPos;
      }
2091

H
Haojun Liao 已提交
2092 2093
      numOfRows = lastPos - firstPos + 1;
      midPos = (numOfRows >> 1) + firstPos;
2094

H
[td-32]  
hjxilinx 已提交
2095 2096 2097 2098 2099 2100 2101 2102 2103
      if (key < keyList[midPos]) {
        lastPos = midPos - 1;
      } else if (key > keyList[midPos]) {
        firstPos = midPos + 1;
      } else {
        break;
      }
    }
  }
2104

H
[td-32]  
hjxilinx 已提交
2105 2106 2107
  return midPos;
}

2108
static void cleanBlockOrderSupporter(SBlockOrderSupporter* pSupporter, int32_t numOfTables) {
S
TD-1848  
Shengliang Guan 已提交
2109 2110
  tfree(pSupporter->numOfBlocksPerTable);
  tfree(pSupporter->blockIndexArray);
2111 2112

  for (int32_t i = 0; i < numOfTables; ++i) {
H
Haojun Liao 已提交
2113
    STableBlockInfo* pBlockInfo = pSupporter->pDataBlockInfo[i];
S
TD-1848  
Shengliang Guan 已提交
2114
    tfree(pBlockInfo);
2115 2116
  }

S
TD-1848  
Shengliang Guan 已提交
2117
  tfree(pSupporter->pDataBlockInfo);
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128
}

static int32_t dataBlockOrderCompar(const void* pLeft, const void* pRight, void* param) {
  int32_t leftTableIndex = *(int32_t*)pLeft;
  int32_t rightTableIndex = *(int32_t*)pRight;

  SBlockOrderSupporter* pSupporter = (SBlockOrderSupporter*)param;

  int32_t leftTableBlockIndex = pSupporter->blockIndexArray[leftTableIndex];
  int32_t rightTableBlockIndex = pSupporter->blockIndexArray[rightTableIndex];

2129
  if (leftTableBlockIndex > pSupporter->numOfBlocksPerTable[leftTableIndex]) {
2130 2131
    /* left block is empty */
    return 1;
2132
  } else if (rightTableBlockIndex > pSupporter->numOfBlocksPerTable[rightTableIndex]) {
2133 2134 2135 2136 2137 2138 2139
    /* right block is empty */
    return -1;
  }

  STableBlockInfo* pLeftBlockInfoEx = &pSupporter->pDataBlockInfo[leftTableIndex][leftTableBlockIndex];
  STableBlockInfo* pRightBlockInfoEx = &pSupporter->pDataBlockInfo[rightTableIndex][rightTableBlockIndex];

H
Haojun Liao 已提交
2140
  //    assert(pLeftBlockInfoEx->compBlock->offset != pRightBlockInfoEx->compBlock->offset);
2141
#if 0	// TODO: temporarily comment off requested by Dr. Liao
H
Haojun Liao 已提交
2142 2143
  if (pLeftBlockInfoEx->compBlock->offset == pRightBlockInfoEx->compBlock->offset &&
      pLeftBlockInfoEx->compBlock->last == pRightBlockInfoEx->compBlock->last) {
B
Bomin Zhang 已提交
2144
    tsdbError("error in header file, two block with same offset:%" PRId64, (int64_t)pLeftBlockInfoEx->compBlock->offset);
2145
  }
H
Haojun Liao 已提交
2146
#endif
2147

H
Haojun Liao 已提交
2148
  return pLeftBlockInfoEx->compBlock->offset > pRightBlockInfoEx->compBlock->offset ? 1 : -1;
2149 2150
}

2151
static int32_t createDataBlocksInfo(STsdbReadHandle* pTsdbReadHandle, int32_t numOfBlocks, int32_t* numOfAllocBlocks) {
H
Haojun Liao 已提交
2152 2153
  size_t size = sizeof(STableBlockInfo) * numOfBlocks;

2154 2155 2156
  if (pTsdbReadHandle->allocSize < size) {
    pTsdbReadHandle->allocSize = (int32_t)size;
    char* tmp = realloc(pTsdbReadHandle->pDataBlockInfo, pTsdbReadHandle->allocSize);
H
Haojun Liao 已提交
2157 2158 2159 2160
    if (tmp == NULL) {
      return TSDB_CODE_TDB_OUT_OF_MEMORY;
    }

2161
    pTsdbReadHandle->pDataBlockInfo = (STableBlockInfo*) tmp;
2162 2163
  }

2164
  memset(pTsdbReadHandle->pDataBlockInfo, 0, size);
2165 2166
  *numOfAllocBlocks = numOfBlocks;

H
Haojun Liao 已提交
2167
  // access data blocks according to the offset of each block in asc/desc order.
2168
  int32_t numOfTables = (int32_t)taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
2169

2170 2171
  SBlockOrderSupporter sup = {0};
  sup.numOfTables = numOfTables;
2172
  sup.numOfBlocksPerTable = calloc(1, sizeof(int32_t) * numOfTables);
2173 2174 2175
  sup.blockIndexArray = calloc(1, sizeof(int32_t) * numOfTables);
  sup.pDataBlockInfo = calloc(1, POINTER_BYTES * numOfTables);

2176
  if (sup.numOfBlocksPerTable == NULL || sup.blockIndexArray == NULL || sup.pDataBlockInfo == NULL) {
2177
    cleanBlockOrderSupporter(&sup, 0);
2178
    return TSDB_CODE_TDB_OUT_OF_MEMORY;
2179
  }
H
Haojun Liao 已提交
2180

2181
  int32_t cnt = 0;
2182
  int32_t numOfQualTables = 0;
H
Haojun Liao 已提交
2183

2184
  for (int32_t j = 0; j < numOfTables; ++j) {
2185
    STableCheckInfo* pTableCheck = (STableCheckInfo*)taosArrayGet(pTsdbReadHandle->pTableCheckInfo, j);
2186 2187 2188
    if (pTableCheck->numOfBlocks <= 0) {
      continue;
    }
H
Haojun Liao 已提交
2189

H
refact  
Hongze Cheng 已提交
2190
    SBlock* pBlock = pTableCheck->pCompInfo->blocks;
2191
    sup.numOfBlocksPerTable[numOfQualTables] = pTableCheck->numOfBlocks;
2192

H
Haojun Liao 已提交
2193
    char* buf = malloc(sizeof(STableBlockInfo) * pTableCheck->numOfBlocks);
2194
    if (buf == NULL) {
2195
      cleanBlockOrderSupporter(&sup, numOfQualTables);
2196
      return TSDB_CODE_TDB_OUT_OF_MEMORY;
2197 2198
    }

2199
    sup.pDataBlockInfo[numOfQualTables] = (STableBlockInfo*)buf;
2200 2201

    for (int32_t k = 0; k < pTableCheck->numOfBlocks; ++k) {
H
Haojun Liao 已提交
2202
      STableBlockInfo* pBlockInfo = &sup.pDataBlockInfo[numOfQualTables][k];
2203

H
Haojun Liao 已提交
2204 2205
      pBlockInfo->compBlock = &pBlock[k];
      pBlockInfo->pTableCheckInfo = pTableCheck;
2206 2207 2208
      cnt++;
    }

2209
    numOfQualTables++;
2210 2211
  }

H
Haojun Liao 已提交
2212
  assert(numOfBlocks == cnt);
2213

H
Haojun Liao 已提交
2214 2215
  // since there is only one table qualified, blocks are not sorted
  if (numOfQualTables == 1) {
2216
    memcpy(pTsdbReadHandle->pDataBlockInfo, sup.pDataBlockInfo[0], sizeof(STableBlockInfo) * numOfBlocks);
H
Haojun Liao 已提交
2217
    cleanBlockOrderSupporter(&sup, numOfQualTables);
2218

2219 2220
    tsdbDebug("%p create data blocks info struct completed for 1 table, %d blocks not sorted 0x%"PRIx64, pTsdbReadHandle, cnt,
        pTsdbReadHandle->qId);
H
Haojun Liao 已提交
2221 2222
    return TSDB_CODE_SUCCESS;
  }
2223

2224 2225
  tsdbDebug("%p create data blocks info struct completed, %d blocks in %d tables 0x%"PRIx64, pTsdbReadHandle, cnt,
      numOfQualTables, pTsdbReadHandle->qId);
2226

2227
  assert(cnt <= numOfBlocks && numOfQualTables <= numOfTables);  // the pTableQueryInfo[j]->numOfBlocks may be 0
2228
  sup.numOfTables = numOfQualTables;
2229

H
Haojun Liao 已提交
2230
  SLoserTreeInfo* pTree = NULL;
2231 2232 2233
  uint8_t ret = tLoserTreeCreate(&pTree, sup.numOfTables, &sup, dataBlockOrderCompar);
  if (ret != TSDB_CODE_SUCCESS) {
    cleanBlockOrderSupporter(&sup, numOfTables);
2234
    return TSDB_CODE_TDB_OUT_OF_MEMORY;
2235 2236 2237 2238 2239 2240 2241 2242
  }

  int32_t numOfTotal = 0;

  while (numOfTotal < cnt) {
    int32_t pos = pTree->pNode[0].index;
    int32_t index = sup.blockIndexArray[pos]++;

H
Haojun Liao 已提交
2243
    STableBlockInfo* pBlocksInfo = sup.pDataBlockInfo[pos];
2244
    pTsdbReadHandle->pDataBlockInfo[numOfTotal++] = pBlocksInfo[index];
2245 2246

    // set data block index overflow, in order to disable the offset comparator
2247 2248
    if (sup.blockIndexArray[pos] >= sup.numOfBlocksPerTable[pos]) {
      sup.blockIndexArray[pos] = sup.numOfBlocksPerTable[pos] + 1;
2249
    }
2250 2251 2252 2253 2254 2255 2256

    tLoserTreeAdjust(pTree, pos + sup.numOfTables);
  }

  /*
   * available when no import exists
   * for(int32_t i = 0; i < cnt - 1; ++i) {
H
Haojun Liao 已提交
2257
   *   assert((*pDataBlockInfo)[i].compBlock->offset < (*pDataBlockInfo)[i+1].compBlock->offset);
2258 2259 2260
   * }
   */

2261
  tsdbDebug("%p %d data blocks sort completed, 0x%"PRIx64, pTsdbReadHandle, cnt, pTsdbReadHandle->qId);
2262 2263 2264 2265 2266 2267
  cleanBlockOrderSupporter(&sup, numOfTables);
  free(pTree);

  return TSDB_CODE_SUCCESS;
}

2268
static int32_t getFirstFileDataBlock(STsdbReadHandle* pTsdbReadHandle, bool* exists);
H
Haojun Liao 已提交
2269

2270 2271 2272
static int32_t getDataBlockRv(STsdbReadHandle* pTsdbReadHandle, STableBlockInfo* pNext, bool *exists) {
  int32_t step = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? 1 : -1;
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
H
Haojun Liao 已提交
2273 2274

  while(1) {
2275
    int32_t code = loadFileDataBlock(pTsdbReadHandle, pNext->compBlock, pNext->pTableCheckInfo, exists);
H
Haojun Liao 已提交
2276 2277 2278 2279
    if (code != TSDB_CODE_SUCCESS || *exists) {
      return code;
    }

2280 2281
    if ((cur->slot == pTsdbReadHandle->numOfBlocks - 1 && ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
        (cur->slot == 0 && !ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
H
Haojun Liao 已提交
2282
      // all data blocks in current file has been checked already, try next file if exists
2283
      return getFirstFileDataBlock(pTsdbReadHandle, exists);
H
Haojun Liao 已提交
2284 2285 2286 2287
    } else {  // next block of the same file
      cur->slot += step;
      cur->mixBlock = false;
      cur->blockCompleted = false;
2288
      pNext = &pTsdbReadHandle->pDataBlockInfo[cur->slot];
H
Haojun Liao 已提交
2289 2290 2291 2292
    }
  }
}

2293 2294 2295
static int32_t getFirstFileDataBlock(STsdbReadHandle* pTsdbReadHandle, bool* exists) {
  pTsdbReadHandle->numOfBlocks = 0;
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
H
Haojun Liao 已提交
2296 2297 2298

  int32_t code = TSDB_CODE_SUCCESS;

2299
  int32_t numOfBlocks = 0;
2300
  int32_t numOfTables = (int32_t)taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
2301

2302
  STsdbCfg* pCfg = &pTsdbReadHandle->pTsdb->config;
2303 2304
  STimeWindow win = TSWINDOW_INITIALIZER;

H
Hongze Cheng 已提交
2305
  while (true) {
2306
    tsdbRLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Hongze Cheng 已提交
2307

2308 2309
    if ((pTsdbReadHandle->pFileGroup = tsdbFSIterNext(&pTsdbReadHandle->fileIter)) == NULL) {
      tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Hongze Cheng 已提交
2310 2311 2312
      break;
    }

2313
    tsdbGetFidKeyRange(pCfg->daysPerFile, pCfg->precision, pTsdbReadHandle->pFileGroup->fid, &win.skey, &win.ekey);
2314 2315

    // current file are not overlapped with query time window, ignore remain files
2316 2317 2318 2319 2320 2321 2322
    if ((ASCENDING_TRAVERSE(pTsdbReadHandle->order) && win.skey > pTsdbReadHandle->window.ekey) ||
        (!ASCENDING_TRAVERSE(pTsdbReadHandle->order) && win.ekey < pTsdbReadHandle->window.ekey)) {
      tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
      tsdbDebug("%p remain files are not qualified for qrange:%" PRId64 "-%" PRId64 ", ignore, 0x%"PRIx64, pTsdbReadHandle,
                pTsdbReadHandle->window.skey, pTsdbReadHandle->window.ekey, pTsdbReadHandle->qId);
      pTsdbReadHandle->pFileGroup = NULL;
      assert(pTsdbReadHandle->numOfBlocks == 0);
2323 2324 2325
      break;
    }

2326 2327
    if (tsdbSetAndOpenReadFSet(&pTsdbReadHandle->rhelper, pTsdbReadHandle->pFileGroup) < 0) {
      tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Hongze Cheng 已提交
2328 2329 2330 2331
      code = terrno;
      break;
    }

2332
    tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Hongze Cheng 已提交
2333

2334
    if (tsdbLoadBlockIdx(&pTsdbReadHandle->rhelper) < 0) {
H
Hongze Cheng 已提交
2335 2336 2337 2338
      code = terrno;
      break;
    }

2339
    if ((code = getFileCompInfo(pTsdbReadHandle, &numOfBlocks)) != TSDB_CODE_SUCCESS) {
2340 2341
      break;
    }
H
Haojun Liao 已提交
2342

2343 2344
    tsdbDebug("%p %d blocks found in file for %d table(s), fid:%d, 0x%"PRIx64, pTsdbReadHandle, numOfBlocks, numOfTables,
              pTsdbReadHandle->pFileGroup->fid, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
2345

2346 2347 2348 2349
    assert(numOfBlocks >= 0);
    if (numOfBlocks == 0) {
      continue;
    }
H
Haojun Liao 已提交
2350

2351
    // todo return error code to query engine
2352
    if ((code = createDataBlocksInfo(pTsdbReadHandle, numOfBlocks, &pTsdbReadHandle->numOfBlocks)) != TSDB_CODE_SUCCESS) {
2353 2354
      break;
    }
H
Haojun Liao 已提交
2355

2356 2357
    assert(numOfBlocks >= pTsdbReadHandle->numOfBlocks);
    if (pTsdbReadHandle->numOfBlocks > 0) {
2358 2359 2360
      break;
    }
  }
H
Haojun Liao 已提交
2361

2362
  // no data in file anymore
2363
  if (pTsdbReadHandle->numOfBlocks <= 0 || code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2364
    if (code == TSDB_CODE_SUCCESS) {
2365
      assert(pTsdbReadHandle->pFileGroup == NULL);
H
Haojun Liao 已提交
2366 2367
    }

D
dapan1121 已提交
2368
    cur->fid = INT32_MIN;  // denote that there are no data in file anymore
H
Haojun Liao 已提交
2369 2370
    *exists = false;
    return code;
2371
  }
H
Haojun Liao 已提交
2372

2373 2374 2375
  assert(pTsdbReadHandle->pFileGroup != NULL && pTsdbReadHandle->numOfBlocks > 0);
  cur->slot = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? 0:pTsdbReadHandle->numOfBlocks-1;
  cur->fid = pTsdbReadHandle->pFileGroup->fid;
H
Haojun Liao 已提交
2376

2377 2378
  STableBlockInfo* pBlockInfo = &pTsdbReadHandle->pDataBlockInfo[cur->slot];
  return getDataBlockRv(pTsdbReadHandle, pBlockInfo, exists);
H
Haojun Liao 已提交
2379 2380 2381 2382 2383 2384 2385
}

static bool isEndFileDataBlock(SQueryFilePos* cur, int32_t numOfBlocks, bool ascTrav) {
  assert(cur != NULL && numOfBlocks > 0);
  return (cur->slot == numOfBlocks - 1 && ascTrav) || (cur->slot == 0 && !ascTrav);
}

2386 2387
static void moveToNextDataBlockInCurrentFile(STsdbReadHandle* pTsdbReadHandle) {
  int32_t step = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? 1 : -1;
H
Haojun Liao 已提交
2388

2389 2390
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
  assert(cur->slot < pTsdbReadHandle->numOfBlocks && cur->slot >= 0);
H
Haojun Liao 已提交
2391 2392 2393 2394

  cur->slot += step;
  cur->mixBlock       = false;
  cur->blockCompleted = false;
2395
}
2396 2397 2398
#if 0
int32_t tsdbGetFileBlocksDistInfo(tsdbReadHandleT* queryHandle, STableBlockDist* pTableBlockInfo) {
  STsdbReadHandle* pTsdbReadHandle = (STsdbReadHandle*) queryHandle;
H
Haojun Liao 已提交
2399

H
Haojun Liao 已提交
2400
  pTableBlockInfo->totalSize = 0;
2401
  pTableBlockInfo->totalRows = 0;
2402
  STsdbFS* pFileHandle = REPO_FS(pTsdbReadHandle->pTsdb);
H
Haojun Liao 已提交
2403 2404

  // find the start data block in file
2405 2406 2407
  pTsdbReadHandle->locateStart = true;
  STsdbCfg* pCfg = &pTsdbReadHandle->pTsdb->config;
  int32_t   fid = getFileIdFromKey(pTsdbReadHandle->window.skey, pCfg->daysPerFile, pCfg->precision);
H
Haojun Liao 已提交
2408 2409

  tsdbRLockFS(pFileHandle);
2410 2411
  tsdbFSIterInit(&pTsdbReadHandle->fileIter, pFileHandle, pTsdbReadHandle->order);
  tsdbFSIterSeek(&pTsdbReadHandle->fileIter, fid);
H
Haojun Liao 已提交
2412 2413
  tsdbUnLockFS(pFileHandle);

H
Haojun Liao 已提交
2414
  pTableBlockInfo->numOfFiles += 1;
H
Haojun Liao 已提交
2415

H
Haojun Liao 已提交
2416
  int32_t     code = TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2417
  int32_t     numOfBlocks = 0;
2418
  int32_t     numOfTables = (int32_t)taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
2419
  int         defaultRows = TSDB_DEFAULT_BLOCK_ROWS(pCfg->maxRowsPerFileBlock);
H
Haojun Liao 已提交
2420 2421 2422 2423
  STimeWindow win = TSWINDOW_INITIALIZER;

  while (true) {
    numOfBlocks = 0;
2424
    tsdbRLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Haojun Liao 已提交
2425

2426 2427
    if ((pTsdbReadHandle->pFileGroup = tsdbFSIterNext(&pTsdbReadHandle->fileIter)) == NULL) {
      tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Haojun Liao 已提交
2428 2429 2430
      break;
    }

2431
    tsdbGetFidKeyRange(pCfg->daysPerFile, pCfg->precision, pTsdbReadHandle->pFileGroup->fid, &win.skey, &win.ekey);
H
Haojun Liao 已提交
2432 2433

    // current file are not overlapped with query time window, ignore remain files
2434 2435 2436 2437 2438 2439
    if ((ASCENDING_TRAVERSE(pTsdbReadHandle->order) && win.skey > pTsdbReadHandle->window.ekey) ||
    (!ASCENDING_TRAVERSE(pTsdbReadHandle->order) && win.ekey < pTsdbReadHandle->window.ekey)) {
      tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
      tsdbDebug("%p remain files are not qualified for qrange:%" PRId64 "-%" PRId64 ", ignore, 0x%"PRIx64, pTsdbReadHandle,
                pTsdbReadHandle->window.skey, pTsdbReadHandle->window.ekey, pTsdbReadHandle->qId);
      pTsdbReadHandle->pFileGroup = NULL;
H
Haojun Liao 已提交
2440 2441 2442
      break;
    }

H
Haojun Liao 已提交
2443
    pTableBlockInfo->numOfFiles += 1;
2444 2445
    if (tsdbSetAndOpenReadFSet(&pTsdbReadHandle->rhelper, pTsdbReadHandle->pFileGroup) < 0) {
      tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Haojun Liao 已提交
2446 2447 2448 2449
      code = terrno;
      break;
    }

2450
    tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Haojun Liao 已提交
2451

2452
    if (tsdbLoadBlockIdx(&pTsdbReadHandle->rhelper) < 0) {
H
Haojun Liao 已提交
2453 2454 2455 2456
      code = terrno;
      break;
    }

2457
    if ((code = getFileCompInfo(pTsdbReadHandle, &numOfBlocks)) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2458 2459 2460
      break;
    }

2461 2462
    tsdbDebug("%p %d blocks found in file for %d table(s), fid:%d, 0x%"PRIx64, pTsdbReadHandle, numOfBlocks, numOfTables,
              pTsdbReadHandle->pFileGroup->fid, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
2463 2464 2465 2466 2467 2468

    if (numOfBlocks == 0) {
      continue;
    }

    for (int32_t i = 0; i < numOfTables; ++i) {
2469
      STableCheckInfo* pCheckInfo = taosArrayGet(pTsdbReadHandle->pTableCheckInfo, i);
H
Haojun Liao 已提交
2470 2471 2472

      SBlock* pBlock = pCheckInfo->pCompInfo->blocks;
      for (int32_t j = 0; j < pCheckInfo->numOfBlocks; ++j) {
H
Haojun Liao 已提交
2473
        pTableBlockInfo->totalSize += pBlock[j].len;
H
Haojun Liao 已提交
2474

H
Haojun Liao 已提交
2475
        int32_t numOfRows = pBlock[j].numOfRows;
2476 2477 2478
        pTableBlockInfo->totalRows += numOfRows;
        if (numOfRows > pTableBlockInfo->maxRows) pTableBlockInfo->maxRows = numOfRows;
        if (numOfRows < pTableBlockInfo->minRows) pTableBlockInfo->minRows = numOfRows;
2479
        if (numOfRows < defaultRows) pTableBlockInfo->numOfSmallBlocks+=1;
2480 2481 2482
        int32_t  stepIndex = (numOfRows-1)/TSDB_BLOCK_DIST_STEP_ROWS;
        SFileBlockInfo *blockInfo = (SFileBlockInfo*)taosArrayGet(pTableBlockInfo->dataBlockInfos, stepIndex);
        blockInfo->numBlocksOfStep++;
H
Haojun Liao 已提交
2483 2484 2485 2486 2487 2488
      }
    }
  }

  return code;
}
2489
#endif
H
Haojun Liao 已提交
2490

2491 2492 2493
static int32_t getDataBlocksInFiles(STsdbReadHandle* pTsdbReadHandle, bool* exists) {
  STsdbFS*       pFileHandle = REPO_FS(pTsdbReadHandle->pTsdb);
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
2494 2495

  // find the start data block in file
2496 2497 2498 2499
  if (!pTsdbReadHandle->locateStart) {
    pTsdbReadHandle->locateStart = true;
    STsdbCfg* pCfg = &pTsdbReadHandle->pTsdb->config;
    int32_t   fid = getFileIdFromKey(pTsdbReadHandle->window.skey, pCfg->daysPerFile, pCfg->precision);
H
Haojun Liao 已提交
2500

H
Hongze Cheng 已提交
2501
    tsdbRLockFS(pFileHandle);
2502 2503
    tsdbFSIterInit(&pTsdbReadHandle->fileIter, pFileHandle, pTsdbReadHandle->order);
    tsdbFSIterSeek(&pTsdbReadHandle->fileIter, fid);
H
Hongze Cheng 已提交
2504
    tsdbUnLockFS(pFileHandle);
2505

2506
    return getFirstFileDataBlock(pTsdbReadHandle, exists);
2507
  } else {
2508
    // check if current file block is all consumed
2509
    STableBlockInfo* pBlockInfo = &pTsdbReadHandle->pDataBlockInfo[cur->slot];
2510
    STableCheckInfo* pCheckInfo = pBlockInfo->pTableCheckInfo;
H
Haojun Liao 已提交
2511

2512
    // current block is done, try next
H
Haojun Liao 已提交
2513
    if ((!cur->mixBlock) || cur->blockCompleted) {
H
Haojun Liao 已提交
2514
      // all data blocks in current file has been checked already, try next file if exists
2515
    } else {
2516 2517 2518 2519
      tsdbDebug("%p continue in current data block, index:%d, pos:%d, 0x%"PRIx64, pTsdbReadHandle, cur->slot, cur->pos,
                pTsdbReadHandle->qId);
      int32_t code = handleDataMergeIfNeeded(pTsdbReadHandle, pBlockInfo->compBlock, pCheckInfo);
      *exists = (pTsdbReadHandle->realNumOfRows > 0);
H
Haojun Liao 已提交
2520

H
Haojun Liao 已提交
2521 2522 2523 2524 2525 2526 2527
      if (code != TSDB_CODE_SUCCESS || *exists) {
        return code;
      }
    }

    // current block is empty, try next block in file
    // all data blocks in current file has been checked already, try next file if exists
2528 2529
    if (isEndFileDataBlock(cur, pTsdbReadHandle->numOfBlocks, ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
      return getFirstFileDataBlock(pTsdbReadHandle, exists);
H
Haojun Liao 已提交
2530
    } else {
2531 2532 2533
      moveToNextDataBlockInCurrentFile(pTsdbReadHandle);
      STableBlockInfo* pNext = &pTsdbReadHandle->pDataBlockInfo[cur->slot];
      return getDataBlockRv(pTsdbReadHandle, pNext, exists);
2534 2535
    }
  }
2536 2537
}

2538 2539
static bool doHasDataInBuffer(STsdbReadHandle* pTsdbReadHandle) {
  size_t numOfTables = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
2540
  
2541 2542
  while (pTsdbReadHandle->activeIndex < numOfTables) {
    if (hasMoreDataInCache(pTsdbReadHandle)) {
2543 2544
      return true;
    }
H
Haojun Liao 已提交
2545

2546
    pTsdbReadHandle->activeIndex += 1;
2547
  }
H
Haojun Liao 已提交
2548

2549 2550 2551
  return false;
}

2552
//todo not unref yet, since it is not support multi-group interpolation query
2553
static UNUSED_FUNC void changeQueryHandleForInterpQuery(tsdbReadHandleT pHandle) {
H
Haojun Liao 已提交
2554
  // filter the queried time stamp in the first place
2555
  STsdbReadHandle* pTsdbReadHandle = (STsdbReadHandle*) pHandle;
H
Haojun Liao 已提交
2556 2557

  // starts from the buffer in case of descending timestamp order check data blocks
2558
  size_t numOfTables = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
H
Haojun Liao 已提交
2559 2560 2561

  int32_t i = 0;
  while(i < numOfTables) {
2562
    STableCheckInfo* pCheckInfo = taosArrayGet(pTsdbReadHandle->pTableCheckInfo, i);
H
Haojun Liao 已提交
2563 2564

    // the first qualified table for interpolation query
2565 2566 2567 2568
//    if ((pTsdbReadHandle->window.skey <= pCheckInfo->pTableObj->lastKey) &&
//        (pCheckInfo->pTableObj->lastKey != TSKEY_INITIAL_VAL)) {
//      break;
//    }
H
Haojun Liao 已提交
2569 2570 2571 2572 2573 2574 2575 2576 2577

    i++;
  }

  // there are no data in all the tables
  if (i == numOfTables) {
    return;
  }

2578 2579
  STableCheckInfo info = *(STableCheckInfo*) taosArrayGet(pTsdbReadHandle->pTableCheckInfo, i);
  taosArrayClear(pTsdbReadHandle->pTableCheckInfo);
H
Haojun Liao 已提交
2580

2581 2582
  info.lastKey = pTsdbReadHandle->window.skey;
  taosArrayPush(pTsdbReadHandle->pTableCheckInfo, &info);
H
Haojun Liao 已提交
2583 2584 2585
}

static int tsdbReadRowsFromCache(STableCheckInfo* pCheckInfo, TSKEY maxKey, int maxRowsToRead, STimeWindow* win,
2586
                                 STsdbReadHandle* pTsdbReadHandle) {
H
Haojun Liao 已提交
2587
  int     numOfRows = 0;
2588 2589
  int32_t numOfCols = (int32_t)taosArrayGetSize(pTsdbReadHandle->pColumns);
  STsdbCfg* pCfg = &pTsdbReadHandle->pTsdb->config;
H
Haojun Liao 已提交
2590 2591 2592
  win->skey = TSKEY_INITIAL_VAL;

  int64_t st = taosGetTimestampUs();
D
fix bug  
dapan1121 已提交
2593 2594
  int16_t rv = -1;
  STSchema* pSchema = NULL;
H
Haojun Liao 已提交
2595 2596

  do {
2597
    SMemRow row = getSMemRowInTableMem(pCheckInfo, pTsdbReadHandle->order, pCfg->update, NULL);
H
Haojun Liao 已提交
2598 2599 2600 2601
    if (row == NULL) {
      break;
    }

C
Cary Xu 已提交
2602
    TSKEY key = memRowKey(row);
2603 2604 2605
    if ((key > maxKey && ASCENDING_TRAVERSE(pTsdbReadHandle->order)) || (key < maxKey && !ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
      tsdbDebug("%p key:%"PRIu64" beyond qrange:%"PRId64" - %"PRId64", no more data in buffer", pTsdbReadHandle, key, pTsdbReadHandle->window.skey,
                pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
2606 2607 2608 2609 2610 2611 2612 2613 2614

      break;
    }

    if (win->skey == INT64_MIN) {
      win->skey = key;
    }

    win->ekey = key;
C
Cary Xu 已提交
2615
    if (rv != memRowVersion(row)) {
2616
      pSchema = metaGetTbTSchema(pTsdbReadHandle->pTsdb->pMeta, pCheckInfo->tableId, 0);
C
Cary Xu 已提交
2617
      rv = memRowVersion(row);
D
fix bug  
dapan1121 已提交
2618
    }
2619
    mergeTwoRowFromMem(pTsdbReadHandle, maxRowsToRead, numOfRows, row, NULL, numOfCols, pCheckInfo->tableId, pSchema, NULL, true);
H
Haojun Liao 已提交
2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630

    if (++numOfRows >= maxRowsToRead) {
      moveToNextRowInMem(pCheckInfo);
      break;
    }

  } while(moveToNextRowInMem(pCheckInfo));

  assert(numOfRows <= maxRowsToRead);

  // if the buffer is not full in case of descending order query, move the data in the front of the buffer
2631
  if (!ASCENDING_TRAVERSE(pTsdbReadHandle->order) && numOfRows < maxRowsToRead) {
H
Haojun Liao 已提交
2632 2633 2634
    int32_t emptySize = maxRowsToRead - numOfRows;

    for(int32_t i = 0; i < numOfCols; ++i) {
2635
      SColumnInfoData* pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, i);
H
Haojun Liao 已提交
2636 2637 2638 2639 2640
      memmove((char*)pColInfo->pData, (char*)pColInfo->pData + emptySize * pColInfo->info.bytes, numOfRows * pColInfo->info.bytes);
    }
  }

  int64_t elapsedTime = taosGetTimestampUs() - st;
2641 2642
  tsdbDebug("%p build data block from cache completed, elapsed time:%"PRId64" us, numOfRows:%d, numOfCols:%d, 0x%"PRIx64, pTsdbReadHandle,
            elapsedTime, numOfRows, numOfCols, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
2643 2644 2645 2646 2647

  return numOfRows;
}

static int32_t getAllTableList(STable* pSuperTable, SArray* list) {
2648
  SSkipListIterator* iter = NULL;//tSkipListCreateIter(pSuperTable->pIndex);
H
Haojun Liao 已提交
2649 2650 2651
  while (tSkipListIterNext(iter)) {
    SSkipListNode* pNode = tSkipListIterGet(iter);

H
TD-1194  
Hongze Cheng 已提交
2652
    STable* pTable = (STable*) SL_GET_NODE_DATA((SSkipListNode*) pNode);
H
Haojun Liao 已提交
2653

H
TD-1194  
Hongze Cheng 已提交
2654
    STableKeyInfo info = {.pTable = pTable, .lastKey = TSKEY_INITIAL_VAL};
H
Haojun Liao 已提交
2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
    taosArrayPush(list, &info);
  }

  tSkipListDestroyIter(iter);
  return TSDB_CODE_SUCCESS;
}

static void destroyHelper(void* param) {
  if (param == NULL) {
    return;
  }

2667 2668 2669 2670 2671 2672
//  tQueryInfo* pInfo = (tQueryInfo*)param;
//  if (pInfo->optr != TSDB_RELATION_IN) {
//    tfree(pInfo->q);
//  } else {
//    taosHashCleanup((SHashObj *)(pInfo->q));
//  }
H
Haojun Liao 已提交
2673 2674 2675 2676

  free(param);
}

2677 2678 2679 2680 2681
#define TSDB_PREV_ROW  0x1
#define TSDB_NEXT_ROW  0x2

static bool  loadBlockOfActiveTable(STsdbReadHandle* pTsdbReadHandle) {
  if (pTsdbReadHandle->checkFiles) {
H
Haojun Liao 已提交
2682 2683
    // check if the query range overlaps with the file data block
    bool exists = true;
H
Haojun Liao 已提交
2684

2685
    int32_t code = getDataBlocksInFiles(pTsdbReadHandle, &exists);
H
Haojun Liao 已提交
2686
    if (code != TSDB_CODE_SUCCESS) {
2687
      pTsdbReadHandle->checkFiles = false;
H
Haojun Liao 已提交
2688 2689
      return false;
    }
H
Haojun Liao 已提交
2690

H
Haojun Liao 已提交
2691
    if (exists) {
2692 2693 2694 2695
      tsdbRetrieveDataBlock((tsdbReadHandleT*) pTsdbReadHandle, NULL);
      if (pTsdbReadHandle->currentLoadExternalRows && pTsdbReadHandle->window.skey == pTsdbReadHandle->window.ekey) {
        SColumnInfoData* pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, 0);
        assert(*(int64_t*)pColInfo->pData == pTsdbReadHandle->window.skey);
H
Haojun Liao 已提交
2696 2697
      }

2698
      pTsdbReadHandle->currentLoadExternalRows = false; // clear the flag, since the exact matched row is found.
H
Haojun Liao 已提交
2699 2700
      return exists;
    }
H
Haojun Liao 已提交
2701

2702
    pTsdbReadHandle->checkFiles = false;
H
Haojun Liao 已提交
2703
  }
H
Haojun Liao 已提交
2704

2705 2706
  if (hasMoreDataInCache(pTsdbReadHandle)) {
    pTsdbReadHandle->currentLoadExternalRows = false;
H
Haojun Liao 已提交
2707 2708
    return true;
  }
H
Haojun Liao 已提交
2709

H
Haojun Liao 已提交
2710
  // current result is empty
2711 2712
  if (pTsdbReadHandle->currentLoadExternalRows && pTsdbReadHandle->window.skey == pTsdbReadHandle->window.ekey && pTsdbReadHandle->cur.rows == 0) {
//    STsdbMemTable* pMemRef = pTsdbReadHandle->pMemTable;
H
Haojun Liao 已提交
2713

2714 2715
//    doGetExternalRow(pTsdbReadHandle, TSDB_PREV_ROW, pMemRef);
//    doGetExternalRow(pTsdbReadHandle, TSDB_NEXT_ROW, pMemRef);
H
Haojun Liao 已提交
2716

2717
    bool result = tsdbGetExternalRow(pTsdbReadHandle);
H
Haojun Liao 已提交
2718

2719 2720 2721
//    pTsdbReadHandle->prev = doFreeColumnInfoData(pTsdbReadHandle->prev);
//    pTsdbReadHandle->next = doFreeColumnInfoData(pTsdbReadHandle->next);
    pTsdbReadHandle->currentLoadExternalRows = false;
H
Haojun Liao 已提交
2722 2723

    return result;
2724
  }
H
Haojun Liao 已提交
2725

H
Haojun Liao 已提交
2726 2727
  return false;
}
2728

2729
static bool loadCachedLastRow(STsdbReadHandle* pTsdbReadHandle) {
H
Haojun Liao 已提交
2730
  // the last row is cached in buffer, return it directly.
2731 2732 2733
  // here note that the pTsdbReadHandle->window must be the TS_INITIALIZER
  int32_t numOfCols  = (int32_t)(QH_GET_NUM_OF_COLS(pTsdbReadHandle));
  size_t  numOfTables = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
H
Haojun Liao 已提交
2734 2735
  assert(numOfTables > 0 && numOfCols > 0);

2736
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
2737

C
Cary Xu 已提交
2738
  SMemRow  pRow = NULL;
H
Haojun Liao 已提交
2739
  TSKEY    key  = TSKEY_INITIAL_VAL;
2740 2741 2742 2743 2744 2745 2746 2747 2748
  int32_t  step = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? 1:-1;

  if (++pTsdbReadHandle->activeIndex < numOfTables) {
    STableCheckInfo* pCheckInfo = taosArrayGet(pTsdbReadHandle->pTableCheckInfo, pTsdbReadHandle->activeIndex);
//    int32_t ret = tsdbGetCachedLastRow(pCheckInfo->pTableObj, &pRow, &key);
//    if (ret != TSDB_CODE_SUCCESS) {
//      return false;
//    }
    mergeTwoRowFromMem(pTsdbReadHandle, pTsdbReadHandle->outputCapacity, 0, pRow, NULL, numOfCols, pCheckInfo->pTableObj, NULL, NULL, true);
H
Haojun Liao 已提交
2749
    tfree(pRow);
H
Haojun Liao 已提交
2750

H
Haojun Liao 已提交
2751 2752 2753 2754 2755 2756 2757 2758 2759 2760
    // update the last key value
    pCheckInfo->lastKey = key + step;

    cur->rows     = 1;  // only one row
    cur->lastKey  = key + step;
    cur->mixBlock = true;
    cur->win.skey = key;
    cur->win.ekey = key;

    return true;
2761
  }
H
Haojun Liao 已提交
2762

H
Haojun Liao 已提交
2763 2764 2765
  return false;
}

D
init  
dapan1121 已提交
2766

D
update  
dapan1121 已提交
2767

2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919
//static bool loadCachedLast(STsdbReadHandle* pTsdbReadHandle) {
//  // the last row is cached in buffer, return it directly.
//  // here note that the pTsdbReadHandle->window must be the TS_INITIALIZER
//  int32_t tgNumOfCols = (int32_t)QH_GET_NUM_OF_COLS(pTsdbReadHandle);
//  size_t  numOfTables = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
//  int32_t numOfRows = 0;
//  assert(numOfTables > 0 && tgNumOfCols > 0);
//  SQueryFilePos* cur = &pTsdbReadHandle->cur;
//  TSKEY priKey = TSKEY_INITIAL_VAL;
//  int32_t priIdx = -1;
//  SColumnInfoData* pColInfo = NULL;
//
//  while (++pTsdbReadHandle->activeIndex < numOfTables) {
//    STableCheckInfo* pCheckInfo = taosArrayGet(pTsdbReadHandle->pTableCheckInfo, pTsdbReadHandle->activeIndex);
//    STable* pTable = pCheckInfo->pTableObj;
//    char* pData = NULL;
//
//    int32_t numOfCols = pTable->maxColNum;
//
//    if (pTable->lastCols == NULL || pTable->maxColNum <= 0) {
//      tsdbWarn("no last cached for table %s, uid:%" PRIu64 ",tid:%d", pTable->name->data, pTable->uid, pTable->tableId);
//      continue;
//    }
//
//    int32_t i = 0, j = 0;
//    while(i < tgNumOfCols && j < numOfCols) {
//      pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, i);
//      if (pTable->lastCols[j].colId < pColInfo->info.colId) {
//        j++;
//        continue;
//      } else if (pTable->lastCols[j].colId > pColInfo->info.colId) {
//        i++;
//        continue;
//      }
//
//      pData = (char*)pColInfo->pData + numOfRows * pColInfo->info.bytes;
//
//      if (pTable->lastCols[j].bytes > 0) {
//        void* value = pTable->lastCols[j].pData;
//        switch (pColInfo->info.type) {
//          case TSDB_DATA_TYPE_BINARY:
//          case TSDB_DATA_TYPE_NCHAR:
//            memcpy(pData, value, varDataTLen(value));
//            break;
//          case TSDB_DATA_TYPE_NULL:
//          case TSDB_DATA_TYPE_BOOL:
//          case TSDB_DATA_TYPE_TINYINT:
//          case TSDB_DATA_TYPE_UTINYINT:
//            *(uint8_t *)pData = *(uint8_t *)value;
//            break;
//          case TSDB_DATA_TYPE_SMALLINT:
//          case TSDB_DATA_TYPE_USMALLINT:
//            *(uint16_t *)pData = *(uint16_t *)value;
//            break;
//          case TSDB_DATA_TYPE_INT:
//          case TSDB_DATA_TYPE_UINT:
//            *(uint32_t *)pData = *(uint32_t *)value;
//            break;
//          case TSDB_DATA_TYPE_BIGINT:
//          case TSDB_DATA_TYPE_UBIGINT:
//            *(uint64_t *)pData = *(uint64_t *)value;
//            break;
//          case TSDB_DATA_TYPE_FLOAT:
//            SET_FLOAT_PTR(pData, value);
//            break;
//          case TSDB_DATA_TYPE_DOUBLE:
//            SET_DOUBLE_PTR(pData, value);
//            break;
//          case TSDB_DATA_TYPE_TIMESTAMP:
//            if (pColInfo->info.colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
//              priKey = tdGetKey(*(TKEY *)value);
//              priIdx = i;
//
//              i++;
//              j++;
//              continue;
//            } else {
//              *(TSKEY *)pData = *(TSKEY *)value;
//            }
//            break;
//          default:
//            memcpy(pData, value, pColInfo->info.bytes);
//        }
//
//        for (int32_t n = 0; n < tgNumOfCols; ++n) {
//          if (n == i) {
//            continue;
//          }
//
//          pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, n);
//          pData = (char*)pColInfo->pData + numOfRows * pColInfo->info.bytes;;
//
//          if (pColInfo->info.colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
////            *(TSKEY *)pData = pTable->lastCols[j].ts;
//            continue;
//          }
//
//          if (pColInfo->info.type == TSDB_DATA_TYPE_BINARY || pColInfo->info.type == TSDB_DATA_TYPE_NCHAR) {
//            setVardataNull(pData, pColInfo->info.type);
//          } else {
//            setNull(pData, pColInfo->info.type, pColInfo->info.bytes);
//          }
//        }
//
//        numOfRows++;
//        assert(numOfRows < pTsdbReadHandle->outputCapacity);
//      }
//
//      i++;
//      j++;
//    }
//
//    // leave the real ts column as the last row, because last function only (not stable) use the last row as res
//    if (priKey != TSKEY_INITIAL_VAL) {
//      pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, priIdx);
//      pData = (char*)pColInfo->pData + numOfRows * pColInfo->info.bytes;
//
//      *(TSKEY *)pData = priKey;
//
//      for (int32_t n = 0; n < tgNumOfCols; ++n) {
//        if (n == priIdx) {
//          continue;
//        }
//
//        pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, n);
//        pData = (char*)pColInfo->pData + numOfRows * pColInfo->info.bytes;;
//
//        assert (pColInfo->info.colId != PRIMARYKEY_TIMESTAMP_COL_ID);
//
//        if (pColInfo->info.type == TSDB_DATA_TYPE_BINARY || pColInfo->info.type == TSDB_DATA_TYPE_NCHAR) {
//          setVardataNull(pData, pColInfo->info.type);
//        } else {
//          setNull(pData, pColInfo->info.type, pColInfo->info.bytes);
//        }
//      }
//
//      numOfRows++;
//    }
//
//    if (numOfRows > 0) {
//      cur->rows     = numOfRows;
//      cur->mixBlock = true;
//
//      return true;
//    }
//  }
//
//  return false;
//}

static bool loadDataBlockFromTableSeq(STsdbReadHandle* pTsdbReadHandle) {
  size_t numOfTables = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
H
Haojun Liao 已提交
2920 2921 2922
  assert(numOfTables > 0);

  int64_t stime = taosGetTimestampUs();
H
Haojun Liao 已提交
2923

2924 2925
  while(pTsdbReadHandle->activeIndex < numOfTables) {
    if (loadBlockOfActiveTable(pTsdbReadHandle)) {
H
Haojun Liao 已提交
2926 2927 2928
      return true;
    }

2929
    STableCheckInfo* pCheckInfo = taosArrayGet(pTsdbReadHandle->pTableCheckInfo, pTsdbReadHandle->activeIndex);
H
Haojun Liao 已提交
2930 2931
    pCheckInfo->numOfBlocks = 0;

2932 2933 2934 2935 2936
    pTsdbReadHandle->activeIndex += 1;
    pTsdbReadHandle->locateStart = false;
    pTsdbReadHandle->checkFiles  = true;
    pTsdbReadHandle->cur.rows    = 0;
    pTsdbReadHandle->currentLoadExternalRows = pTsdbReadHandle->loadExternalRow;
H
Haojun Liao 已提交
2937 2938 2939 2940

    terrno = TSDB_CODE_SUCCESS;

    int64_t elapsedTime = taosGetTimestampUs() - stime;
2941
    pTsdbReadHandle->cost.checkForNextTime += elapsedTime;
H
Haojun Liao 已提交
2942 2943 2944
  }

  return false;
2945 2946
}

H
Haojun Liao 已提交
2947
// handle data in cache situation
2948 2949
bool tsdbNextDataBlock(tsdbReadHandleT pHandle) {
  STsdbReadHandle* pTsdbReadHandle = (STsdbReadHandle*) pHandle;
Y
yihaoDeng 已提交
2950

2951 2952
  if (emptyQueryTimewindow(pTsdbReadHandle)) {
    tsdbDebug("%p query window not overlaps with the data set, no result returned, 0x%"PRIx64, pTsdbReadHandle, pTsdbReadHandle->qId);
2953 2954 2955
    return false;
  }

Y
yihaoDeng 已提交
2956 2957 2958
  int64_t stime = taosGetTimestampUs();
  int64_t elapsedTime = stime;

2959
  // TODO refactor: remove "type"
2960 2961 2962 2963 2964
  if (pTsdbReadHandle->type == TSDB_QUERY_TYPE_LAST) {
    if (pTsdbReadHandle->cachelastrow == TSDB_CACHED_TYPE_LASTROW) {
//      return loadCachedLastRow(pTsdbReadHandle);
    } else if (pTsdbReadHandle->cachelastrow == TSDB_CACHED_TYPE_LAST) {
//      return loadCachedLast(pTsdbReadHandle);
D
init  
dapan1121 已提交
2965
    }
H
Haojun Liao 已提交
2966
  }
Y
yihaoDeng 已提交
2967

2968 2969
  if (pTsdbReadHandle->loadType == BLOCK_LOAD_TABLE_SEQ_ORDER) {
    return loadDataBlockFromTableSeq(pTsdbReadHandle);
H
Haojun Liao 已提交
2970
  } else { // loadType == RR and Offset Order
2971
    if (pTsdbReadHandle->checkFiles) {
H
Haojun Liao 已提交
2972 2973 2974
      // check if the query range overlaps with the file data block
      bool exists = true;

2975
      int32_t code = getDataBlocksInFiles(pTsdbReadHandle, &exists);
H
Haojun Liao 已提交
2976
      if (code != TSDB_CODE_SUCCESS) {
2977 2978
        pTsdbReadHandle->activeIndex = 0;
        pTsdbReadHandle->checkFiles = false;
H
Haojun Liao 已提交
2979 2980 2981 2982 2983

        return false;
      }

      if (exists) {
2984
        pTsdbReadHandle->cost.checkForNextTime += (taosGetTimestampUs() - stime);
H
Haojun Liao 已提交
2985 2986
        return exists;
      }
Y
yihaoDeng 已提交
2987

2988 2989
      pTsdbReadHandle->activeIndex = 0;
      pTsdbReadHandle->checkFiles = false;
Y
yihaoDeng 已提交
2990 2991
    }

H
Haojun Liao 已提交
2992
    // TODO: opt by consider the scan order
2993
    bool ret = doHasDataInBuffer(pTsdbReadHandle);
H
Haojun Liao 已提交
2994
    terrno = TSDB_CODE_SUCCESS;
Y
yihaoDeng 已提交
2995

H
Haojun Liao 已提交
2996
    elapsedTime = taosGetTimestampUs() - stime;
2997
    pTsdbReadHandle->cost.checkForNextTime += elapsedTime;
H
Haojun Liao 已提交
2998
    return ret;
Y
yihaoDeng 已提交
2999 3000
  }
}
3001

3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114
//static int32_t doGetExternalRow(STsdbReadHandle* pTsdbReadHandle, int16_t type, STsdbMemTable* pMemRef) {
//  STsdbReadHandle* pSecQueryHandle = NULL;
//
//  if (type == TSDB_PREV_ROW && pTsdbReadHandle->prev) {
//    return TSDB_CODE_SUCCESS;
//  }
//
//  if (type == TSDB_NEXT_ROW && pTsdbReadHandle->next) {
//    return TSDB_CODE_SUCCESS;
//  }
//
//  // prepare the structure
//  int32_t numOfCols = (int32_t) QH_GET_NUM_OF_COLS(pTsdbReadHandle);
//
//  if (type == TSDB_PREV_ROW) {
//    pTsdbReadHandle->prev = taosArrayInit(numOfCols, sizeof(SColumnInfoData));
//    if (pTsdbReadHandle->prev == NULL) {
//      terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
//      goto out_of_memory;
//    }
//  } else {
//    pTsdbReadHandle->next = taosArrayInit(numOfCols, sizeof(SColumnInfoData));
//    if (pTsdbReadHandle->next == NULL) {
//      terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
//      goto out_of_memory;
//    }
//  }
//
//  SArray* row = (type == TSDB_PREV_ROW)? pTsdbReadHandle->prev : pTsdbReadHandle->next;
//
//  for (int32_t i = 0; i < numOfCols; ++i) {
//    SColumnInfoData* pCol = taosArrayGet(pTsdbReadHandle->pColumns, i);
//
//    SColumnInfoData colInfo = {{0}, 0};
//    colInfo.info = pCol->info;
//    colInfo.pData = calloc(1, pCol->info.bytes);
//    if (colInfo.pData == NULL) {
//      terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
//      goto out_of_memory;
//    }
//
//    taosArrayPush(row, &colInfo);
//  }
//
//  // load the previous row
//  STsdbQueryCond cond = {.numOfCols = numOfCols, .loadExternalRows = false, .type = BLOCK_LOAD_OFFSET_SEQ_ORDER};
//  if (type == TSDB_PREV_ROW) {
//    cond.order = TSDB_ORDER_DESC;
//    cond.twindow = (STimeWindow){pTsdbReadHandle->window.skey, INT64_MIN};
//  } else {
//    cond.order = TSDB_ORDER_ASC;
//    cond.twindow = (STimeWindow){pTsdbReadHandle->window.skey, INT64_MAX};
//  }
//
//  cond.colList = calloc(cond.numOfCols, sizeof(SColumnInfo));
//  if (cond.colList == NULL) {
//    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
//    goto out_of_memory;
//  }
//
//  for (int32_t i = 0; i < cond.numOfCols; ++i) {
//    SColumnInfoData* pColInfoData = taosArrayGet(pTsdbReadHandle->pColumns, i);
//    memcpy(&cond.colList[i], &pColInfoData->info, sizeof(SColumnInfo));
//  }
//
//  pSecQueryHandle = tsdbQueryTablesImpl(pTsdbReadHandle->pTsdb, &cond, pTsdbReadHandle->qId, pMemRef);
//  tfree(cond.colList);
//
//  // current table, only one table
//  STableCheckInfo* pCurrent = taosArrayGet(pTsdbReadHandle->pTableCheckInfo, pTsdbReadHandle->activeIndex);
//
//  SArray* psTable = NULL;
//  pSecQueryHandle->pTableCheckInfo = createCheckInfoFromCheckInfo(pCurrent, pSecQueryHandle->window.skey, &psTable);
//  if (pSecQueryHandle->pTableCheckInfo == NULL) {
//    taosArrayDestroy(psTable);
//    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
//    goto out_of_memory;
//  }
//
//
//  tsdbMayTakeMemSnapshot(pSecQueryHandle, psTable);
//  if (!tsdbNextDataBlock((void*)pSecQueryHandle)) {
//    // no result in current query, free the corresponding result rows structure
//    if (type == TSDB_PREV_ROW) {
//      pTsdbReadHandle->prev = doFreeColumnInfoData(pTsdbReadHandle->prev);
//    } else {
//      pTsdbReadHandle->next = doFreeColumnInfoData(pTsdbReadHandle->next);
//    }
//
//    goto out_of_memory;
//  }
//
//  SDataBlockInfo blockInfo = {{0}, 0};
//  tsdbRetrieveDataBlockInfo((void*)pSecQueryHandle, &blockInfo);
//  tsdbRetrieveDataBlock((void*)pSecQueryHandle, pSecQueryHandle->defaultLoadColumn);
//
//  row = (type == TSDB_PREV_ROW)? pTsdbReadHandle->prev:pTsdbReadHandle->next;
//  int32_t pos = (type == TSDB_PREV_ROW)?pSecQueryHandle->cur.rows - 1:0;
//
//  for (int32_t i = 0; i < numOfCols; ++i) {
//    SColumnInfoData* pCol = taosArrayGet(row, i);
//    SColumnInfoData* s = taosArrayGet(pSecQueryHandle->pColumns, i);
//    memcpy((char*)pCol->pData, (char*)s->pData + s->info.bytes * pos, pCol->info.bytes);
//  }
//
//out_of_memory:
//  tsdbCleanupQueryHandle(pSecQueryHandle);
//  return terrno;
//}

bool tsdbGetExternalRow(tsdbReadHandleT pHandle) {
  STsdbReadHandle* pTsdbReadHandle = (STsdbReadHandle*) pHandle;
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
H
Haojun Liao 已提交
3115

H
Haojun Liao 已提交
3116 3117
  cur->fid = INT32_MIN;
  cur->mixBlock = true;
3118
  if (pTsdbReadHandle->prev == NULL || pTsdbReadHandle->next == NULL) {
H
Haojun Liao 已提交
3119 3120
    cur->rows = 0;
    return false;
H
Haojun Liao 已提交
3121 3122
  }

3123
  int32_t numOfCols = (int32_t) QH_GET_NUM_OF_COLS(pTsdbReadHandle);
H
Haojun Liao 已提交
3124
  for (int32_t i = 0; i < numOfCols; ++i) {
3125 3126
    SColumnInfoData* pColInfoData = taosArrayGet(pTsdbReadHandle->pColumns, i);
    SColumnInfoData* first = taosArrayGet(pTsdbReadHandle->prev, i);
H
Haojun Liao 已提交
3127 3128 3129

    memcpy(pColInfoData->pData, first->pData, pColInfoData->info.bytes);

3130
    SColumnInfoData* sec = taosArrayGet(pTsdbReadHandle->next, i);
sangshuduo's avatar
sangshuduo 已提交
3131
    memcpy(((char*)pColInfoData->pData) + pColInfoData->info.bytes, sec->pData, pColInfoData->info.bytes);
H
Haojun Liao 已提交
3132 3133

    if (i == 0 && pColInfoData->info.type == TSDB_DATA_TYPE_TIMESTAMP) {
H
Haojun Liao 已提交
3134
      cur->win.skey = *(TSKEY*)pColInfoData->pData;
sangshuduo's avatar
sangshuduo 已提交
3135
      cur->win.ekey = *(TSKEY*)(((char*)pColInfoData->pData) + TSDB_KEYSIZE);
H
Haojun Liao 已提交
3136 3137 3138
    }
  }

H
Haojun Liao 已提交
3139 3140
  cur->rows = 2;
  return true;
3141 3142
}

3143
/*
3144
 * if lastRow == NULL, return TSDB_CODE_TDB_NO_CACHE_LAST_ROW
3145
 * else set pRes and return TSDB_CODE_SUCCESS and save lastKey
3146
 */
3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170
//int32_t tsdbGetCachedLastRow(STable* pTable, SMemRow* pRes, TSKEY* lastKey) {
//  int32_t code = TSDB_CODE_SUCCESS;
//
//  TSDB_RLOCK_TABLE(pTable);
//
//  if (!pTable->lastRow) {
//    code = TSDB_CODE_TDB_NO_CACHE_LAST_ROW;
//    goto out;
//  }
//
//  if (pRes) {
//    *pRes = tdMemRowDup(pTable->lastRow);
//    if (*pRes == NULL) {
//      code = TSDB_CODE_TDB_OUT_OF_MEMORY;
//    }
//  }
//
//out:
//  TSDB_RUNLOCK_TABLE(pTable);
//  return code;
//}

bool isTsdbCacheLastRow(tsdbReadHandleT* pTsdbReadHandle) {
  return ((STsdbReadHandle *)pTsdbReadHandle)->cachelastrow > TSDB_CACHED_TYPE_NONE;
D
fix bug  
dapan1121 已提交
3171 3172
}

3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199
int32_t checkForCachedLastRow(STsdbReadHandle* pTsdbReadHandle, STableGroupInfo *groupList) {
  assert(pTsdbReadHandle != NULL && groupList != NULL);

//  TSKEY    key = TSKEY_INITIAL_VAL;
//
//  SArray* group = taosArrayGetP(groupList->pGroupList, 0);
//  assert(group != NULL);
//
//  STableKeyInfo* pInfo = (STableKeyInfo*)taosArrayGet(group, 0);
//
//  int32_t code = 0;
//
//  if (((STable*)pInfo->pTable)->lastRow) {
//    code = tsdbGetCachedLastRow(pInfo->pTable, NULL, &key);
//    if (code != TSDB_CODE_SUCCESS) {
//      pTsdbReadHandle->cachelastrow = TSDB_CACHED_TYPE_NONE;
//    } else {
//      pTsdbReadHandle->cachelastrow = TSDB_CACHED_TYPE_LASTROW;
//    }
//  }
//
//  // update the tsdb query time range
//  if (pTsdbReadHandle->cachelastrow != TSDB_CACHED_TYPE_NONE) {
//    pTsdbReadHandle->window      = TSWINDOW_INITIALIZER;
//    pTsdbReadHandle->checkFiles  = false;
//    pTsdbReadHandle->activeIndex = -1;  // start from -1
//  }
H
Haojun Liao 已提交
3200

3201
  return TSDB_CODE_SUCCESS;
3202 3203
}

3204 3205
int32_t checkForCachedLast(STsdbReadHandle* pTsdbReadHandle) {
  assert(pTsdbReadHandle != NULL);
D
update  
dapan1121 已提交
3206 3207

  int32_t code = 0;
3208 3209 3210
//  if (pTsdbReadHandle->pTsdb && atomic_load_8(&pTsdbReadHandle->pTsdb->hasCachedLastColumn)){
//    pTsdbReadHandle->cachelastrow = TSDB_CACHED_TYPE_LAST;
//  }
D
update  
dapan1121 已提交
3211 3212

  // update the tsdb query time range
3213 3214 3215
  if (pTsdbReadHandle->cachelastrow) {
    pTsdbReadHandle->checkFiles  = false;
    pTsdbReadHandle->activeIndex = -1;  // start from -1
D
update  
dapan1121 已提交
3216 3217 3218 3219 3220 3221
  }

  return code;
}


3222
STimeWindow updateLastrowForEachGroup(STableGroupInfo *groupList) {
H
Haojun Liao 已提交
3223
  STimeWindow window = {INT64_MAX, INT64_MIN};
H
Haojun Liao 已提交
3224

H
Haojun Liao 已提交
3225
  int32_t totalNumOfTable = 0;
3226
  SArray* emptyGroup = taosArrayInit(16, sizeof(int32_t));
H
Haojun Liao 已提交
3227

H
Haojun Liao 已提交
3228 3229 3230 3231 3232
  // NOTE: starts from the buffer in case of descending timestamp order check data blocks
  size_t numOfGroups = taosArrayGetSize(groupList->pGroupList);
  for(int32_t j = 0; j < numOfGroups; ++j) {
    SArray* pGroup = taosArrayGetP(groupList->pGroupList, j);
    TSKEY   key = TSKEY_INITIAL_VAL;
H
Haojun Liao 已提交
3233

H
Haojun Liao 已提交
3234
    STableKeyInfo keyInfo = {0};
H
Haojun Liao 已提交
3235

H
Haojun Liao 已提交
3236 3237
    size_t numOfTables = taosArrayGetSize(pGroup);
    for(int32_t i = 0; i < numOfTables; ++i) {
3238
      STableKeyInfo* pInfo = (STableKeyInfo*) taosArrayGet(pGroup, i);
H
Haojun Liao 已提交
3239

H
Haojun Liao 已提交
3240
      // if the lastKey equals to INT64_MIN, there is no data in this table
3241
      TSKEY lastKey = 0;//((STable*)(pInfo->pTable))->lastKey;
H
Haojun Liao 已提交
3242 3243
      if (key < lastKey) {
        key = lastKey;
H
Haojun Liao 已提交
3244

3245
        keyInfo.pTable  = pInfo->pTable;
H
Haojun Liao 已提交
3246
        keyInfo.lastKey = key;
3247
        pInfo->lastKey  = key;
H
Haojun Liao 已提交
3248

H
Haojun Liao 已提交
3249 3250 3251
        if (key < window.skey) {
          window.skey = key;
        }
3252

H
Haojun Liao 已提交
3253 3254 3255 3256
        if (key > window.ekey) {
          window.ekey = key;
        }
      }
3257
    }
H
Haojun Liao 已提交
3258

H
Hongze Cheng 已提交
3259 3260
    // clear current group, unref unused table
    for (int32_t i = 0; i < numOfTables; ++i) {
3261
      STableKeyInfo* pInfo = (STableKeyInfo*)taosArrayGet(pGroup, i);
H
Hongze Cheng 已提交
3262 3263

      // keyInfo.pTable may be NULL here.
3264
      if (pInfo->pTable != keyInfo.pTable) {
3265
//        tsdbUnRefTable(pInfo->pTable);
H
Hongze Cheng 已提交
3266 3267 3268
      }
    }

H
Haojun Liao 已提交
3269
    // more than one table in each group, only one table left for each group
H
Haojun Liao 已提交
3270 3271
    if (keyInfo.pTable != NULL) {
      totalNumOfTable++;
3272 3273 3274 3275 3276 3277 3278
      if (taosArrayGetSize(pGroup) == 1) {
        // do nothing
      } else {
        taosArrayClear(pGroup);
        taosArrayPush(pGroup, &keyInfo);
      }
    } else {  // mark all the empty groups, and remove it later
3279
      taosArrayDestroy(pGroup);
3280
      taosArrayPush(emptyGroup, &j);
3281 3282
    }
  }
H
Haojun Liao 已提交
3283

H
Haojun Liao 已提交
3284 3285 3286
  // window does not being updated, so set the original
  if (window.skey == INT64_MAX && window.ekey == INT64_MIN) {
    window = TSWINDOW_INITIALIZER;
H
Haojun Liao 已提交
3287
    assert(totalNumOfTable == 0 && taosArrayGetSize(groupList->pGroupList) == numOfGroups);
H
Haojun Liao 已提交
3288 3289
  }

H
Haojun Liao 已提交
3290
  taosArrayRemoveBatch(groupList->pGroupList, TARRAY_GET_START(emptyGroup), (int32_t) taosArrayGetSize(emptyGroup));
3291 3292
  taosArrayDestroy(emptyGroup);

H
Haojun Liao 已提交
3293
  groupList->numOfTables = totalNumOfTable;
H
Haojun Liao 已提交
3294
  return window;
H
hjxilinx 已提交
3295 3296
}

3297 3298
void tsdbRetrieveDataBlockInfo(tsdbReadHandleT* pTsdbReadHandle, SDataBlockInfo* pDataBlockInfo) {
  STsdbReadHandle* pHandle = (STsdbReadHandle*)pTsdbReadHandle;
3299
  SQueryFilePos* cur = &pHandle->cur;
3300 3301

  uint64_t uid = 0;
H
Haojun Liao 已提交
3302

3303
  // there are data in file
D
dapan1121 已提交
3304
  if (pHandle->cur.fid != INT32_MIN) {
3305
    STableBlockInfo* pBlockInfo = &pHandle->pDataBlockInfo[cur->slot];
3306
    uid = pBlockInfo->pTableCheckInfo->tableId;
H
[td-32]  
hjxilinx 已提交
3307
  } else {
3308
    STableCheckInfo* pCheckInfo = taosArrayGet(pHandle->pTableCheckInfo, pHandle->activeIndex);
3309
    uid = pCheckInfo->tableId;
3310
  }
3311

3312 3313
  pDataBlockInfo->uid    = uid;
  pDataBlockInfo->rows   = cur->rows;
H
Haojun Liao 已提交
3314
  pDataBlockInfo->window = cur->win;
S
TD-1057  
Shengliang Guan 已提交
3315
  pDataBlockInfo->numOfCols = (int32_t)(QH_GET_NUM_OF_COLS(pHandle));
3316
}
H
hjxilinx 已提交
3317

H
Haojun Liao 已提交
3318 3319 3320
/*
 * return null for mixed data block, if not a complete file data block, the statistics value will always return NULL
 */
3321 3322
int32_t tsdbRetrieveDataBlockStatisInfo(tsdbReadHandleT* pTsdbReadHandle, SDataStatis** pBlockStatis) {
  STsdbReadHandle* pHandle = (STsdbReadHandle*) pTsdbReadHandle;
H
Haojun Liao 已提交
3323

H
Haojun Liao 已提交
3324 3325
  SQueryFilePos* c = &pHandle->cur;
  if (c->mixBlock) {
H
Haojun Liao 已提交
3326 3327 3328
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
  }
H
Haojun Liao 已提交
3329

H
Haojun Liao 已提交
3330 3331 3332 3333
  STableBlockInfo* pBlockInfo = &pHandle->pDataBlockInfo[c->slot];
  assert((c->slot >= 0 && c->slot < pHandle->numOfBlocks) || ((c->slot == pHandle->numOfBlocks) && (c->slot == 0)));

  // file block with sub-blocks has no statistics data
H
Haojun Liao 已提交
3334 3335 3336 3337
  if (pBlockInfo->compBlock->numOfSubBlocks > 1) {
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
  }
H
Haojun Liao 已提交
3338 3339

  int64_t stime = taosGetTimestampUs();
H
Hongze Cheng 已提交
3340 3341 3342
  if (tsdbLoadBlockStatis(&pHandle->rhelper, pBlockInfo->compBlock) < 0) {
    return terrno;
  }
H
Haojun Liao 已提交
3343

H
Haojun Liao 已提交
3344 3345
  int16_t* colIds = pHandle->defaultLoadColumn->pData;

H
Haojun Liao 已提交
3346
  size_t numOfCols = QH_GET_NUM_OF_COLS(pHandle);
H
Haojun Liao 已提交
3347
  memset(pHandle->statis, 0, numOfCols * sizeof(SDataStatis));
3348
  for(int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
3349
    pHandle->statis[i].colId = colIds[i];
3350
  }
H
Haojun Liao 已提交
3351

H
Hongze Cheng 已提交
3352
  tsdbGetBlockStatis(&pHandle->rhelper, pHandle->statis, (int)numOfCols);
H
Haojun Liao 已提交
3353 3354 3355

  // always load the first primary timestamp column data
  SDataStatis* pPrimaryColStatis = &pHandle->statis[0];
3356
  assert(pPrimaryColStatis->colId == PRIMARYKEY_TIMESTAMP_COL_ID);
H
Haojun Liao 已提交
3357 3358 3359 3360 3361

  pPrimaryColStatis->numOfNull = 0;
  pPrimaryColStatis->min = pBlockInfo->compBlock->keyFirst;
  pPrimaryColStatis->max = pBlockInfo->compBlock->keyLast;

H
Haojun Liao 已提交
3362
  //update the number of NULL data rows
H
Haojun Liao 已提交
3363
  for(int32_t i = 1; i < numOfCols; ++i) {
3364
    if (pHandle->statis[i].numOfNull == -1) { // set the column data are all NULL
H
Haojun Liao 已提交
3365 3366 3367
      pHandle->statis[i].numOfNull = pBlockInfo->compBlock->numOfRows;
    }
  }
H
Haojun Liao 已提交
3368 3369 3370 3371

  int64_t elapsed = taosGetTimestampUs() - stime;
  pHandle->cost.statisInfoLoadTime += elapsed;

H
Haojun Liao 已提交
3372
  *pBlockStatis = pHandle->statis;
3373
  return TSDB_CODE_SUCCESS;
H
hjxilinx 已提交
3374 3375
}

3376
SArray* tsdbRetrieveDataBlock(tsdbReadHandleT* pTsdbReadHandle, SArray* pIdList) {
H
[td-32]  
hjxilinx 已提交
3377
  /**
H
hjxilinx 已提交
3378
   * In the following two cases, the data has been loaded to SColumnInfoData.
H
[td-32]  
hjxilinx 已提交
3379 3380
   * 1. data is from cache, 2. data block is not completed qualified to query time range
   */
3381
  STsdbReadHandle* pHandle = (STsdbReadHandle*)pTsdbReadHandle;
3382

D
dapan1121 已提交
3383
  if (pHandle->cur.fid == INT32_MIN) {
H
[td-32]  
hjxilinx 已提交
3384 3385
    return pHandle->pColumns;
  } else {
H
Haojun Liao 已提交
3386 3387
    STableBlockInfo* pBlockInfo = &pHandle->pDataBlockInfo[pHandle->cur.slot];
    STableCheckInfo* pCheckInfo = pBlockInfo->pTableCheckInfo;
3388

3389
    if (pHandle->cur.mixBlock) {
H
[td-32]  
hjxilinx 已提交
3390 3391
      return pHandle->pColumns;
    } else {
3392
      SDataBlockInfo binfo = {0};/*GET_FILE_DATA_BLOCK_INFO(pCheckInfo, pBlockInfo->compBlock);*/
3393
      assert(pHandle->realNumOfRows <= binfo.rows);
H
Haojun Liao 已提交
3394

H
hjxilinx 已提交
3395 3396
      // data block has been loaded, todo extract method
      SDataBlockLoadInfo* pBlockLoadInfo = &pHandle->dataBlockLoadInfo;
H
Haojun Liao 已提交
3397

H
Hongze Cheng 已提交
3398
      if (pBlockLoadInfo->slot == pHandle->cur.slot && pBlockLoadInfo->fileGroup->fid == pHandle->cur.fid &&
3399
          pBlockLoadInfo->uid == pCheckInfo->pTableObj->tid) {
H
hjxilinx 已提交
3400
        return pHandle->pColumns;
H
Haojun Liao 已提交
3401
      } else {  // only load the file block
H
refact  
Hongze Cheng 已提交
3402
        SBlock* pBlock = pBlockInfo->compBlock;
H
Haojun Liao 已提交
3403
        if (doLoadFileDataBlock(pHandle, pBlock, pCheckInfo, pHandle->cur.slot) != TSDB_CODE_SUCCESS) {
3404 3405
          return NULL;
        }
H
Haojun Liao 已提交
3406

H
Haojun Liao 已提交
3407
        // todo refactor
H
Haojun Liao 已提交
3408
        int32_t numOfRows = doCopyRowsFromFileBlock(pHandle, pHandle->outputCapacity, 0, 0, pBlock->numOfRows - 1);
H
Haojun Liao 已提交
3409

H
Haojun Liao 已提交
3410
        // if the buffer is not full in case of descending order query, move the data in the front of the buffer
3411
        if (!ASCENDING_TRAVERSE(pHandle->order) && numOfRows < pHandle->outputCapacity) {
H
Haojun Liao 已提交
3412
          int32_t emptySize = pHandle->outputCapacity - numOfRows;
S
TD-1057  
Shengliang Guan 已提交
3413
          int32_t reqNumOfCols = (int32_t)taosArrayGetSize(pHandle->pColumns);
H
Haojun Liao 已提交
3414

H
Haojun Liao 已提交
3415 3416
          for(int32_t i = 0; i < reqNumOfCols; ++i) {
            SColumnInfoData* pColInfo = taosArrayGet(pHandle->pColumns, i);
S
TD-1057  
Shengliang Guan 已提交
3417
            memmove((char*)pColInfo->pData, (char*)pColInfo->pData + emptySize * pColInfo->info.bytes, numOfRows * pColInfo->info.bytes);
H
Haojun Liao 已提交
3418 3419
          }
        }
H
Haojun Liao 已提交
3420

H
hjxilinx 已提交
3421 3422
        return pHandle->pColumns;
      }
H
[td-32]  
hjxilinx 已提交
3423 3424
    }
  }
H
hjxilinx 已提交
3425
}
3426
#if 0
3427
void filterPrepare(void* expr, void* param) {
3428
  tExprNode* pExpr = (tExprNode*)expr;
H
[td-32]  
hjxilinx 已提交
3429
  if (pExpr->_node.info != NULL) {
3430 3431
    return;
  }
3432

H
[td-32]  
hjxilinx 已提交
3433
  pExpr->_node.info = calloc(1, sizeof(tQueryInfo));
H
Haojun Liao 已提交
3434

3435
  STSchema*   pTSSchema = (STSchema*) param;
H
hjxilinx 已提交
3436 3437 3438
  tQueryInfo* pInfo = pExpr->_node.info;
  tVariant*   pCond = pExpr->_node.pRight->pVal;
  SSchema*    pSchema = pExpr->_node.pLeft->pSchema;
3439

3440 3441
  pInfo->sch      = *pSchema;
  pInfo->optr     = pExpr->_node.optr;
Y
yihaoDeng 已提交
3442
  pInfo->compare  = getComparFunc(pInfo->sch.type, pInfo->optr);
H
Haojun Liao 已提交
3443
  pInfo->indexed  = pTSSchema->columns->colId == pInfo->sch.colId;
H
Haojun Liao 已提交
3444

H
hjxilinx 已提交
3445
  if (pInfo->optr == TSDB_RELATION_IN) {
Y
yihaoDeng 已提交
3446
     int dummy = -1;
3447
     SHashObj *pObj = NULL;
Y
yihaoDeng 已提交
3448 3449 3450 3451
     if (pInfo->sch.colId == TSDB_TBNAME_COLUMN_INDEX) {
        pObj = taosHashInit(256, taosGetDefaultHashFunction(pInfo->sch.type), true, false);
        SArray *arr = (SArray *)(pCond->arr);
        for (size_t i = 0; i < taosArrayGetSize(arr); i++) {
Y
yihaoDeng 已提交
3452
          char* p = taosArrayGetP(arr, i);
3453 3454
          strntolower_s(varDataVal(p), varDataVal(p), varDataLen(p));
          taosHashPut(pObj, varDataVal(p), varDataLen(p), &dummy, sizeof(dummy));
Y
yihaoDeng 已提交
3455 3456 3457 3458
        }
     } else {
       buildFilterSetFromBinary((void **)&pObj, pCond->pz, pCond->nLen);
     }
3459
     pInfo->q = (char *)pObj;
H
Haojun Liao 已提交
3460
  } else if (pCond != NULL) {
3461 3462 3463 3464
    uint32_t size = pCond->nLen * TSDB_NCHAR_SIZE;
    if (size < (uint32_t)pSchema->bytes) {
      size = pSchema->bytes;
    }
3465 3466
    // to make sure tonchar does not cause invalid write, since the '\0' needs at least sizeof(wchar_t) space.
    pInfo->q = calloc(1, size + TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE);
3467
    tVariantDump(pCond, pInfo->q, pSchema->type, true);
weixin_48148422's avatar
weixin_48148422 已提交
3468
  }
3469 3470
}

H
Haojun Liao 已提交
3471
static int32_t tableGroupComparFn(const void *p1, const void *p2, const void *param) {
3472
  STableGroupSupporter* pTableGroupSupp = (STableGroupSupporter*) param;
H
Haojun Liao 已提交
3473 3474
  STable* pTable1 = ((STableKeyInfo*) p1)->pTable;
  STable* pTable2 = ((STableKeyInfo*) p2)->pTable;
H
Haojun Liao 已提交
3475

3476 3477 3478
  for (int32_t i = 0; i < pTableGroupSupp->numOfCols; ++i) {
    SColIndex* pColIndex = &pTableGroupSupp->pCols[i];
    int32_t colIndex = pColIndex->colIndex;
H
Haojun Liao 已提交
3479

H
Haojun Liao 已提交
3480
    assert(colIndex >= TSDB_TBNAME_COLUMN_INDEX);
H
Haojun Liao 已提交
3481

3482 3483 3484 3485
    char *  f1 = NULL;
    char *  f2 = NULL;
    int32_t type = 0;
    int32_t bytes = 0;
H
Haojun Liao 已提交
3486

H
Haojun Liao 已提交
3487 3488 3489
    if (colIndex == TSDB_TBNAME_COLUMN_INDEX) {
      f1 = (char*) TABLE_NAME(pTable1);
      f2 = (char*) TABLE_NAME(pTable2);
3490
      type = TSDB_DATA_TYPE_BINARY;
3491
      bytes = tGetTbnameColumnSchema()->bytes;
3492
    } else {
Y
yihaoDeng 已提交
3493 3494 3495 3496 3497 3498 3499
      if (pTableGroupSupp->pTagSchema && colIndex < pTableGroupSupp->pTagSchema->numOfCols) {
        STColumn* pCol = schemaColAt(pTableGroupSupp->pTagSchema, colIndex);
        bytes = pCol->bytes;
        type = pCol->type;
        f1 = tdGetKVRowValOfCol(pTable1->tagVal, pCol->colId);
        f2 = tdGetKVRowValOfCol(pTable2->tagVal, pCol->colId);
      } 
3500
    }
H
Haojun Liao 已提交
3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514

    // this tags value may be NULL
    if (f1 == NULL && f2 == NULL) {
      continue;
    }

    if (f1 == NULL) {
      return -1;
    }

    if (f2 == NULL) {
      return 1;
    }

3515 3516 3517 3518 3519 3520 3521
    int32_t ret = doCompare(f1, f2, type, bytes);
    if (ret == 0) {
      continue;
    } else {
      return ret;
    }
  }
H
Haojun Liao 已提交
3522

3523 3524
  return 0;
}
3525
#endif
3526

H
Haojun Liao 已提交
3527
static int tsdbCheckInfoCompar(const void* key1, const void* key2) {
3528
  if (((STableCheckInfo*)key1)->tableId < ((STableCheckInfo*)key2)->tableId) {
H
Haojun Liao 已提交
3529
    return -1;
3530
  } else if (((STableCheckInfo*)key1)->tableId > ((STableCheckInfo*)key2)->tableId) {
H
Haojun Liao 已提交
3531 3532 3533 3534 3535 3536 3537 3538 3539
    return 1;
  } else {
    ASSERT(false);
    return 0;
  }
}

void createTableGroupImpl(SArray* pGroups, SArray* pTableList, size_t numOfTables, TSKEY skey,
                          STableGroupSupporter* pSupp, __ext_compar_fn_t compareFn) {
3540
  STable* pTable = taosArrayGetP(pTableList, 0);
H
Haojun Liao 已提交
3541

H
Haojun Liao 已提交
3542 3543 3544 3545
  SArray* g = taosArrayInit(16, sizeof(STableKeyInfo));

  STableKeyInfo info = {.pTable = pTable, .lastKey = skey};
  taosArrayPush(g, &info);
3546

3547
  for (int32_t i = 1; i < numOfTables; ++i) {
3548 3549
    STable** prev = taosArrayGet(pTableList, i - 1);
    STable** p = taosArrayGet(pTableList, i);
H
Haojun Liao 已提交
3550

H
hjxilinx 已提交
3551
    int32_t ret = compareFn(prev, p, pSupp);
3552
    assert(ret == 0 || ret == -1);
H
Haojun Liao 已提交
3553

3554
//    assert((*p)->type == TSDB_CHILD_TABLE);
3555

3556
    if (ret == 0) {
H
Haojun Liao 已提交
3557 3558
      STableKeyInfo info1 = {.pTable = *p, .lastKey = skey};
      taosArrayPush(g, &info1);
3559 3560
    } else {
      taosArrayPush(pGroups, &g);  // current group is ended, start a new group
H
Haojun Liao 已提交
3561 3562 3563 3564
      g = taosArrayInit(16, sizeof(STableKeyInfo));

      STableKeyInfo info1 = {.pTable = *p, .lastKey = skey};
      taosArrayPush(g, &info1);
3565 3566
    }
  }
H
Haojun Liao 已提交
3567

3568
  taosArrayPush(pGroups, &g);
3569 3570
}

3571
#if 0
H
Haojun Liao 已提交
3572
SArray* createTableGroup(SArray* pTableList, STSchema* pTagSchema, SColIndex* pCols, int32_t numOfOrderCols, TSKEY skey) {
3573
  assert(pTableList != NULL);
3574
  SArray* pTableGroup = taosArrayInit(1, POINTER_BYTES);
H
Haojun Liao 已提交
3575

3576 3577
  size_t size = taosArrayGetSize(pTableList);
  if (size == 0) {
S
Shengliang Guan 已提交
3578
    tsdbDebug("no qualified tables");
3579 3580
    return pTableGroup;
  }
H
Haojun Liao 已提交
3581

3582
  if (numOfOrderCols == 0 || size == 1) { // no group by tags clause or only one table
H
Haojun Liao 已提交
3583
    SArray* sa = taosArrayInit(size, sizeof(STableKeyInfo));
H
Haojun Liao 已提交
3584 3585 3586 3587
    if (sa == NULL) {
      taosArrayDestroy(pTableGroup);
      return NULL;
    }
H
Haojun Liao 已提交
3588

weixin_48148422's avatar
weixin_48148422 已提交
3589
    for(int32_t i = 0; i < size; ++i) {
H
Haojun Liao 已提交
3590 3591 3592 3593
      STableKeyInfo *pKeyInfo = taosArrayGet(pTableList, i);

      STableKeyInfo info = {.pTable = pKeyInfo->pTable, .lastKey = skey};
      taosArrayPush(sa, &info);
3594
    }
H
Haojun Liao 已提交
3595

3596
    taosArrayPush(pTableGroup, &sa);
S
TD-1057  
Shengliang Guan 已提交
3597
    tsdbDebug("all %" PRIzu " tables belong to one group", size);
3598
  } else {
H
Haojun Liao 已提交
3599 3600 3601 3602 3603 3604 3605
    STableGroupSupporter sup = {0};
    sup.numOfCols = numOfOrderCols;
    sup.pTagSchema = pTagSchema;
    sup.pCols = pCols;

    taosqsort(pTableList->pData, size, sizeof(STableKeyInfo), &sup, tableGroupComparFn);
    createTableGroupImpl(pTableGroup, pTableList, size, skey, &sup, tableGroupComparFn);
3606
  }
H
Haojun Liao 已提交
3607

3608 3609 3610
  return pTableGroup;
}

H
Haojun Liao 已提交
3611
static bool tableFilterFp(const void* pNode, void* param) {
H
hjxilinx 已提交
3612
  tQueryInfo* pInfo = (tQueryInfo*) param;
H
Haojun Liao 已提交
3613

H
TD-1194  
Hongze Cheng 已提交
3614
  STable* pTable = (STable*)(SL_GET_NODE_DATA((SSkipListNode*)pNode));
3615

H
Haojun Liao 已提交
3616
  char* val = NULL;
3617
  if (pInfo->sch.colId == TSDB_TBNAME_COLUMN_INDEX) {
H
Haojun Liao 已提交
3618
    val = (char*) TABLE_NAME(pTable);
3619
  } else {
H
Haojun Liao 已提交
3620
    val = tdGetKVRowValOfCol(pTable->tagVal, pInfo->sch.colId);
3621
  }
H
Haojun Liao 已提交
3622

H
Haojun Liao 已提交
3623 3624 3625 3626 3627 3628
  if (pInfo->optr == TSDB_RELATION_ISNULL || pInfo->optr == TSDB_RELATION_NOTNULL) {
    if (pInfo->optr == TSDB_RELATION_ISNULL) {
      return (val == NULL) || isNull(val, pInfo->sch.type);
    } else if (pInfo->optr == TSDB_RELATION_NOTNULL) {
      return (val != NULL) && (!isNull(val, pInfo->sch.type));
    }
Y
yihaoDeng 已提交
3629 3630
  } else if (pInfo->optr == TSDB_RELATION_IN) {
     int type = pInfo->sch.type;
3631
     if (type == TSDB_DATA_TYPE_BOOL || IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_TIMESTAMP) {
Y
yihaoDeng 已提交
3632 3633 3634
       int64_t v;
       GET_TYPED_DATA(v, int64_t, pInfo->sch.type, val);
       return NULL != taosHashGet((SHashObj *)pInfo->q, (char *)&v, sizeof(v));     
3635 3636 3637 3638 3639
     } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
       uint64_t v;
       GET_TYPED_DATA(v, uint64_t, pInfo->sch.type, val);
       return NULL != taosHashGet((SHashObj *)pInfo->q, (char *)&v, sizeof(v));     
     }
3640
     else if (type == TSDB_DATA_TYPE_DOUBLE || type == TSDB_DATA_TYPE_FLOAT) {
Y
yihaoDeng 已提交
3641 3642 3643 3644 3645 3646 3647
       double v;
       GET_TYPED_DATA(v, double, pInfo->sch.type, val);
       return NULL != taosHashGet((SHashObj *)pInfo->q, (char *)&v, sizeof(v));     
     } else if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR){
       return NULL != taosHashGet((SHashObj *)pInfo->q, varDataVal(val), varDataLen(val));        
     }     

H
Haojun Liao 已提交
3648 3649
  }

H
Haojun Liao 已提交
3650 3651 3652 3653 3654 3655
  int32_t ret = 0;
  if (val == NULL) { //the val is possible to be null, so check it out carefully
    ret = -1; // val is missing in table tags value pairs
  } else {
    ret = pInfo->compare(val, pInfo->q);
  }
3656

3657 3658 3659 3660 3661 3662 3663
  switch (pInfo->optr) {
    case TSDB_RELATION_EQUAL: {
      return ret == 0;
    }
    case TSDB_RELATION_NOT_EQUAL: {
      return ret != 0;
    }
3664
    case TSDB_RELATION_GREATER_EQUAL: {
3665 3666
      return ret >= 0;
    }
3667
    case TSDB_RELATION_GREATER: {
3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678
      return ret > 0;
    }
    case TSDB_RELATION_LESS_EQUAL: {
      return ret <= 0;
    }
    case TSDB_RELATION_LESS: {
      return ret < 0;
    }
    case TSDB_RELATION_LIKE: {
      return ret == 0;
    }
3679 3680 3681
    case TSDB_RELATION_MATCH: {
      return ret == 0;
    }
3682 3683 3684
    case TSDB_RELATION_NMATCH: {
      return ret == 0;
    }
weixin_48148422's avatar
weixin_48148422 已提交
3685
    case TSDB_RELATION_IN: {
3686
      return ret == 1;
weixin_48148422's avatar
weixin_48148422 已提交
3687
    }
3688

3689 3690 3691
    default:
      assert(false);
  }
H
Haojun Liao 已提交
3692

3693 3694 3695
  return true;
}

H
Haojun Liao 已提交
3696 3697
static void getTableListfromSkipList(tExprNode *pExpr, SSkipList *pSkipList, SArray *result, SExprTraverseSupp *param);

3698
static int32_t doQueryTableList(STable* pSTable, SArray* pRes, tExprNode* pExpr) {
H
hjxilinx 已提交
3699 3700
  // query according to the expression tree
  SExprTraverseSupp supp = {
H
Haojun Liao 已提交
3701
      .nodeFilterFn = (__result_filter_fn_t) tableFilterFp,
H
hjxilinx 已提交
3702 3703
      .setupInfoFn = filterPrepare,
      .pExtInfo = pSTable->tagSchema,
3704
      };
3705

H
Haojun Liao 已提交
3706
  getTableListfromSkipList(pExpr, pSTable->pIndex, pRes, &supp);
H
Haojun Liao 已提交
3707
  tExprTreeDestroy(pExpr, destroyHelper);
3708 3709 3710
  return TSDB_CODE_SUCCESS;
}

3711
int32_t tsdbQuerySTableByTagCond(STsdb* tsdb, uint64_t uid, TSKEY skey, const char* pTagCond, size_t len,
3712 3713
                                 int16_t tagNameRelType, const char* tbnameCond, STableGroupInfo* pGroupInfo,
                                 SColIndex* pColIndex, int32_t numOfCols) {
3714 3715
  if (tsdbRLockRepoMeta(tsdb) < 0) goto _error;

H
hjxilinx 已提交
3716 3717
  STable* pTable = tsdbGetTableByUid(tsdbGetMeta(tsdb), uid);
  if (pTable == NULL) {
3718
    tsdbError("%p failed to get stable, uid:%" PRIu64, tsdb, uid);
3719 3720 3721 3722
    terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
    tsdbUnlockRepoMeta(tsdb);

    goto _error;
3723
  }
H
Haojun Liao 已提交
3724

H
hjxilinx 已提交
3725
  if (pTable->type != TSDB_SUPER_TABLE) {
3726
    tsdbError("%p query normal tag not allowed, uid:%" PRIu64 ", tid:%d, name:%s", tsdb, uid, pTable->tableId,
B
Bomin Zhang 已提交
3727
        pTable->name->data);
3728 3729 3730 3731
    terrno = TSDB_CODE_COM_OPS_NOT_SUPPORT; //basically, this error is caused by invalid sql issued by client

    tsdbUnlockRepoMeta(tsdb);
    goto _error;
H
hjxilinx 已提交
3732
  }
3733 3734

  //NOTE: not add ref count for super table
H
Haojun Liao 已提交
3735
  SArray* res = taosArrayInit(8, sizeof(STableKeyInfo));
H
TD-353  
Hongze Cheng 已提交
3736
  STSchema* pTagSchema = tsdbGetTableTagSchema(pTable);
H
Haojun Liao 已提交
3737

weixin_48148422's avatar
weixin_48148422 已提交
3738 3739
  // no tags and tbname condition, all child tables of this stable are involved
  if (tbnameCond == NULL && (pTagCond == NULL || len == 0)) {
3740 3741 3742 3743
    int32_t ret = getAllTableList(pTable, res);
    if (ret != TSDB_CODE_SUCCESS) {
      tsdbUnlockRepoMeta(tsdb);
      goto _error;
3744
    }
3745

sangshuduo's avatar
sangshuduo 已提交
3746
    pGroupInfo->numOfTables = (uint32_t) taosArrayGetSize(res);
H
Haojun Liao 已提交
3747
    pGroupInfo->pGroupList  = createTableGroup(res, pTagSchema, pColIndex, numOfCols, skey);
H
Haojun Liao 已提交
3748

H
Haojun Liao 已提交
3749
    tsdbDebug("%p no table name/tag condition, all tables qualified, numOfTables:%u, group:%zu", tsdb,
3750
              pGroupInfo->numOfTables, taosArrayGetSize(pGroupInfo->pGroupList));
3751

3752
    taosArrayDestroy(res);
3753
    if (tsdbUnlockRepoMeta(tsdb) < 0) goto _error;
3754 3755
    return ret;
  }
3756

H
hjxilinx 已提交
3757
  int32_t ret = TSDB_CODE_SUCCESS;
3758
  tExprNode* expr = NULL;
3759

dengyihao's avatar
dengyihao 已提交
3760
  TRY(TSDB_MAX_TAG_CONDITIONS) {
3761
    expr = exprTreeFromTableName(tbnameCond);
weixin_48148422's avatar
weixin_48148422 已提交
3762
    if (expr == NULL) {
3763
      expr = exprTreeFromBinary(pTagCond, len);
weixin_48148422's avatar
weixin_48148422 已提交
3764
    } else {
H
Haojun Liao 已提交
3765
      CLEANUP_PUSH_VOID_PTR_PTR(true, tExprTreeDestroy, expr, NULL);
3766 3767
      tExprNode* tagExpr = exprTreeFromBinary(pTagCond, len);
      if (tagExpr != NULL) {
H
Haojun Liao 已提交
3768
        CLEANUP_PUSH_VOID_PTR_PTR(true, tExprTreeDestroy, tagExpr, NULL);
3769 3770 3771
        tExprNode* tbnameExpr = expr;
        expr = calloc(1, sizeof(tExprNode));
        if (expr == NULL) {
3772
          THROW( TSDB_CODE_TDB_OUT_OF_MEMORY );
3773 3774
        }
        expr->nodeType = TSQL_NODE_EXPR;
S
TD-1057  
Shengliang Guan 已提交
3775
        expr->_node.optr = (uint8_t)tagNameRelType;
3776 3777 3778
        expr->_node.pLeft = tagExpr;
        expr->_node.pRight = tbnameExpr;
      }
weixin_48148422's avatar
weixin_48148422 已提交
3779
    }
3780 3781 3782 3783
    CLEANUP_EXECUTE();

  } CATCH( code ) {
    CLEANUP_EXECUTE();
dengyihao's avatar
TD-816  
dengyihao 已提交
3784
    terrno = code;
3785 3786
    tsdbUnlockRepoMeta(tsdb);     // unlock tsdb in any cases

H
Haojun Liao 已提交
3787
    goto _error;
3788 3789
    // TODO: more error handling
  } END_TRY
3790

H
hjxilinx 已提交
3791
  doQueryTableList(pTable, res, expr);
sangshuduo's avatar
sangshuduo 已提交
3792
  pGroupInfo->numOfTables = (uint32_t)taosArrayGetSize(res);
H
Haojun Liao 已提交
3793
  pGroupInfo->pGroupList  = createTableGroup(res, pTagSchema, pColIndex, numOfCols, skey);
3794

3795 3796
  tsdbDebug("%p stable tid:%d, uid:%"PRIu64" query, numOfTables:%u, belong to %" PRIzu " groups", tsdb, pTable->tableId,
      pTable->uid, pGroupInfo->numOfTables, taosArrayGetSize(pGroupInfo->pGroupList));
H
Haojun Liao 已提交
3797

3798
  taosArrayDestroy(res);
3799 3800

  if (tsdbUnlockRepoMeta(tsdb) < 0) goto _error;
3801
  return ret;
3802 3803 3804

  _error:
  return terrno;
3805
}
3806

3807
int32_t tsdbGetOneTableGroup(STsdb* tsdb, uint64_t uid, TSKEY startKey, STableGroupInfo* pGroupInfo) {
3808 3809
  if (tsdbRLockRepoMeta(tsdb) < 0) goto _error;

3810 3811
  STable* pTable = tsdbGetTableByUid(tsdbGetMeta(tsdb), uid);
  if (pTable == NULL) {
3812
    terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
H
Hongze Cheng 已提交
3813
    tsdbUnlockRepoMeta(tsdb);
3814
    goto _error;
3815
  }
3816

B
Bomin Zhang 已提交
3817
  assert(pTable->type == TSDB_CHILD_TABLE || pTable->type == TSDB_NORMAL_TABLE || pTable->type == TSDB_STREAM_TABLE);
3818 3819
  if (tsdbUnlockRepoMeta(tsdb) < 0) goto _error;

3820 3821
  pGroupInfo->numOfTables = 1;
  pGroupInfo->pGroupList = taosArrayInit(1, POINTER_BYTES);
H
Haojun Liao 已提交
3822

H
Haojun Liao 已提交
3823 3824 3825 3826
  SArray* group = taosArrayInit(1, sizeof(STableKeyInfo));

  STableKeyInfo info = {.pTable = pTable, .lastKey = startKey};
  taosArrayPush(group, &info);
H
Haojun Liao 已提交
3827

3828
  taosArrayPush(pGroupInfo->pGroupList, &group);
3829
  return TSDB_CODE_SUCCESS;
3830 3831 3832

  _error:
  return terrno;
3833
}
3834

3835
int32_t tsdbGetTableGroupFromIdList(STsdb* tsdb, SArray* pTableIdList, STableGroupInfo* pGroupInfo) {
B
Bomin Zhang 已提交
3836 3837 3838
  if (tsdbRLockRepoMeta(tsdb) < 0) {
    return terrno;
  }
3839 3840 3841 3842

  assert(pTableIdList != NULL);
  size_t size = taosArrayGetSize(pTableIdList);
  pGroupInfo->pGroupList = taosArrayInit(1, POINTER_BYTES);
H
Haojun Liao 已提交
3843
  SArray* group = taosArrayInit(1, sizeof(STableKeyInfo));
3844

B
Bomin Zhang 已提交
3845
  for(int32_t i = 0; i < size; ++i) {
3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856
    STableIdInfo *id = taosArrayGet(pTableIdList, i);

    STable* pTable = tsdbGetTableByUid(tsdbGetMeta(tsdb), id->uid);
    if (pTable == NULL) {
      tsdbWarn("table uid:%"PRIu64", tid:%d has been drop already", id->uid, id->tid);
      continue;
    }

    if (pTable->type == TSDB_SUPER_TABLE) {
      tsdbError("direct query on super tale is not allowed, table uid:%"PRIu64", tid:%d", id->uid, id->tid);
      terrno = TSDB_CODE_QRY_INVALID_MSG;
D
fix bug  
dapan1121 已提交
3857 3858 3859
      tsdbUnlockRepoMeta(tsdb);
      taosArrayDestroy(group);
      return terrno;
3860 3861
    }

H
Haojun Liao 已提交
3862 3863
    STableKeyInfo info = {.pTable = pTable, .lastKey = id->key};
    taosArrayPush(group, &info);
3864 3865
  }

B
Bomin Zhang 已提交
3866 3867 3868 3869
  if (tsdbUnlockRepoMeta(tsdb) < 0) {
    taosArrayDestroy(group);
    return terrno;
  }
3870

sangshuduo's avatar
sangshuduo 已提交
3871
  pGroupInfo->numOfTables = (uint32_t) taosArrayGetSize(group);
B
Bomin Zhang 已提交
3872 3873 3874 3875 3876
  if (pGroupInfo->numOfTables > 0) {
    taosArrayPush(pGroupInfo->pGroupList, &group);
  } else {
    taosArrayDestroy(group);
  }
3877 3878 3879 3880

  return TSDB_CODE_SUCCESS;
}

3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895
static void* doFreeColumnInfoData(SArray* pColumnInfoData) {
  if (pColumnInfoData == NULL) {
    return NULL;
  }

  size_t cols = taosArrayGetSize(pColumnInfoData);
  for (int32_t i = 0; i < cols; ++i) {
    SColumnInfoData* pColInfo = taosArrayGet(pColumnInfoData, i);
    tfree(pColInfo->pData);
  }

  taosArrayDestroy(pColumnInfoData);
  return NULL;
}

H
Haojun Liao 已提交
3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908
static void* destroyTableCheckInfo(SArray* pTableCheckInfo) {
  size_t size = taosArrayGetSize(pTableCheckInfo);
  for (int32_t i = 0; i < size; ++i) {
    STableCheckInfo* p = taosArrayGet(pTableCheckInfo, i);
    destroyTableMemIterator(p);

    tfree(p->pCompInfo);
  }

  taosArrayDestroy(pTableCheckInfo);
  return NULL;
}

3909 3910 3911
void tsdbCleanupQueryHandle(tsdbReadHandleT queryHandle) {
  STsdbReadHandle* pTsdbReadHandle = (STsdbReadHandle*)queryHandle;
  if (pTsdbReadHandle == NULL) {
3912 3913
    return;
  }
3914

3915
  pTsdbReadHandle->pColumns = doFreeColumnInfoData(pTsdbReadHandle->pColumns);
3916

3917 3918 3919
  taosArrayDestroy(pTsdbReadHandle->defaultLoadColumn);
  tfree(pTsdbReadHandle->pDataBlockInfo);
  tfree(pTsdbReadHandle->statis);
3920

3921 3922
  if (!emptyQueryTimewindow(pTsdbReadHandle)) {
    tsdbMayUnTakeMemSnapshot(pTsdbReadHandle);
3923
  } else {
3924
    assert(pTsdbReadHandle->pTableCheckInfo == NULL);
3925 3926
  }

3927 3928
  if (pTsdbReadHandle->pTableCheckInfo != NULL) {
    pTsdbReadHandle->pTableCheckInfo = destroyTableCheckInfo(pTsdbReadHandle->pTableCheckInfo);
3929
  }
3930

3931
  tsdbDestroyReadH(&pTsdbReadHandle->rhelper);
H
Haojun Liao 已提交
3932

3933 3934
  tdFreeDataCols(pTsdbReadHandle->pDataCols);
  pTsdbReadHandle->pDataCols = NULL;
H
Haojun Liao 已提交
3935

3936 3937
  pTsdbReadHandle->prev = doFreeColumnInfoData(pTsdbReadHandle->prev);
  pTsdbReadHandle->next = doFreeColumnInfoData(pTsdbReadHandle->next);
3938

3939
  SIOCostSummary* pCost = &pTsdbReadHandle->cost;
3940

3941
  tsdbDebug("%p :io-cost summary: head-file read cnt:%"PRIu64", head-file time:%"PRIu64" us, statis-info:%"PRId64" us, datablock:%" PRId64" us, check data:%"PRId64" us, 0x%"PRIx64,
3942
      pTsdbReadHandle, pCost->headFileLoad, pCost->headFileLoadTime, pCost->statisInfoLoadTime, pCost->blockLoadTime, pCost->checkForNextTime, pTsdbReadHandle->qId);
H
Haojun Liao 已提交
3943

3944
  tfree(pTsdbReadHandle);
3945
}
3946

H
Haojun Liao 已提交
3947
void tsdbDestroyTableGroup(STableGroupInfo *pGroupList) {
3948 3949 3950 3951 3952 3953 3954 3955 3956 3957
  assert(pGroupList != NULL);

  size_t numOfGroup = taosArrayGetSize(pGroupList->pGroupList);

  for(int32_t i = 0; i < numOfGroup; ++i) {
    SArray* p = taosArrayGetP(pGroupList->pGroupList, i);

    size_t numOfTables = taosArrayGetSize(p);
    for(int32_t j = 0; j < numOfTables; ++j) {
      STable* pTable = taosArrayGetP(p, j);
3958 3959 3960 3961
      if (pTable != NULL) { // in case of handling retrieve data from tsdb
        tsdbUnRefTable(pTable);
      }
      //assert(pTable != NULL);
3962 3963 3964 3965 3966
    }

    taosArrayDestroy(p);
  }

3967
  taosHashCleanup(pGroupList->map);
3968
  taosArrayDestroy(pGroupList->pGroupList);
H
Haojun Liao 已提交
3969
  pGroupList->numOfTables = 0;
3970
}
H
Haojun Liao 已提交
3971 3972 3973 3974 3975 3976 3977

static void applyFilterToSkipListNode(SSkipList *pSkipList, tExprNode *pExpr, SArray *pResult, SExprTraverseSupp *param) {
  SSkipListIterator* iter = tSkipListCreateIter(pSkipList);

  // Scan each node in the skiplist by using iterator
  while (tSkipListIterNext(iter)) {
    SSkipListNode *pNode = tSkipListIterGet(iter);
H
Haojun Liao 已提交
3978
    if (exprTreeApplyFilter(pExpr, pNode, param)) {
H
Haojun Liao 已提交
3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001
      taosArrayPush(pResult, &(SL_GET_NODE_DATA(pNode)));
    }
  }

  tSkipListDestroyIter(iter);
}

typedef struct {
  char*    v;
  int32_t  optr;
} SEndPoint;

typedef struct {
  SEndPoint* start;
  SEndPoint* end;
} SQueryCond;

// todo check for malloc failure
static int32_t setQueryCond(tQueryInfo *queryColInfo, SQueryCond* pCond) {
  int32_t optr = queryColInfo->optr;

  if (optr == TSDB_RELATION_GREATER || optr == TSDB_RELATION_GREATER_EQUAL ||
      optr == TSDB_RELATION_EQUAL || optr == TSDB_RELATION_NOT_EQUAL) {
Y
yihaoDeng 已提交
4002
    pCond->start       = calloc(1, sizeof(SEndPoint));
H
Haojun Liao 已提交
4003
    pCond->start->optr = queryColInfo->optr;
Y
yihaoDeng 已提交
4004
    pCond->start->v    = queryColInfo->q;
H
Haojun Liao 已提交
4005
  } else if (optr == TSDB_RELATION_LESS || optr == TSDB_RELATION_LESS_EQUAL) {
Y
yihaoDeng 已提交
4006
    pCond->end       = calloc(1, sizeof(SEndPoint));
H
Haojun Liao 已提交
4007
    pCond->end->optr = queryColInfo->optr;
Y
yihaoDeng 已提交
4008 4009 4010 4011 4012 4013
    pCond->end->v    = queryColInfo->q;
  } else if (optr == TSDB_RELATION_IN) {
    pCond->start       = calloc(1, sizeof(SEndPoint));
    pCond->start->optr = queryColInfo->optr;
    pCond->start->v    = queryColInfo->q; 
  } else if (optr == TSDB_RELATION_LIKE) {
H
Haojun Liao 已提交
4014
    assert(0);
4015 4016
  } else if (optr == TSDB_RELATION_MATCH) {
    assert(0);
4017 4018
  } else if (optr == TSDB_RELATION_NMATCH) {
    assert(0);
H
Haojun Liao 已提交
4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101
  }

  return TSDB_CODE_SUCCESS;
}

static void queryIndexedColumn(SSkipList* pSkipList, tQueryInfo* pQueryInfo, SArray* result) {
  SSkipListIterator* iter = NULL;

  SQueryCond cond = {0};
  if (setQueryCond(pQueryInfo, &cond) != TSDB_CODE_SUCCESS) {
    //todo handle error
  }

  if (cond.start != NULL) {
    iter = tSkipListCreateIterFromVal(pSkipList, (char*) cond.start->v, pSkipList->type, TSDB_ORDER_ASC);
  } else {
    iter = tSkipListCreateIterFromVal(pSkipList, (char*)(cond.end ? cond.end->v: NULL), pSkipList->type, TSDB_ORDER_DESC);
  }

  if (cond.start != NULL) {
    int32_t optr = cond.start->optr;

    if (optr == TSDB_RELATION_EQUAL) {   // equals
      while(tSkipListIterNext(iter)) {
        SSkipListNode* pNode = tSkipListIterGet(iter);

        int32_t ret = pQueryInfo->compare(SL_GET_NODE_KEY(pSkipList, pNode), cond.start->v);
        if (ret != 0) {
          break;
        }

        STableKeyInfo info = {.pTable = (void*)SL_GET_NODE_DATA(pNode), .lastKey = TSKEY_INITIAL_VAL};
        taosArrayPush(result, &info);
      }
    } else if (optr == TSDB_RELATION_GREATER || optr == TSDB_RELATION_GREATER_EQUAL) { // greater equal
      bool comp = true;
      int32_t ret = 0;

      while(tSkipListIterNext(iter)) {
        SSkipListNode* pNode = tSkipListIterGet(iter);

        if (comp) {
          ret = pQueryInfo->compare(SL_GET_NODE_KEY(pSkipList, pNode), cond.start->v);
          assert(ret >= 0);
        }

        if (ret == 0 && optr == TSDB_RELATION_GREATER) {
          continue;
        } else {
          STableKeyInfo info = {.pTable = (void*)SL_GET_NODE_DATA(pNode), .lastKey = TSKEY_INITIAL_VAL};
          taosArrayPush(result, &info);
          comp = false;
        }
      }
    } else if (optr == TSDB_RELATION_NOT_EQUAL) {   // not equal
      bool comp = true;

      while(tSkipListIterNext(iter)) {
        SSkipListNode* pNode = tSkipListIterGet(iter);
        comp = comp && (pQueryInfo->compare(SL_GET_NODE_KEY(pSkipList, pNode), cond.start->v) == 0);
        if (comp) {
          continue;
        }

        STableKeyInfo info = {.pTable = (void*)SL_GET_NODE_DATA(pNode), .lastKey = TSKEY_INITIAL_VAL};
        taosArrayPush(result, &info);
      }

      tSkipListDestroyIter(iter);

      comp = true;
      iter = tSkipListCreateIterFromVal(pSkipList, (char*) cond.start->v, pSkipList->type, TSDB_ORDER_DESC);
      while(tSkipListIterNext(iter)) {
        SSkipListNode* pNode = tSkipListIterGet(iter);
        comp = comp && (pQueryInfo->compare(SL_GET_NODE_KEY(pSkipList, pNode), cond.start->v) == 0);
        if (comp) {
          continue;
        }

        STableKeyInfo info = {.pTable = (void*)SL_GET_NODE_DATA(pNode), .lastKey = TSKEY_INITIAL_VAL};
        taosArrayPush(result, &info);
      }

Y
yihaoDeng 已提交
4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114
    } else if (optr == TSDB_RELATION_IN) {
      while(tSkipListIterNext(iter)) {
        SSkipListNode* pNode = tSkipListIterGet(iter);

        int32_t ret = pQueryInfo->compare(SL_GET_NODE_KEY(pSkipList, pNode), cond.start->v);
        if (ret != 0) {
          break;
        }

        STableKeyInfo info = {.pTable = (void*)SL_GET_NODE_DATA(pNode), .lastKey = TSKEY_INITIAL_VAL};
        taosArrayPush(result, &info);
      }
      
H
Haojun Liao 已提交
4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175
    } else {
      assert(0);
    }
  } else {
    int32_t optr = cond.end ? cond.end->optr : TSDB_RELATION_INVALID;
    if (optr == TSDB_RELATION_LESS || optr == TSDB_RELATION_LESS_EQUAL) {
      bool    comp = true;
      int32_t ret = 0;

      while (tSkipListIterNext(iter)) {
        SSkipListNode *pNode = tSkipListIterGet(iter);

        if (comp) {
          ret = pQueryInfo->compare(SL_GET_NODE_KEY(pSkipList, pNode), cond.end->v);
          assert(ret <= 0);
        }

        if (ret == 0 && optr == TSDB_RELATION_LESS) {
          continue;
        } else {
          STableKeyInfo info = {.pTable = (void *)SL_GET_NODE_DATA(pNode), .lastKey = TSKEY_INITIAL_VAL};
          taosArrayPush(result, &info);
          comp = false;  // no need to compare anymore
        }
      }
    } else {
      assert(pQueryInfo->optr == TSDB_RELATION_ISNULL || pQueryInfo->optr == TSDB_RELATION_NOTNULL);

      while (tSkipListIterNext(iter)) {
        SSkipListNode *pNode = tSkipListIterGet(iter);

        bool isnull = isNull(SL_GET_NODE_KEY(pSkipList, pNode), pQueryInfo->sch.type);
        if ((pQueryInfo->optr == TSDB_RELATION_ISNULL && isnull) ||
            (pQueryInfo->optr == TSDB_RELATION_NOTNULL && (!isnull))) {
          STableKeyInfo info = {.pTable = (void *)SL_GET_NODE_DATA(pNode), .lastKey = TSKEY_INITIAL_VAL};
          taosArrayPush(result, &info);
        }
      }
    }
  }

  free(cond.start);
  free(cond.end);
  tSkipListDestroyIter(iter);
}

static void queryIndexlessColumn(SSkipList* pSkipList, tQueryInfo* pQueryInfo, SArray* res, __result_filter_fn_t filterFp) {
  SSkipListIterator* iter = tSkipListCreateIter(pSkipList);

  while (tSkipListIterNext(iter)) {
    bool addToResult = false;

    SSkipListNode *pNode = tSkipListIterGet(iter);

    char *pData = SL_GET_NODE_DATA(pNode);
    tstr *name = (tstr*) tsdbGetTableName((void*) pData);

    // todo speed up by using hash
    if (pQueryInfo->sch.colId == TSDB_TBNAME_COLUMN_INDEX) {
      if (pQueryInfo->optr == TSDB_RELATION_IN) {
        addToResult = pQueryInfo->compare(name, pQueryInfo->q);
4176 4177 4178
      } else if (pQueryInfo->optr == TSDB_RELATION_LIKE ||
                 pQueryInfo->optr == TSDB_RELATION_MATCH ||
                 pQueryInfo->optr == TSDB_RELATION_NMATCH) {
H
Haojun Liao 已提交
4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209
        addToResult = !pQueryInfo->compare(name, pQueryInfo->q);
      }
    } else {
      addToResult = filterFp(pNode, pQueryInfo);
    }

    if (addToResult) {
      STableKeyInfo info = {.pTable = (void*)pData, .lastKey = TSKEY_INITIAL_VAL};
      taosArrayPush(res, &info);
    }
  }

  tSkipListDestroyIter(iter);
}

// Apply the filter expression to each node in the skiplist to acquire the qualified nodes in skip list
void getTableListfromSkipList(tExprNode *pExpr, SSkipList *pSkipList, SArray *result, SExprTraverseSupp *param) {
  if (pExpr == NULL) {
    return;
  }

  tExprNode *pLeft  = pExpr->_node.pLeft;
  tExprNode *pRight = pExpr->_node.pRight;

  // column project
  if (pLeft->nodeType != TSQL_NODE_EXPR && pRight->nodeType != TSQL_NODE_EXPR) {
    assert(pLeft->nodeType == TSQL_NODE_COL && (pRight->nodeType == TSQL_NODE_VALUE || pRight->nodeType == TSQL_NODE_DUMMY));

    param->setupInfoFn(pExpr, param->pExtInfo);

    tQueryInfo *pQueryInfo = pExpr->_node.info;
4210 4211
    if (pQueryInfo->indexed && (pQueryInfo->optr != TSDB_RELATION_LIKE
                                && pQueryInfo->optr != TSDB_RELATION_MATCH && pQueryInfo->optr != TSDB_RELATION_NMATCH
4212
                                && pQueryInfo->optr != TSDB_RELATION_IN)) {
H
Haojun Liao 已提交
4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227
      queryIndexedColumn(pSkipList, pQueryInfo, result);
    } else {
      queryIndexlessColumn(pSkipList, pQueryInfo, result, param->nodeFilterFn);
    }

    return;
  }

  // The value of hasPK is always 0.
  uint8_t weight = pLeft->_node.hasPK + pRight->_node.hasPK;
  assert(weight == 0 && pSkipList != NULL && taosArrayGetSize(result) == 0);

  //apply the hierarchical filter expression to every node in skiplist to find the qualified nodes
  applyFilterToSkipListNode(pSkipList, pExpr, result, param);
}
4228
#endif