tsdbRead.c 140.3 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/>.
 */

wafwerar's avatar
wafwerar 已提交
16
#include "tsdbDef.h"
H
Haojun Liao 已提交
17 18 19 20 21 22
#include <tdatablock.h>
#include "os.h"
#include "talgo.h"
#include "tcompare.h"
#include "tdataformat.h"
#include "texception.h"
23 24 25 26 27
#include "tsdb.h"
#include "tsdbFS.h"
#include "tsdbLog.h"
#include "tsdbReadImpl.h"
#include "tskiplist.h"
H
Haojun Liao 已提交
28
#include "ttime.h"
29

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

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

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

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

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

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

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

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

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

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

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

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

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

117 118
typedef struct STsdbReadHandle {
  STsdb*     pTsdb;
H
Haojun Liao 已提交
119 120 121 122 123 124 125 126 127
  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 已提交
128
  SArray*        pTableCheckInfo;  // SArray<STableCheckInfo>
H
Haojun Liao 已提交
129 130
  int32_t        activeIndex;
  bool           checkFiles;       // check file stage
D
init  
dapan1121 已提交
131
  int8_t         cachelastrow;     // check if last row cached
132
  bool           loadExternalRow;  // load time window external data rows
H
Haojun Liao 已提交
133 134
  bool           currentLoadExternalRows; // current load external rows
  int32_t        loadType;         // block load type
H
Haojun Liao 已提交
135
  char          *idStr;            // query info handle, for debug purpose
H
Haojun Liao 已提交
136
  int32_t        type;             // query type: retrieve all data blocks, 2. retrieve only last row, 3. retrieve direct prev|next rows
H
Hongze Cheng 已提交
137 138 139
  SDFileSet*     pFileGroup;
  SFSIter        fileIter;
  SReadH         rhelper;
H
Haojun Liao 已提交
140
  STableBlockInfo* pDataBlockInfo;
H
Haojun Liao 已提交
141
  SDataCols     *pDataCols;        // in order to hold current file data block
H
Haojun Liao 已提交
142
  int32_t        allocSize;        // allocated data block size
H
Haojun Liao 已提交
143
  SArray        *defaultLoadColumn;// default load column
H
Haojun Liao 已提交
144
  SDataBlockLoadInfo dataBlockLoadInfo; /* record current block load information */
H
Haojun Liao 已提交
145
  SLoadCompBlockInfo compBlockLoadInfo; /* record current compblock information in SQueryAttr */
H
Haojun Liao 已提交
146

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

H
Haojun Liao 已提交
152 153 154
typedef struct STableGroupSupporter {
  int32_t    numOfCols;
  SColIndex* pCols;
155
  SSchema*   pTagSchema;
H
Haojun Liao 已提交
156 157
} STableGroupSupporter;

158
static STimeWindow updateLastrowForEachGroup(STableGroupInfo *groupList);
159 160
static int32_t checkForCachedLastRow(STsdbReadHandle* pTsdbReadHandle, STableGroupInfo *groupList);
static int32_t checkForCachedLast(STsdbReadHandle* pTsdbReadHandle);
H
Haojun Liao 已提交
161
// static int32_t tsdbGetCachedLastRow(STable* pTable, STSRow** pRes, TSKEY* lastKey);
H
Haojun Liao 已提交
162

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

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

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

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

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

  return pIdList;
}

197 198
static SArray* getDefaultLoadColumns(STsdbReadHandle* pTsdbReadHandle, bool loadTS) {
  SArray* pLocalIdList = getColumnIdList(pTsdbReadHandle);
H
Haojun Liao 已提交
199 200 201 202 203

  // 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
H
Haojun Liao 已提交
204 205
  if (loadTS && colId != PRIMARYKEY_TIMESTAMP_COL_ID) {
    int16_t columnId = PRIMARYKEY_TIMESTAMP_COL_ID;
H
Haojun Liao 已提交
206 207 208 209 210 211
    taosArrayInsert(pLocalIdList, 0, &columnId);
  }

  return pLocalIdList;
}

H
Haojun Liao 已提交
212
//int64_t tsdbGetNumOfRowsInMemTable(tsdbReaderT* pHandle) {
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
//  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;
//}

241 242 243
static SArray* createCheckInfoFromTableGroup(STsdbReadHandle* pTsdbReadHandle, STableGroupInfo* pGroupList) {
  size_t numOfGroup = taosArrayGetSize(pGroupList->pGroupList);
  assert(numOfGroup >= 1);
H
Haojun Liao 已提交
244 245 246 247 248 249 250 251

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

  // todo apply the lastkey of table check to avoid to load header file
252
  for (int32_t i = 0; i < numOfGroup; ++i) {
H
Haojun Liao 已提交
253 254 255 256 257 258 259 260
    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);

261
      STableCheckInfo info = { .lastKey = pKeyInfo->lastKey, .tableId = pKeyInfo->uid};
262 263 264
      if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
        if (info.lastKey == INT64_MIN || info.lastKey < pTsdbReadHandle->window.skey) {
          info.lastKey = pTsdbReadHandle->window.skey;
265 266
        }

267
        assert(info.lastKey >= pTsdbReadHandle->window.skey && info.lastKey <= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
268
      } else {
269
        assert(info.lastKey >= pTsdbReadHandle->window.ekey && info.lastKey <= pTsdbReadHandle->window.skey);
H
Haojun Liao 已提交
270 271 272
      }

      taosArrayPush(pTableCheckInfo, &info);
H
Haojun Liao 已提交
273
      tsdbDebug("%p check table uid:%"PRId64" from lastKey:%"PRId64" %s", pTsdbReadHandle, info.tableId, info.lastKey, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
274 275 276
    }
  }

277
  // TODO  group table according to the tag value.
278
  taosArraySort(pTableCheckInfo, tsdbCheckInfoCompar);
H
Haojun Liao 已提交
279 280 281
  return pTableCheckInfo;
}

282 283
static void resetCheckInfo(STsdbReadHandle* pTsdbReadHandle) {
  size_t numOfTables = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
H
Haojun Liao 已提交
284 285 286 287
  assert(numOfTables >= 1);

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

294 295
    if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
      assert(pCheckInfo->lastKey >= pTsdbReadHandle->window.skey);
296
    } else {
297
      assert(pCheckInfo->lastKey <= pTsdbReadHandle->window.skey);
298
    }
H
Haojun Liao 已提交
299 300 301
  }
}

H
Haojun Liao 已提交
302 303 304
// only one table, not need to sort again
static SArray* createCheckInfoFromCheckInfo(STableCheckInfo* pCheckInfo, TSKEY skey, SArray** psTable) {
  SArray* pNew = taosArrayInit(1, sizeof(STableCheckInfo));
D
fix bug  
dapan1121 已提交
305

H
Haojun Liao 已提交
306
  STableCheckInfo info = { .lastKey = skey};
H
Haojun Liao 已提交
307

H
Haojun Liao 已提交
308 309
  info.tableId = pCheckInfo->tableId;
  taosArrayPush(pNew, &info);
H
Haojun Liao 已提交
310 311 312
  return pNew;
}

313 314
static bool emptyQueryTimewindow(STsdbReadHandle* pTsdbReadHandle) {
  assert(pTsdbReadHandle != NULL);
315

316 317
  STimeWindow* w = &pTsdbReadHandle->window;
  bool asc = ASCENDING_TRAVERSE(pTsdbReadHandle->order);
318 319 320 321

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

322 323
// 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.
324
static int64_t getEarliestValidTimestamp(STsdb* pTsdb) {
325 326 327
  STsdbCfg* pCfg = &pTsdb->config;

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

331 332
static void setQueryTimewindow(STsdbReadHandle* pTsdbReadHandle, STsdbQueryCond* pCond) {
  pTsdbReadHandle->window = pCond->twindow;
333

334
  bool    updateTs = false;
335 336 337 338
  int64_t startTs = getEarliestValidTimestamp(pTsdbReadHandle->pTsdb);
  if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
    if (startTs > pTsdbReadHandle->window.skey) {
      pTsdbReadHandle->window.skey = startTs;
339 340
      pCond->twindow.skey = startTs;
      updateTs = true;
341 342
    }
  } else {
343 344
    if (startTs > pTsdbReadHandle->window.ekey) {
      pTsdbReadHandle->window.ekey = startTs;
345 346
      pCond->twindow.ekey = startTs;
      updateTs = true;
347 348 349
    }
  }

350
  if (updateTs) {
H
Haojun Liao 已提交
351 352 353
    tsdbDebug("%p update the query time window, old:%" PRId64 " - %" PRId64 ", new:%" PRId64 " - %" PRId64 ", %s",
              pTsdbReadHandle, pCond->twindow.skey, pCond->twindow.ekey, pTsdbReadHandle->window.skey,
              pTsdbReadHandle->window.ekey, pTsdbReadHandle->idStr);
354
  }
355 356
}

H
Haojun Liao 已提交
357
static STsdbReadHandle* tsdbQueryTablesImpl(STsdb* tsdb, STsdbQueryCond* pCond, uint64_t qId, uint64_t taskId) {
358 359
  STsdbReadHandle* pReadHandle = calloc(1, sizeof(STsdbReadHandle));
  if (pReadHandle == NULL) {
360
    goto _end;
361
  }
H
Haojun Liao 已提交
362

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
  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->allocSize   = 0;
  pReadHandle->locateStart = false;
  pReadHandle->loadType    = pCond->type;

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

H
Haojun Liao 已提交
378
  char buf[128] = {0};
H
Haojun Liao 已提交
379
  snprintf(buf, tListLen(buf), "TID:0x%"PRIx64" QID:0x%"PRIx64, taskId, qId);
H
Haojun Liao 已提交
380 381
  pReadHandle->idStr = strdup(buf);

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

386 387
  assert(pCond != NULL);
  setQueryTimewindow(pReadHandle, pCond);
388

389 390
  if (pCond->numOfCols > 0) {
    // allocate buffer in order to load data blocks from file
391 392
    pReadHandle->statis = calloc(pCond->numOfCols, sizeof(SDataStatis));
    if (pReadHandle->statis == NULL) {
393
      goto _end;
394
    }
H
Haojun Liao 已提交
395

396
    // todo: use list instead of array?
397 398
    pReadHandle->pColumns = taosArrayInit(pCond->numOfCols, sizeof(SColumnInfoData));
    if (pReadHandle->pColumns == NULL) {
399
      goto _end;
400
    }
H
Haojun Liao 已提交
401

402 403 404
    for (int32_t i = 0; i < pCond->numOfCols; ++i) {
      SColumnInfoData colInfo = {{0}, 0};
      colInfo.info = pCond->colList[i];
H
Haojun Liao 已提交
405

406 407
      int32_t code = blockDataEnsureColumnCapacity(&colInfo, pReadHandle->outputCapacity);
      if (code != TSDB_CODE_SUCCESS) {
408
        goto _end;
409
      }
410

411 412
      taosArrayPush(pReadHandle->pColumns, &colInfo);
      pReadHandle->statis[i].colId = colInfo.info.colId;
B
Bomin Zhang 已提交
413
    }
H
Haojun Liao 已提交
414

415
    pReadHandle->defaultLoadColumn = getDefaultLoadColumns(pReadHandle, true);
H
Haojun Liao 已提交
416
  }
417

418 419
  pReadHandle->pDataCols = tdNewDataCols(1000, pReadHandle->pTsdb->config.maxRowsPerFileBlock);
  if (pReadHandle->pDataCols == NULL) {
H
Haojun Liao 已提交
420
    tsdbError("%p failed to malloc buf for pDataCols, %s", pReadHandle, pReadHandle->idStr);
H
Haojun Liao 已提交
421
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
422
    goto _end;
H
hjxilinx 已提交
423
  }
424

425 426
  tsdbInitDataBlockLoadInfo(&pReadHandle->dataBlockLoadInfo);
  tsdbInitCompBlockLoadInfo(&pReadHandle->compBlockLoadInfo);
427

H
Haojun Liao 已提交
428
  return (tsdbReaderT)pReadHandle;
429

430
  _end:
431
  tsdbCleanupReadHandle(pReadHandle);
432
  terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
433
  return NULL;
H
hjxilinx 已提交
434 435
}

H
Haojun Liao 已提交
436
tsdbReaderT* tsdbQueryTables(STsdb* tsdb, STsdbQueryCond* pCond, STableGroupInfo* groupList, uint64_t qId, uint64_t taskId) {
H
Haojun Liao 已提交
437
  STsdbReadHandle* pTsdbReadHandle = tsdbQueryTablesImpl(tsdb, pCond, qId, taskId);
438
  if (pTsdbReadHandle == NULL) {
439 440 441
    return NULL;
  }

442
  if (emptyQueryTimewindow(pTsdbReadHandle)) {
H
Haojun Liao 已提交
443
    return (tsdbReaderT*) pTsdbReadHandle;
444
  }
H
Haojun Liao 已提交
445 446

  // todo apply the lastkey of table check to avoid to load header file
447
  pTsdbReadHandle->pTableCheckInfo = createCheckInfoFromTableGroup(pTsdbReadHandle, groupList);
448
  if (pTsdbReadHandle->pTableCheckInfo == NULL) {
449
//    tsdbCleanupReadHandle(pTsdbReadHandle);
H
Haojun Liao 已提交
450 451 452 453
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    return NULL;
  }

454 455 456
  tsdbDebug("%p total numOfTable:%" PRIzu " in this query, group %"PRIzu" %s", pTsdbReadHandle, taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo),
      taosArrayGetSize(groupList->pGroupList), pTsdbReadHandle->idStr);

H
Haojun Liao 已提交
457
  return (tsdbReaderT) pTsdbReadHandle;
H
Haojun Liao 已提交
458 459
}

H
Haojun Liao 已提交
460
void tsdbResetQueryHandle(tsdbReaderT queryHandle, STsdbQueryCond *pCond) {
461
  STsdbReadHandle* pTsdbReadHandle = queryHandle;
H
Haojun Liao 已提交
462

463 464 465
  if (emptyQueryTimewindow(pTsdbReadHandle)) {
    if (pCond->order != pTsdbReadHandle->order) {
      pTsdbReadHandle->order = pCond->order;
dengyihao's avatar
dengyihao 已提交
466
      TSWAP(pTsdbReadHandle->window.skey, pTsdbReadHandle->window.ekey, int64_t);
467 468 469 470 471
    }

    return;
  }

472 473 474 475 476 477 478 479 480
  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 已提交
481 482

  if (ASCENDING_TRAVERSE(pCond->order)) {
483
    assert(pTsdbReadHandle->window.skey <= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
484
  } else {
485
    assert(pTsdbReadHandle->window.skey >= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
486 487 488
  }

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

491 492
  tsdbInitDataBlockLoadInfo(&pTsdbReadHandle->dataBlockLoadInfo);
  tsdbInitCompBlockLoadInfo(&pTsdbReadHandle->compBlockLoadInfo);
H
Haojun Liao 已提交
493

494
  resetCheckInfo(pTsdbReadHandle);
H
Haojun Liao 已提交
495 496
}

H
Haojun Liao 已提交
497
void tsdbResetQueryHandleForNewTable(tsdbReaderT queryHandle, STsdbQueryCond *pCond, STableGroupInfo* groupList) {
498
  STsdbReadHandle* pTsdbReadHandle = queryHandle;
H
Haojun Liao 已提交
499

500 501 502 503 504 505 506 507 508
  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 已提交
509 510

  if (ASCENDING_TRAVERSE(pCond->order)) {
511
    assert(pTsdbReadHandle->window.skey <= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
512
  } else {
513
    assert(pTsdbReadHandle->window.skey >= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
514 515 516
  }

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

519 520
  tsdbInitDataBlockLoadInfo(&pTsdbReadHandle->dataBlockLoadInfo);
  tsdbInitCompBlockLoadInfo(&pTsdbReadHandle->compBlockLoadInfo);
H
Haojun Liao 已提交
521

H
Haojun Liao 已提交
522
  SArray* pTable = NULL;
523
//  STsdbMeta* pMeta = tsdbGetMeta(pTsdbReadHandle->pTsdb);
H
Haojun Liao 已提交
524

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

527 528
  pTsdbReadHandle->pTableCheckInfo = NULL;//createCheckInfoFromTableGroup(pTsdbReadHandle, groupList, pMeta, &pTable);
  if (pTsdbReadHandle->pTableCheckInfo == NULL) {
529
//    tsdbCleanupReadHandle(pTsdbReadHandle);
H
Haojun Liao 已提交
530 531
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
532

533 534
//  pTsdbReadHandle->prev = doFreeColumnInfoData(pTsdbReadHandle->prev);
//  pTsdbReadHandle->next = doFreeColumnInfoData(pTsdbReadHandle->next);
H
Haojun Liao 已提交
535 536
}

H
Haojun Liao 已提交
537
tsdbReaderT tsdbQueryLastRow(STsdb *tsdb, STsdbQueryCond *pCond, STableGroupInfo *groupList, uint64_t qId, uint64_t taskId) {
538
  pCond->twindow = updateLastrowForEachGroup(groupList);
H
Haojun Liao 已提交
539 540 541 542 543 544

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

H
Haojun Liao 已提交
545
  STsdbReadHandle *pTsdbReadHandle = (STsdbReadHandle*) tsdbQueryTables(tsdb, pCond, groupList, qId, taskId);
546
  if (pTsdbReadHandle == NULL) {
547 548 549
    return NULL;
  }

550
  int32_t code = checkForCachedLastRow(pTsdbReadHandle, groupList);
H
Haojun Liao 已提交
551 552 553 554
  if (code != TSDB_CODE_SUCCESS) { // set the numOfTables to be 0
    terrno = code;
    return NULL;
  }
H
Haojun Liao 已提交
555 556

  assert(pCond->order == TSDB_ORDER_ASC && pCond->twindow.skey <= pCond->twindow.ekey);
557 558
  if (pTsdbReadHandle->cachelastrow) {
    pTsdbReadHandle->type = TSDB_QUERY_TYPE_LAST;
D
init  
dapan1121 已提交
559 560
  }
  
561
  return pTsdbReadHandle;
D
init  
dapan1121 已提交
562 563
}

564
#if 0
H
Haojun Liao 已提交
565
tsdbReaderT tsdbQueryCacheLast(STsdb *tsdb, STsdbQueryCond *pCond, STableGroupInfo *groupList, uint64_t qId, STsdbMemTable* pMemRef) {
566 567
  STsdbReadHandle *pTsdbReadHandle = (STsdbReadHandle*) tsdbQueryTables(tsdb, pCond, groupList, qId, pMemRef);
  if (pTsdbReadHandle == NULL) {
568 569 570
    return NULL;
  }

571
  int32_t code = checkForCachedLast(pTsdbReadHandle);
D
init  
dapan1121 已提交
572 573 574 575 576
  if (code != TSDB_CODE_SUCCESS) { // set the numOfTables to be 0
    terrno = code;
    return NULL;
  }

577 578
  if (pTsdbReadHandle->cachelastrow) {
    pTsdbReadHandle->type = TSDB_QUERY_TYPE_LAST;
D
fix bug  
dapan1121 已提交
579
  }
D
init  
dapan1121 已提交
580
  
581
  return pTsdbReadHandle;
H
hjxilinx 已提交
582 583
}

584
#endif
H
Haojun Liao 已提交
585
SArray* tsdbGetQueriedTableList(tsdbReaderT *pHandle) {
586
  assert(pHandle != NULL);
H
Haojun Liao 已提交
587

588
  STsdbReadHandle *pTsdbReadHandle = (STsdbReadHandle*) pHandle;
H
Haojun Liao 已提交
589

590
  size_t size = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
591
  SArray* res = taosArrayInit(size, POINTER_BYTES);
592 593 594
  return res;
}

H
Haojun Liao 已提交
595 596 597 598 599 600
// 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 已提交
601
  pNew->pGroupList = taosArrayInit(numOfGroup, POINTER_BYTES);
H
Haojun Liao 已提交
602 603 604 605 606 607 608 609

  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);
610 611 612 613 614
//      if (window->skey <= pInfo->lastKey && ((STable*)pInfo->pTable)->lastKey != TSKEY_INITIAL_VAL) {
//        taosArrayPush(px, pInfo);
//        pNew->numOfTables += 1;
//        break;
//      }
H
Haojun Liao 已提交
615 616 617 618 619 620 621 622 623 624 625 626 627
    }

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

  return pNew;
}

H
Haojun Liao 已提交
628
tsdbReaderT tsdbQueryRowsInExternalWindow(STsdb *tsdb, STsdbQueryCond* pCond, STableGroupInfo *groupList, uint64_t qId, uint64_t taskId) {
H
Haojun Liao 已提交
629 630
  STableGroupInfo* pNew = trimTableGroup(&pCond->twindow, groupList);

631 632 633 634 635 636 637 638 639 640 641 642
  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;
    }
  }

H
Haojun Liao 已提交
643
  STsdbReadHandle *pTsdbReadHandle = (STsdbReadHandle*) tsdbQueryTables(tsdb, pCond, pNew, qId, taskId);
644 645
  pTsdbReadHandle->loadExternalRow = true;
  pTsdbReadHandle->currentLoadExternalRows = true;
646

647
  return pTsdbReadHandle;
648 649
}

650
static bool initTableMemIterator(STsdbReadHandle* pHandle, STableCheckInfo* pCheckInfo) {
651
  if (pCheckInfo->initBuf) {
652 653
    return true;
  }
H
Haojun Liao 已提交
654

655
  pCheckInfo->initBuf = true;
656
  int32_t order = pHandle->order;
H
Haojun Liao 已提交
657

658 659 660
  STbData** pMem = NULL;
  STbData** pIMem = NULL;

H
Haojun Liao 已提交
661
  TSKEY tLastKey = 0;  /// keyToTkey(pCheckInfo->lastKey);
662 663 664
  if (pHandle->pTsdb->mem != NULL) {
    pMem = taosHashGet(pHandle->pTsdb->mem->pHashIdx, &pCheckInfo->tableId, sizeof(pCheckInfo->tableId));
    if (pMem != NULL) {
H
Haojun Liao 已提交
665
      pCheckInfo->iter =
666
          tSkipListCreateIterFromVal((*pMem)->pData, (const char*)&tLastKey, TSDB_DATA_TYPE_TIMESTAMP, order);
H
Haojun Liao 已提交
667
    }
668
  }
H
Haojun Liao 已提交
669

670 671 672
  if (pHandle->pTsdb->imem != NULL) {
    pIMem = taosHashGet(pHandle->pTsdb->imem->pHashIdx, &pCheckInfo->tableId, sizeof(pCheckInfo->tableId));
    if (pIMem != NULL) {
H
Haojun Liao 已提交
673
      pCheckInfo->iiter =
674
          tSkipListCreateIterFromVal((*pIMem)->pData, (const char*)&tLastKey, TSDB_DATA_TYPE_TIMESTAMP, order);
H
Haojun Liao 已提交
675
    }
676
  }
H
Haojun Liao 已提交
677

678 679 680 681
  // both iterators are NULL, no data in buffer right now
  if (pCheckInfo->iter == NULL && pCheckInfo->iiter == NULL) {
    return false;
  }
H
Haojun Liao 已提交
682

683 684 685 686 687
  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 已提交
688

689 690 691
  if (!memEmpty) {
    SSkipListNode* node = tSkipListIterGet(pCheckInfo->iter);
    assert(node != NULL);
H
Haojun Liao 已提交
692

H
Haojun Liao 已提交
693 694
    STSRow* row = (STSRow*)SL_GET_NODE_DATA(node);
    TSKEY   key = TD_ROW_KEY(row);  // first timestamp in buffer
695
    tsdbDebug("%p uid:%" PRId64 ", check data in mem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
H
Haojun Liao 已提交
696 697
              "-%" PRId64 ", lastKey:%" PRId64 ", numOfRows:%"PRId64", %s",
              pHandle, pCheckInfo->tableId, key, order, (*pMem)->keyMin, (*pMem)->keyMax, pCheckInfo->lastKey, (*pMem)->nrows, pHandle->idStr);
H
Haojun Liao 已提交
698 699 700 701 702 703 704

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

705
  } else {
H
Haojun Liao 已提交
706
    tsdbDebug("%p uid:%"PRId64", no data in mem, %s", pHandle, pCheckInfo->tableId, pHandle->idStr);
707
  }
H
Haojun Liao 已提交
708

709 710 711
  if (!imemEmpty) {
    SSkipListNode* node = tSkipListIterGet(pCheckInfo->iiter);
    assert(node != NULL);
H
Haojun Liao 已提交
712

H
Haojun Liao 已提交
713 714
    STSRow* row = (STSRow*)SL_GET_NODE_DATA(node);
    TSKEY   key = TD_ROW_KEY(row);  // first timestamp in buffer
715
    tsdbDebug("%p uid:%" PRId64 ", check data in imem from skey:%" PRId64 ", order:%d, ts range in buf:%" PRId64
H
Haojun Liao 已提交
716 717
              "-%" PRId64 ", lastKey:%" PRId64 ", numOfRows:%"PRId64", %s",
              pHandle, pCheckInfo->tableId, key, order, (*pIMem)->keyMin, (*pIMem)->keyMax, pCheckInfo->lastKey, (*pIMem)->nrows, pHandle->idStr);
H
Haojun Liao 已提交
718 719 720 721 722 723

    if (ASCENDING_TRAVERSE(order)) {
      assert(pCheckInfo->lastKey <= key);
    } else {
      assert(pCheckInfo->lastKey >= key);
    }
724
  } else {
H
Haojun Liao 已提交
725
    tsdbDebug("%p uid:%"PRId64", no data in imem, %s", pHandle, pCheckInfo->tableId, pHandle->idStr);
726
  }
H
Haojun Liao 已提交
727

728 729 730
  return true;
}

H
Haojun Liao 已提交
731 732 733 734 735
static void destroyTableMemIterator(STableCheckInfo* pCheckInfo) {
  tSkipListDestroyIter(pCheckInfo->iter);
  tSkipListDestroyIter(pCheckInfo->iiter);
}

736
static TSKEY extractFirstTraverseKey(STableCheckInfo* pCheckInfo, int32_t order, int32_t update) {
H
Haojun Liao 已提交
737
  STSRow *rmem = NULL, *rimem = NULL;
738 739 740
  if (pCheckInfo->iter) {
    SSkipListNode* node = tSkipListIterGet(pCheckInfo->iter);
    if (node != NULL) {
H
Haojun Liao 已提交
741
      rmem = (STSRow*)SL_GET_NODE_DATA(node);
742 743 744 745 746 747
    }
  }

  if (pCheckInfo->iiter) {
    SSkipListNode* node = tSkipListIterGet(pCheckInfo->iiter);
    if (node != NULL) {
H
Haojun Liao 已提交
748
      rimem = (STSRow*)SL_GET_NODE_DATA(node);
749 750 751 752 753 754 755 756 757
    }
  }

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

  if (rmem != NULL && rimem == NULL) {
    pCheckInfo->chosen = CHECKINFO_CHOSEN_MEM;
H
Haojun Liao 已提交
758
    return TD_ROW_KEY(rmem);
759 760 761 762
  }

  if (rmem == NULL && rimem != NULL) {
    pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
H
Haojun Liao 已提交
763
    return TD_ROW_KEY(rimem);
764 765
  }

H
Haojun Liao 已提交
766 767
  TSKEY r1 = TD_ROW_KEY(rmem);
  TSKEY r2 = TD_ROW_KEY(rimem);
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790

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

H
Haojun Liao 已提交
791 792
static STSRow* getSRowInTableMem(STableCheckInfo* pCheckInfo, int32_t order, int32_t update, STSRow** extraRow) {
  STSRow *rmem = NULL, *rimem = NULL;
H
Haojun Liao 已提交
793 794 795
  if (pCheckInfo->iter) {
    SSkipListNode* node = tSkipListIterGet(pCheckInfo->iter);
    if (node != NULL) {
H
Haojun Liao 已提交
796
      rmem = (STSRow*)SL_GET_NODE_DATA(node);
H
Haojun Liao 已提交
797 798
    }
  }
799

H
Haojun Liao 已提交
800 801 802
  if (pCheckInfo->iiter) {
    SSkipListNode* node = tSkipListIterGet(pCheckInfo->iiter);
    if (node != NULL) {
H
Haojun Liao 已提交
803
      rimem = (STSRow*)SL_GET_NODE_DATA(node);
H
Haojun Liao 已提交
804 805
    }
  }
806

H
Haojun Liao 已提交
807 808
  if (rmem == NULL && rimem == NULL) {
    return NULL;
H
Haojun Liao 已提交
809
  }
810

H
Haojun Liao 已提交
811
  if (rmem != NULL && rimem == NULL) {
H
Haojun Liao 已提交
812 813 814
    pCheckInfo->chosen = 0;
    return rmem;
  }
815

H
Haojun Liao 已提交
816
  if (rmem == NULL && rimem != NULL) {
H
Haojun Liao 已提交
817 818 819
    pCheckInfo->chosen = 1;
    return rimem;
  }
820

H
Haojun Liao 已提交
821 822
  TSKEY r1 = TD_ROW_KEY(rmem);
  TSKEY r2 = TD_ROW_KEY(rimem);
H
Haojun Liao 已提交
823

824 825
  if (r1 == r2) {
    if (update == TD_ROW_DISCARD_UPDATE) {
H
TD-1439  
Hongze Cheng 已提交
826
      tSkipListIterNext(pCheckInfo->iter);
827
      pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
H
TD-1439  
Hongze Cheng 已提交
828
      return rimem;
829
    } else if(update == TD_ROW_OVERWRITE_UPDATE){
H
TD-1439  
Hongze Cheng 已提交
830
      tSkipListIterNext(pCheckInfo->iiter);
831 832 833 834
      pCheckInfo->chosen = CHECKINFO_CHOSEN_MEM;
      return rmem;
    } else {
      pCheckInfo->chosen = CHECKINFO_CHOSEN_BOTH;
H
Haojun Liao 已提交
835
      *extraRow = rimem;
H
TD-1439  
Hongze Cheng 已提交
836 837
      return rmem;
    }
H
Haojun Liao 已提交
838 839 840
  } else {
    if (ASCENDING_TRAVERSE(order)) {
      if (r1 < r2) {
841
        pCheckInfo->chosen = CHECKINFO_CHOSEN_MEM;
H
Haojun Liao 已提交
842 843
        return rmem;
      } else {
844
        pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
H
Haojun Liao 已提交
845 846 847 848
        return rimem;
      }
    } else {
      if (r1 < r2) {
849
        pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
H
Haojun Liao 已提交
850 851
        return rimem;
      } else {
852
        pCheckInfo->chosen = CHECKINFO_CHOSEN_IMEM;
H
Haojun Liao 已提交
853 854 855 856
        return rmem;
      }
    }
  }
H
Haojun Liao 已提交
857 858
}

859
static bool moveToNextRowInMem(STableCheckInfo* pCheckInfo) {
H
Haojun Liao 已提交
860
  bool hasNext = false;
861
  if (pCheckInfo->chosen == CHECKINFO_CHOSEN_MEM) {
H
Haojun Liao 已提交
862 863 864
    if (pCheckInfo->iter != NULL) {
      hasNext = tSkipListIterNext(pCheckInfo->iter);
    }
865

H
Haojun Liao 已提交
866 867 868
    if (hasNext) {
      return hasNext;
    }
869

H
Haojun Liao 已提交
870 871 872
    if (pCheckInfo->iiter != NULL) {
      return tSkipListIterGet(pCheckInfo->iiter) != NULL;
    }
873
  } else if (pCheckInfo->chosen == CHECKINFO_CHOSEN_IMEM){
874 875 876
    if (pCheckInfo->iiter != NULL) {
      hasNext = tSkipListIterNext(pCheckInfo->iiter);
    }
877

878 879 880
    if (hasNext) {
      return hasNext;
    }
881

882 883
    if (pCheckInfo->iter != NULL) {
      return tSkipListIterGet(pCheckInfo->iter) != NULL;
H
Haojun Liao 已提交
884
    }
885 886 887 888 889 890 891
  } else {
    if (pCheckInfo->iter != NULL) {
      hasNext = tSkipListIterNext(pCheckInfo->iter);
    }
    if (pCheckInfo->iiter != NULL) {
      hasNext = tSkipListIterNext(pCheckInfo->iiter) || hasNext;
    }
H
Haojun Liao 已提交
892
  }
893

H
Haojun Liao 已提交
894 895 896
  return hasNext;
}

897
static bool hasMoreDataInCache(STsdbReadHandle* pHandle) {
H
TD-1439  
Hongze Cheng 已提交
898
  STsdbCfg *pCfg = &pHandle->pTsdb->config;
899 900
  size_t size = taosArrayGetSize(pHandle->pTableCheckInfo);
  assert(pHandle->activeIndex < size && pHandle->activeIndex >= 0 && size >= 1);
D
dapan1121 已提交
901
  pHandle->cur.fid = INT32_MIN;
H
Haojun Liao 已提交
902

903
  STableCheckInfo* pCheckInfo = taosArrayGet(pHandle->pTableCheckInfo, pHandle->activeIndex);
H
Haojun Liao 已提交
904 905 906 907
  if (!pCheckInfo->initBuf) {
    initTableMemIterator(pHandle, pCheckInfo);
  }

H
Haojun Liao 已提交
908
  STSRow* row = getSRowInTableMem(pCheckInfo, pHandle->order, pCfg->update, NULL);
H
Haojun Liao 已提交
909
  if (row == NULL) {
910 911
    return false;
  }
912

H
Haojun Liao 已提交
913
  pCheckInfo->lastKey = TD_ROW_KEY(row);  // first timestamp in buffer
H
Haojun Liao 已提交
914 915
  tsdbDebug("%p uid:%" PRId64", check data in buffer from skey:%" PRId64 ", order:%d, %s", pHandle,
      pCheckInfo->tableId,  pCheckInfo->lastKey, pHandle->order, pHandle->idStr);
H
Haojun Liao 已提交
916

917
  // all data in mem are checked already.
918 919
  if ((pCheckInfo->lastKey > pHandle->window.ekey && ASCENDING_TRAVERSE(pHandle->order)) ||
      (pCheckInfo->lastKey < pHandle->window.ekey && !ASCENDING_TRAVERSE(pHandle->order))) {
920 921
    return false;
  }
H
Haojun Liao 已提交
922

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

927 928 929 930
  // update the last key value
  pCheckInfo->lastKey = win->ekey + step;
  pHandle->cur.lastKey = win->ekey + step;
  pHandle->cur.mixBlock = true;
931

932
  if (!ASCENDING_TRAVERSE(pHandle->order)) {
dengyihao's avatar
dengyihao 已提交
933
    TSWAP(win->skey, win->ekey, TSKEY);
934
  }
H
Haojun Liao 已提交
935

936
  return true;
937
}
H
hjxilinx 已提交
938

939 940
static int32_t getFileIdFromKey(TSKEY key, int32_t daysPerFile, int32_t precision) {
  assert(precision >= TSDB_TIME_PRECISION_MICRO || precision <= TSDB_TIME_PRECISION_NANO);
941 942 943
  if (key == TSKEY_INITIAL_VAL) {
    return INT32_MIN;
  }
H
Haojun Liao 已提交
944

D
dapan1121 已提交
945
  if (key < 0) {
946
    key -= (daysPerFile * tsTickPerDay[precision]);
D
dapan1121 已提交
947 948
  }
  
949
  int64_t fid = (int64_t)(key / (daysPerFile * tsTickPerDay[precision]));  // set the starting fileId
950 951 952
  if (fid < 0L && llabs(fid) > INT32_MAX) { // data value overflow for INT32
    fid = INT32_MIN;
  }
H
Haojun Liao 已提交
953

954
  if (fid > 0L && fid > INT32_MAX) {
955 956
    fid = INT32_MAX;
  }
H
Haojun Liao 已提交
957

S
TD-1057  
Shengliang Guan 已提交
958
  return (int32_t)fid;
959 960
}

H
refact  
Hongze Cheng 已提交
961
static int32_t binarySearchForBlock(SBlock* pBlock, int32_t numOfBlocks, TSKEY skey, int32_t order) {
962 963
  int32_t firstSlot = 0;
  int32_t lastSlot = numOfBlocks - 1;
H
Haojun Liao 已提交
964

965
  int32_t midSlot = firstSlot;
H
Haojun Liao 已提交
966

967 968 969
  while (1) {
    numOfBlocks = lastSlot - firstSlot + 1;
    midSlot = (firstSlot + (numOfBlocks >> 1));
H
Haojun Liao 已提交
970

971
    if (numOfBlocks == 1) break;
H
Haojun Liao 已提交
972

973 974 975 976 977 978 979 980 981 982 983
    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 已提交
984

985 986
  return midSlot;
}
987

988
static int32_t loadBlockInfo(STsdbReadHandle * pTsdbReadHandle, int32_t index, int32_t* numOfBlocks) {
H
Haojun Liao 已提交
989
  int32_t code = 0;
H
Haojun Liao 已提交
990

991
  STableCheckInfo* pCheckInfo = taosArrayGet(pTsdbReadHandle->pTableCheckInfo, index);
H
Haojun Liao 已提交
992
  pCheckInfo->numOfBlocks = 0;
993

H
Haojun Liao 已提交
994 995 996 997
  STable table = {.uid = pCheckInfo->tableId, .tid = pCheckInfo->tableId};
  table.pSchema = metaGetTbTSchema(pTsdbReadHandle->pTsdb->pMeta, pCheckInfo->tableId, 0);

  if (tsdbSetReadTable(&pTsdbReadHandle->rhelper, &table) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
998 999 1000
    code = terrno;
    return code;
  }
1001

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

H
Haojun Liao 已提交
1004
  // no data block in this file, try next file
1005
  if (compIndex == NULL || compIndex->uid != pCheckInfo->tableId) {
H
Haojun Liao 已提交
1006 1007
    return 0;  // no data blocks in the file belongs to pCheckInfo->pTable
  }
1008

H
Haojun Liao 已提交
1009 1010 1011 1012 1013 1014 1015 1016
  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;
1017 1018
    }

H
Haojun Liao 已提交
1019 1020 1021
    pCheckInfo->pCompInfo = (SBlockInfo*)t;
    pCheckInfo->compSize = compIndex->len;
  }
1022

1023
  if (tsdbLoadBlockInfo(&(pTsdbReadHandle->rhelper), (void*)(pCheckInfo->pCompInfo)) < 0) {
H
Hongze Cheng 已提交
1024 1025
    return terrno;
  }
H
Haojun Liao 已提交
1026
  SBlockInfo* pCompInfo = pCheckInfo->pCompInfo;
1027

H
Haojun Liao 已提交
1028
  TSKEY s = TSKEY_INITIAL_VAL, e = TSKEY_INITIAL_VAL;
1029

1030 1031
  if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
    assert(pCheckInfo->lastKey <= pTsdbReadHandle->window.ekey && pTsdbReadHandle->window.skey <= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
1032
  } else {
1033
    assert(pCheckInfo->lastKey >= pTsdbReadHandle->window.ekey && pTsdbReadHandle->window.skey >= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
1034
  }
1035

dengyihao's avatar
dengyihao 已提交
1036 1037
  s = TMIN(pCheckInfo->lastKey, pTsdbReadHandle->window.ekey);
  e = TMAX(pCheckInfo->lastKey, pTsdbReadHandle->window.ekey);
1038

H
Haojun Liao 已提交
1039 1040 1041
  // 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 已提交
1042

H
Haojun Liao 已提交
1043 1044 1045
  if (s > pCompInfo->blocks[start].keyLast) {
    return 0;
  }
1046

H
Haojun Liao 已提交
1047 1048 1049 1050
  // todo speedup the procedure of located end block
  while (end < (int32_t)compIndex->numOfBlocks && (pCompInfo->blocks[end].keyFirst <= e)) {
    end += 1;
  }
1051

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

H
Haojun Liao 已提交
1054 1055 1056
  if (start > 0) {
    memmove(pCompInfo->blocks, &pCompInfo->blocks[start], pCheckInfo->numOfBlocks * sizeof(SBlock));
  }
1057

H
Haojun Liao 已提交
1058 1059 1060
  (*numOfBlocks) += pCheckInfo->numOfBlocks;
  return 0;
}
1061

1062
static int32_t getFileCompInfo(STsdbReadHandle* pTsdbReadHandle, int32_t* numOfBlocks) {
H
Haojun Liao 已提交
1063 1064 1065 1066
  // load all the comp offset value for all tables in this file
  int32_t code = TSDB_CODE_SUCCESS;
  *numOfBlocks = 0;

1067
  pTsdbReadHandle->cost.headFileLoad += 1;
1068 1069
  int64_t s = taosGetTimestampUs();

H
Haojun Liao 已提交
1070
  size_t numOfTables = 0;
1071 1072 1073 1074
  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);
1075

H
Haojun Liao 已提交
1076
    for (int32_t i = 0; i < numOfTables; ++i) {
1077
      code = loadBlockInfo(pTsdbReadHandle, i, numOfBlocks);
H
Haojun Liao 已提交
1078
      if (code != TSDB_CODE_SUCCESS) {
1079 1080
        int64_t e = taosGetTimestampUs();

1081
        pTsdbReadHandle->cost.headFileLoadTime += (e - s);
H
Haojun Liao 已提交
1082 1083 1084 1085 1086
        return code;
      }
    }
  } else {
    assert(0);
1087
  }
1088

1089
  int64_t e = taosGetTimestampUs();
1090
  pTsdbReadHandle->cost.headFileLoadTime += (e - s);
H
Haojun Liao 已提交
1091
  return code;
1092 1093
}

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

H
Haojun Liao 已提交
1097
  STSchema *pSchema = metaGetTbTSchema(pTsdbReadHandle->pTsdb->pMeta, pCheckInfo->tableId, 0);
1098
  int32_t   code = tdInitDataCols(pTsdbReadHandle->pDataCols, pSchema);
H
Haojun Liao 已提交
1099
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1100
    tsdbError("%p failed to malloc buf for pDataCols, %s", pTsdbReadHandle, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
1101 1102 1103 1104
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _error;
  }

1105
  code = tdInitDataCols(pTsdbReadHandle->rhelper.pDCols[0], pSchema);
H
Haojun Liao 已提交
1106
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1107
    tsdbError("%p failed to malloc buf for rhelper.pDataCols[0], %s", pTsdbReadHandle, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
1108 1109 1110 1111
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _error;
  }

1112
  code = tdInitDataCols(pTsdbReadHandle->rhelper.pDCols[1], pSchema);
H
Haojun Liao 已提交
1113
  if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1114
    tsdbError("%p failed to malloc buf for rhelper.pDataCols[1], %s", pTsdbReadHandle, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
1115 1116 1117
    terrno = TSDB_CODE_TDB_OUT_OF_MEMORY;
    goto _error;
  }
1118

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

1121
  int32_t ret = tsdbLoadBlockDataCols(&(pTsdbReadHandle->rhelper), pBlock, pCheckInfo->pCompInfo, colIds, (int)(QH_GET_NUM_OF_COLS(pTsdbReadHandle)));
H
Haojun Liao 已提交
1122
  if (ret != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1123 1124 1125
    int32_t c = terrno;
    assert(c != TSDB_CODE_SUCCESS);
    goto _error;
H
Haojun Liao 已提交
1126
  }
1127

1128
  SDataBlockLoadInfo* pBlockLoadInfo = &pTsdbReadHandle->dataBlockLoadInfo;
1129

1130 1131
  pBlockLoadInfo->fileGroup = pTsdbReadHandle->pFileGroup;
  pBlockLoadInfo->slot = pTsdbReadHandle->cur.slot;
H
Haojun Liao 已提交
1132
  pBlockLoadInfo->uid = pCheckInfo->tableId;
1133

1134
  SDataCols* pCols = pTsdbReadHandle->rhelper.pDCols[0];
1135
  assert(pCols->numOfRows != 0 && pCols->numOfRows <= pBlock->numOfRows);
1136

1137
  pBlock->numOfRows = pCols->numOfRows;
H
Haojun Liao 已提交
1138

1139
  // Convert from TKEY to TSKEY for primary timestamp column if current block has timestamp before 1970-01-01T00:00:00Z
1140
  if(pBlock->keyFirst < 0 && colIds[0] == PRIMARYKEY_TIMESTAMP_COL_ID) {
1141 1142 1143 1144 1145 1146
    int64_t* src = pCols->cols[0].pData;
    for(int32_t i = 0; i < pBlock->numOfRows; ++i) {
      src[i] = tdGetKey(src[i]);
    }
  }

H
Haojun Liao 已提交
1147
  int64_t elapsedTime = (taosGetTimestampUs() - st);
1148
  pTsdbReadHandle->cost.blockLoadTime += elapsedTime;
1149

H
Haojun Liao 已提交
1150 1151
  tsdbDebug("%p load file block into buffer, index:%d, brange:%"PRId64"-%"PRId64", rows:%d, elapsed time:%"PRId64 " us, %s",
      pTsdbReadHandle, slotIndex, pBlock->keyFirst, pBlock->keyLast, pBlock->numOfRows, elapsedTime, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
1152
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1153 1154 1155 1156

_error:
  pBlock->numOfRows = 0;

H
Haojun Liao 已提交
1157 1158
  tsdbError("%p error occurs in loading file block, index:%d, brange:%"PRId64"-%"PRId64", rows:%d, %s",
            pTsdbReadHandle, slotIndex, pBlock->keyFirst, pBlock->keyLast, pBlock->numOfRows, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
1159
  return terrno;
H
hjxilinx 已提交
1160 1161
}

1162 1163 1164 1165 1166
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);
1167

1168 1169 1170
static int32_t handleDataMergeIfNeeded(STsdbReadHandle* pTsdbReadHandle, SBlock* pBlock, STableCheckInfo* pCheckInfo){
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
  STsdbCfg*      pCfg = &pTsdbReadHandle->pTsdb->config;
H
Haojun Liao 已提交
1171
  SDataBlockInfo binfo = GET_FILE_DATA_BLOCK_INFO(pCheckInfo, pBlock);
1172
  TSKEY          key;
H
Haojun Liao 已提交
1173
  int32_t code = TSDB_CODE_SUCCESS;
1174

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

1178
  key = extractFirstTraverseKey(pCheckInfo, pTsdbReadHandle->order, pCfg->update);
1179

H
Haojun Liao 已提交
1180
  if (key != TSKEY_INITIAL_VAL) {
H
Haojun Liao 已提交
1181
    tsdbDebug("%p key in mem:%"PRId64", %s", pTsdbReadHandle, key, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
1182
  } else {
H
Haojun Liao 已提交
1183
    tsdbDebug("%p no data in mem, %s", pTsdbReadHandle, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
1184
  }
H
Haojun Liao 已提交
1185

1186 1187
  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 已提交
1188

1189 1190
    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))) {
1191

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

1195 1196 1197
      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 已提交
1198 1199 1200

      // update the last key value
      pCheckInfo->lastKey = cur->win.ekey + step;
1201
      if (!ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
dengyihao's avatar
dengyihao 已提交
1202
        TSWAP(cur->win.skey, cur->win.ekey, TSKEY);
H
Haojun Liao 已提交
1203
      }
H
Haojun Liao 已提交
1204

H
Haojun Liao 已提交
1205 1206
      cur->mixBlock = true;
      cur->blockCompleted = false;
H
Haojun Liao 已提交
1207
      return code;
H
Haojun Liao 已提交
1208
    }
H
Haojun Liao 已提交
1209

1210

1211
    // return error, add test cases
1212
    if ((code = doLoadFileDataBlock(pTsdbReadHandle, pBlock, pCheckInfo, cur->slot)) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1213
      return code;
1214 1215
    }

1216
    doMergeTwoLevelData(pTsdbReadHandle, pCheckInfo, pBlock);
1217
  } else {
1218 1219 1220 1221 1222 1223
    /*
     * 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
     */
1224 1225
    assert(pTsdbReadHandle->outputCapacity >= binfo.rows);
    int32_t endPos = getEndPosInDataBlock(pTsdbReadHandle, &binfo);
1226

1227 1228 1229
    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;
1230 1231 1232 1233

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

1236
      if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
H
Haojun Liao 已提交
1237 1238 1239 1240 1241 1242
        cur->lastKey = binfo.window.ekey + 1;
        cur->pos = binfo.rows;
      } else {
        cur->lastKey = binfo.window.skey - 1;
        cur->pos = -1;
      }
H
Haojun Liao 已提交
1243
    } else { // partially copy to dest buffer
1244
      copyAllRemainRowsFromFileBlock(pTsdbReadHandle, pCheckInfo, &binfo, endPos);
1245 1246
      cur->mixBlock = true;
    }
1247

H
Haojun Liao 已提交
1248
    assert(cur->blockCompleted);
H
Haojun Liao 已提交
1249
    if (cur->rows == binfo.rows) {
H
Haojun Liao 已提交
1250 1251
      tsdbDebug("%p whole file block qualified, brange:%"PRId64"-%"PRId64", rows:%d, lastKey:%"PRId64", %s",
                pTsdbReadHandle, cur->win.skey, cur->win.ekey, cur->rows, cur->lastKey, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
1252
    } else {
H
Haojun Liao 已提交
1253 1254
      tsdbDebug("%p create data block from remain file block, brange:%"PRId64"-%"PRId64", rows:%d, total:%d, lastKey:%"PRId64", %s",
                pTsdbReadHandle, cur->win.skey, cur->win.ekey, cur->rows, binfo.rows, cur->lastKey, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
1255 1256
    }

1257
  }
H
Haojun Liao 已提交
1258 1259

  return code;
1260 1261
}

1262 1263
static int32_t loadFileDataBlock(STsdbReadHandle* pTsdbReadHandle, SBlock* pBlock, STableCheckInfo* pCheckInfo, bool* exists) {
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
H
Haojun Liao 已提交
1264
  int32_t code = TSDB_CODE_SUCCESS;
1265
  bool asc = ASCENDING_TRAVERSE(pTsdbReadHandle->order);
1266

1267
  if (asc) {
H
Haojun Liao 已提交
1268
    // query ended in/started from current block
1269 1270
    if (pTsdbReadHandle->window.ekey < pBlock->keyLast || pCheckInfo->lastKey > pBlock->keyFirst) {
      if ((code = doLoadFileDataBlock(pTsdbReadHandle, pBlock, pCheckInfo, cur->slot)) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1271 1272
        *exists = false;
        return code;
1273
      }
1274

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

1278 1279
      if (pCheckInfo->lastKey > pBlock->keyFirst) {
        cur->pos =
1280
            binarySearchForKey(pTSCol->cols[0].pData, pBlock->numOfRows, pCheckInfo->lastKey, pTsdbReadHandle->order);
1281 1282 1283
      } else {
        cur->pos = 0;
      }
H
Haojun Liao 已提交
1284

H
Haojun Liao 已提交
1285
      assert(pCheckInfo->lastKey <= pBlock->keyLast);
1286
      doMergeTwoLevelData(pTsdbReadHandle, pCheckInfo, pBlock);
1287
    } else {  // the whole block is loaded in to buffer
1288
      cur->pos = asc? 0:(pBlock->numOfRows - 1);
1289
      code = handleDataMergeIfNeeded(pTsdbReadHandle, pBlock, pCheckInfo);
H
[td-32]  
hjxilinx 已提交
1290
    }
1291
  } else {  //desc order, query ended in current block
1292 1293
    if (pTsdbReadHandle->window.ekey > pBlock->keyFirst || pCheckInfo->lastKey < pBlock->keyLast) {
      if ((code = doLoadFileDataBlock(pTsdbReadHandle, pBlock, pCheckInfo, cur->slot)) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1294 1295
        *exists = false;
        return code;
1296
      }
H
Haojun Liao 已提交
1297

1298
      SDataCols* pTsCol = pTsdbReadHandle->rhelper.pDCols[0];
1299
      if (pCheckInfo->lastKey < pBlock->keyLast) {
1300
        cur->pos = binarySearchForKey(pTsCol->cols[0].pData, pBlock->numOfRows, pCheckInfo->lastKey, pTsdbReadHandle->order);
1301
      } else {
H
Haojun Liao 已提交
1302
        cur->pos = pBlock->numOfRows - 1;
1303
      }
H
Haojun Liao 已提交
1304

H
Haojun Liao 已提交
1305
      assert(pCheckInfo->lastKey >= pBlock->keyFirst);
1306
      doMergeTwoLevelData(pTsdbReadHandle, pCheckInfo, pBlock);
1307
    } else {
1308
      cur->pos = asc? 0:(pBlock->numOfRows-1);
1309
      code = handleDataMergeIfNeeded(pTsdbReadHandle, pBlock, pCheckInfo);
H
[td-32]  
hjxilinx 已提交
1310
    }
1311
  }
1312

1313
  *exists = pTsdbReadHandle->realNumOfRows > 0;
H
Haojun Liao 已提交
1314
  return code;
H
[td-32]  
hjxilinx 已提交
1315 1316
}

1317
static int doBinarySearchKey(char* pValue, int num, TSKEY key, int order) {
1318
  int    firstPos, lastPos, midPos = -1;
H
Haojun Liao 已提交
1319
  int    numOfRows;
1320 1321
  TSKEY* keyList;

1322
  assert(order == TSDB_ORDER_ASC || order == TSDB_ORDER_DESC);
H
Haojun Liao 已提交
1323

1324
  if (num <= 0) return -1;
1325 1326

  keyList = (TSKEY*)pValue;
1327 1328
  firstPos = 0;
  lastPos = num - 1;
1329

1330
  if (order == TSDB_ORDER_DESC) {
1331 1332 1333 1334 1335
    // 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;
1336

H
Haojun Liao 已提交
1337 1338
      numOfRows = lastPos - firstPos + 1;
      midPos = (numOfRows >> 1) + firstPos;
1339

1340 1341 1342 1343 1344 1345 1346 1347
      if (key < keyList[midPos]) {
        lastPos = midPos - 1;
      } else if (key > keyList[midPos]) {
        firstPos = midPos + 1;
      } else {
        break;
      }
    }
1348

1349 1350 1351 1352 1353
  } 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;
1354

1355 1356 1357 1358 1359 1360 1361
      if (key > keyList[lastPos]) {
        lastPos = lastPos + 1;
        if (lastPos >= num)
          return -1;
        else
          return lastPos;
      }
1362

H
Haojun Liao 已提交
1363 1364
      numOfRows = lastPos - firstPos + 1;
      midPos = (numOfRows >> 1) + firstPos;
1365

1366 1367 1368 1369 1370 1371 1372 1373 1374
      if (key < keyList[midPos]) {
        lastPos = midPos - 1;
      } else if (key > keyList[midPos]) {
        firstPos = midPos + 1;
      } else {
        break;
      }
    }
  }
1375

1376 1377 1378
  return midPos;
}

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

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

1386
  int32_t num = end - start + 1;
H
Haojun Liao 已提交
1387 1388 1389 1390 1391 1392
  assert(num >= 0);

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

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

1395
  //data in buffer has greater timestamp, copy data in file block
1396 1397
  int32_t i = 0, j = 0;
  while(i < requiredNumOfCols && j < pCols->numOfCols) {
1398
    SColumnInfoData* pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, i);
1399 1400 1401 1402 1403 1404 1405 1406 1407

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

    int32_t bytes = pColInfo->info.bytes;

1408
    if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
S
TD-1057  
Shengliang Guan 已提交
1409
      pData = (char*)pColInfo->pData + numOfRows * pColInfo->info.bytes;
1410
    } else {
S
TD-1057  
Shengliang Guan 已提交
1411
      pData = (char*)pColInfo->pData + (capacity - numOfRows - num) * pColInfo->info.bytes;
1412
    }
1413

L
Liu Jicong 已提交
1414
    if (!isAllRowsNull(src) && pColInfo->info.colId == src->colId) {
1415 1416 1417 1418 1419 1420 1421
      if (!IS_VAR_DATA_TYPE(pColInfo->info.type)) {  // todo opt performance
//        memmove(pData, (char*)src->pData + bytes * start, bytes * num);
        for(int32_t k = start; k < num + start; ++k) {
          SCellVal sVal = {0};
          if (tdGetColDataOfRow(&sVal, src, k) < 0) {
            TASSERT(0);
          }
1422

1423 1424 1425 1426 1427 1428 1429
          if (sVal.valType == TD_VTYPE_NULL) {
            colDataAppend(pColInfo, k, NULL, true);
          } else {
            colDataAppend(pColInfo, k, sVal.val, false);
          }
        }
      } else {  // handle the var-string
1430 1431
        // todo refactor, only copy one-by-one
        for (int32_t k = start; k < num + start; ++k) {
1432
          SCellVal sVal = {0};
H
Haojun Liao 已提交
1433 1434 1435
          if(tdGetColDataOfRow(&sVal, src, k) < 0){
            TASSERT(0);
          }
1436 1437

          colDataAppend(pColInfo, k, sVal.val, false);
1438 1439
        }
      }
1440 1441 1442 1443

      j++;
      i++;
    } else { // pColInfo->info.colId < src->colId, it is a NULL data
1444 1445
      for(int32_t k = start; k < num + start; ++k) {  // TODO opt performance
        colDataAppend(pColInfo, k, NULL, true);
1446 1447
      }
      i++;
1448 1449
    }
  }
1450 1451

  while (i < requiredNumOfCols) { // the remain columns are all null data
1452
    SColumnInfoData* pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, i);
1453 1454
    for(int32_t k = start; k < num + start; ++k) {
      colDataAppend(pColInfo, k, NULL, true); // TODO add a fast version to set a number of consecutive NULL value.
1455 1456
    }
    i++;
1457
  }
H
Haojun Liao 已提交
1458

1459 1460
  pTsdbReadHandle->cur.win.ekey = tsArray[end];
  pTsdbReadHandle->cur.lastKey = tsArray[end] + step;
1461

1462
  return numOfRows + num;
1463 1464
}

H
Haojun Liao 已提交
1465 1466
// TODO fix bug for reverse copy data
// TODO handle the null data
1467
// Note: row1 always has high priority
H
Haojun Liao 已提交
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
static void mergeTwoRowFromMem(STsdbReadHandle* pTsdbReadHandle, int32_t capacity, int32_t numOfRows, STSRow* row1,
                               STSRow* row2, int32_t numOfCols, uint64_t uid, STSchema* pSchema1, STSchema* pSchema2,
                               bool forceSetNull) {
#if 1
  char*       pData = NULL;
  STSchema*   pSchema;
  STSRow*     row;
  int16_t     colId;
  int16_t     offset;

  bool isRow1DataRow = TD_IS_TP_ROW(row1);
1479 1480 1481
  bool isRow2DataRow;
  bool isChosenRowDataRow;
  int32_t chosen_itr;
H
Haojun Liao 已提交
1482
  SCellVal sVal = {0};
1483

H
Haojun Liao 已提交
1484
  // the schema version info is embeded in STSRow
1485 1486 1487
  int32_t numOfColsOfRow1 = 0;

  if (pSchema1 == NULL) {
H
Haojun Liao 已提交
1488
    pSchema1 = metaGetTbTSchema(pTsdbReadHandle->pTsdb->pMeta, uid, TD_ROW_SVER(row1));
1489
  }
1490

1491 1492
  if(isRow1DataRow) {
    numOfColsOfRow1 = schemaNCols(pSchema1);
H
Haojun Liao 已提交
1493
  } else {
H
Haojun Liao 已提交
1494
    numOfColsOfRow1 = tdRowGetNCols(row1);
D
fix bug  
dapan1121 已提交
1495
  }
1496

1497 1498
  int32_t numOfColsOfRow2 = 0;
  if(row2) {
H
Haojun Liao 已提交
1499
    isRow2DataRow = TD_IS_TP_ROW(row2);
1500
    if (pSchema2 == NULL) {
H
Haojun Liao 已提交
1501
      pSchema2 = metaGetTbTSchema(pTsdbReadHandle->pTsdb->pMeta, uid, TD_ROW_SVER(row2));
1502 1503 1504 1505
    }
    if(isRow2DataRow) {
      numOfColsOfRow2 = schemaNCols(pSchema2);
    } else {
H
Haojun Liao 已提交
1506
      numOfColsOfRow2 = tdRowGetNCols(row2);
1507 1508
    }
  }
C
Cary Xu 已提交
1509

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

1514
    if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
      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 {
H
Haojun Liao 已提交
1526
      SKvRowIdx *pColIdx = tdKvRowColIdxAt(row1, j);
1527 1528 1529 1530 1531 1532 1533 1534 1535
      colIdOfRow1 = pColIdx->colId;
    }

    int32_t colIdOfRow2;
    if(k >= numOfColsOfRow2) {
      colIdOfRow2 = INT32_MAX;
    } else if(isRow2DataRow) {
      colIdOfRow2 = pSchema2->columns[k].colId;
    } else {
H
Haojun Liao 已提交
1536
      SKvRowIdx *pColIdx = tdKvRowColIdxAt(row2, k);
1537 1538 1539 1540 1541
      colIdOfRow2 = pColIdx->colId;
    }

    if(colIdOfRow1 == colIdOfRow2) {
      if(colIdOfRow1 < pColInfo->info.colId) {
C
Cary Xu 已提交
1542
        j++;
1543
        k++;
C
Cary Xu 已提交
1544 1545
        continue;
      }
1546 1547 1548 1549 1550 1551 1552 1553
      row = row1;
      pSchema = pSchema1;
      isChosenRowDataRow = isRow1DataRow;
      chosen_itr = j;
    } else if(colIdOfRow1 < colIdOfRow2) {
      if(colIdOfRow1 < pColInfo->info.colId) {
        j++;
        continue;
C
Cary Xu 已提交
1554
      }
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
      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;
H
Haojun Liao 已提交
1572
      tdSTpRowGetVal(row, colId, pSchema->columns[chosen_itr].type, pSchema->flen, offset, chosen_itr, &sVal);
1573
    } else {
H
Haojun Liao 已提交
1574
      SKvRowIdx *pColIdx = tdKvRowColIdxAt(row, chosen_itr);
1575 1576
      colId = pColIdx->colId;
      offset = pColIdx->offset;
H
Haojun Liao 已提交
1577
      tdSKvRowGetVal(row, colId, offset, chosen_itr, &sVal);
1578 1579 1580
    }

    if (colId == pColInfo->info.colId) {
H
Haojun Liao 已提交
1581
      if (tdValTypeIsNorm(sVal.valType)) {
C
Cary Xu 已提交
1582 1583 1584
        switch (pColInfo->info.type) {
          case TSDB_DATA_TYPE_BINARY:
          case TSDB_DATA_TYPE_NCHAR:
H
Haojun Liao 已提交
1585
            memcpy(pData, sVal.val, varDataTLen(sVal.val));
C
Cary Xu 已提交
1586 1587 1588 1589
            break;
          case TSDB_DATA_TYPE_BOOL:
          case TSDB_DATA_TYPE_TINYINT:
          case TSDB_DATA_TYPE_UTINYINT:
H
Haojun Liao 已提交
1590
            *(uint8_t *)pData = *(uint8_t *)sVal.val;
C
Cary Xu 已提交
1591 1592 1593
            break;
          case TSDB_DATA_TYPE_SMALLINT:
          case TSDB_DATA_TYPE_USMALLINT:
H
Haojun Liao 已提交
1594
            *(uint16_t *)pData = *(uint16_t *)sVal.val;
C
Cary Xu 已提交
1595 1596 1597
            break;
          case TSDB_DATA_TYPE_INT:
          case TSDB_DATA_TYPE_UINT:
H
Haojun Liao 已提交
1598
            *(uint32_t *)pData = *(uint32_t *)sVal.val;
C
Cary Xu 已提交
1599 1600 1601
            break;
          case TSDB_DATA_TYPE_BIGINT:
          case TSDB_DATA_TYPE_UBIGINT:
H
Haojun Liao 已提交
1602
            *(uint64_t *)pData = *(uint64_t *)sVal.val;
C
Cary Xu 已提交
1603 1604
            break;
          case TSDB_DATA_TYPE_FLOAT:
H
Haojun Liao 已提交
1605
            SET_FLOAT_PTR(pData, sVal.val);
C
Cary Xu 已提交
1606 1607
            break;
          case TSDB_DATA_TYPE_DOUBLE:
H
Haojun Liao 已提交
1608
            SET_DOUBLE_PTR(pData, sVal.val);
C
Cary Xu 已提交
1609 1610
            break;
          case TSDB_DATA_TYPE_TIMESTAMP:
H
Haojun Liao 已提交
1611
            *(TSKEY*)pData = *(TSKEY*)sVal.val;
C
Cary Xu 已提交
1612 1613
            break;
          default:
H
Haojun Liao 已提交
1614 1615 1616
            memcpy(pData, sVal.val, pColInfo->info.bytes);
        }
      } else if (forceSetNull) {
H
Haojun Liao 已提交
1617
        colDataAppend(pColInfo, numOfRows, NULL, true);
1618 1619
      }
      i++;
C
Cary Xu 已提交
1620

1621
      if(row == row1) {
C
Cary Xu 已提交
1622
        j++;
1623 1624 1625 1626 1627
      } else {
        k++;
      }
    } else {
      if(forceSetNull) {
H
Haojun Liao 已提交
1628
        colDataAppend(pColInfo, numOfRows, NULL, true);
C
Cary Xu 已提交
1629
      }
1630
      i++;
1631
    }
1632
  }
1633

1634 1635
  if(forceSetNull) {
    while (i < numOfCols) { // the remain columns are all null data
1636
      SColumnInfoData* pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, i);
H
Haojun Liao 已提交
1637
      colDataAppend(pColInfo, numOfRows, NULL, true);
1638
      i++;
1639 1640
    }
  }
H
Haojun Liao 已提交
1641
#endif
1642
}
1643

1644 1645
static void moveDataToFront(STsdbReadHandle* pTsdbReadHandle, int32_t numOfRows, int32_t numOfCols) {
  if (numOfRows == 0 || ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
1646 1647 1648 1649
    return;
  }

  // if the buffer is not full in case of descending order query, move the data in the front of the buffer
1650 1651
  if (numOfRows < pTsdbReadHandle->outputCapacity) {
    int32_t emptySize = pTsdbReadHandle->outputCapacity - numOfRows;
1652
    for(int32_t i = 0; i < numOfCols; ++i) {
1653
      SColumnInfoData* pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, i);
S
TD-1057  
Shengliang Guan 已提交
1654
      memmove((char*)pColInfo->pData, (char*)pColInfo->pData + emptySize * pColInfo->info.bytes, numOfRows * pColInfo->info.bytes);
1655 1656 1657 1658
    }
  }
}

1659
static void getQualifiedRowsPos(STsdbReadHandle* pTsdbReadHandle, int32_t startPos, int32_t endPos, int32_t numOfExisted,
1660
                                int32_t* start, int32_t* end) {
1661 1662
  *start = -1;

1663
  if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
1664
    int32_t remain = endPos - startPos + 1;
1665 1666
    if (remain + numOfExisted > pTsdbReadHandle->outputCapacity) {
      *end = (pTsdbReadHandle->outputCapacity - numOfExisted) + startPos - 1;
H
Haojun Liao 已提交
1667 1668
    } else {
      *end = endPos;
1669 1670 1671 1672 1673
    }

    *start = startPos;
  } else {
    int32_t remain = (startPos - endPos) + 1;
1674 1675
    if (remain + numOfExisted > pTsdbReadHandle->outputCapacity) {
      *end = startPos + 1 - (pTsdbReadHandle->outputCapacity - numOfExisted);
H
Haojun Liao 已提交
1676 1677
    } else {
      *end = endPos;
1678 1679 1680 1681 1682 1683 1684
    }

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

1685 1686
static void updateInfoAfterMerge(STsdbReadHandle* pTsdbReadHandle, STableCheckInfo* pCheckInfo, int32_t numOfRows, int32_t endPos) {
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
1687 1688

  pCheckInfo->lastKey = cur->lastKey;
1689
  pTsdbReadHandle->realNumOfRows = numOfRows;
1690 1691 1692 1693
  cur->rows = numOfRows;
  cur->pos = endPos;
}

1694 1695
static void doCheckGeneratedBlockRange(STsdbReadHandle* pTsdbReadHandle) {
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
H
Haojun Liao 已提交
1696 1697

  if (cur->rows > 0) {
1698 1699
    if (ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
      assert(cur->win.skey >= pTsdbReadHandle->window.skey && cur->win.ekey <= pTsdbReadHandle->window.ekey);
H
Haojun Liao 已提交
1700
    } else {
1701
      assert(cur->win.skey >= pTsdbReadHandle->window.ekey && cur->win.ekey <= pTsdbReadHandle->window.skey);
H
Haojun Liao 已提交
1702 1703
    }

1704
    SColumnInfoData* pColInfoData = taosArrayGet(pTsdbReadHandle->pColumns, 0);
H
Haojun Liao 已提交
1705 1706
    assert(cur->win.skey == ((TSKEY*)pColInfoData->pData)[0] && cur->win.ekey == ((TSKEY*)pColInfoData->pData)[cur->rows-1]);
  } else {
1707
    cur->win = pTsdbReadHandle->window;
H
Haojun Liao 已提交
1708

1709 1710
    int32_t step = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? 1:-1;
    cur->lastKey = pTsdbReadHandle->window.ekey + step;
H
Haojun Liao 已提交
1711 1712 1713
  }
}

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

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

1720 1721
  int32_t step = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? 1:-1;
  int32_t numOfCols = (int32_t)(QH_GET_NUM_OF_COLS(pTsdbReadHandle));
H
Haojun Liao 已提交
1722 1723 1724 1725 1726 1727

  int32_t pos = cur->pos;

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

1728
  if (!ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
dengyihao's avatar
dengyihao 已提交
1729
    TSWAP(start, end, int32_t);
H
Haojun Liao 已提交
1730 1731
  }

1732 1733
  assert(pTsdbReadHandle->outputCapacity >= (end - start + 1));
  int32_t numOfRows = doCopyRowsFromFileBlock(pTsdbReadHandle, pTsdbReadHandle->outputCapacity, 0, start, end);
H
Haojun Liao 已提交
1734 1735 1736

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

  // if the buffer is not full in case of descending order query, move the data in the front of the buffer
1742
  moveDataToFront(pTsdbReadHandle, numOfRows, numOfCols);
H
Haojun Liao 已提交
1743 1744 1745

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

H
Haojun Liao 已提交
1749 1750
  tsdbDebug("%p uid:%" PRIu64", data block created, mixblock:%d, brange:%"PRIu64"-%"PRIu64" rows:%d, %s",
            pTsdbReadHandle, pCheckInfo->tableId, cur->mixBlock, cur->win.skey, cur->win.ekey, cur->rows, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
1751 1752
}

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

1758 1759
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
  SDataCols* pCols = pTsdbReadHandle->rhelper.pDCols[0];
H
Haojun Liao 已提交
1760

1761
  if (ASCENDING_TRAVERSE(pTsdbReadHandle->order) && pTsdbReadHandle->window.ekey >= pBlockInfo->window.ekey) {
H
Haojun Liao 已提交
1762 1763
    endPos = pBlockInfo->rows - 1;
    cur->mixBlock = (cur->pos != 0);
1764
  } else if (!ASCENDING_TRAVERSE(pTsdbReadHandle->order) && pTsdbReadHandle->window.ekey <= pBlockInfo->window.skey) {
H
Haojun Liao 已提交
1765 1766 1767 1768
    endPos = 0;
    cur->mixBlock = (cur->pos != pBlockInfo->rows - 1);
  } else {
    assert(pCols->numOfRows > 0);
1769
    endPos = doBinarySearchKey(pCols->cols[0].pData, pCols->numOfRows, pTsdbReadHandle->window.ekey, order);
H
Haojun Liao 已提交
1770 1771 1772 1773 1774 1775
    cur->mixBlock = true;
  }

  return endPos;
}

H
[td-32]  
hjxilinx 已提交
1776 1777
// 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
1778 1779 1780 1781
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 已提交
1782

1783
  initTableMemIterator(pTsdbReadHandle, pCheckInfo);
1784

1785 1786
  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 已提交
1787 1788
      cur->pos >= 0 && cur->pos < pBlock->numOfRows);

1789
  TSKEY* tsArray = pCols->cols[0].pData;
H
Haojun Liao 已提交
1790
  assert(pCols->numOfRows == pBlock->numOfRows && tsArray[0] == pBlock->keyFirst && tsArray[pBlock->numOfRows-1] == pBlock->keyLast);
1791 1792

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

1795 1796
  int32_t step = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? 1:-1;
  int32_t numOfCols = (int32_t)(QH_GET_NUM_OF_COLS(pTsdbReadHandle));
1797

H
Haojun Liao 已提交
1798
  STable* pTable = NULL;
1799
  int32_t endPos = getEndPosInDataBlock(pTsdbReadHandle, &blockInfo);
H
Haojun Liao 已提交
1800

1801
  tsdbDebug("%p uid:%" PRIu64" start merge data block, file block range:%"PRIu64"-%"PRIu64" rows:%d, start:%d,"
H
Haojun Liao 已提交
1802
            "end:%d, %s",
1803
            pTsdbReadHandle, pCheckInfo->tableId, blockInfo.window.skey, blockInfo.window.ekey,
H
Haojun Liao 已提交
1804
            blockInfo.rows, cur->pos, endPos, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
1805

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

1809 1810 1811 1812
  int16_t rv1 = -1;
  int16_t rv2 = -1;
  STSchema* pSchema1 = NULL;
  STSchema* pSchema2 = NULL;
D
fix bug  
dapan1121 已提交
1813

H
Haojun Liao 已提交
1814 1815
  int32_t pos = cur->pos;
  cur->win = TSWINDOW_INITIALIZER;
1816

1817 1818
  // no data in buffer, load data from file directly
  if (pCheckInfo->iiter == NULL && pCheckInfo->iter == NULL) {
1819
    copyAllRemainRowsFromFileBlock(pTsdbReadHandle, pCheckInfo, &blockInfo, endPos);
1820
    return;
1821
  } else if (pCheckInfo->iter != NULL || pCheckInfo->iiter != NULL) {
1822 1823
    SSkipListNode* node = NULL;
    do {
H
Haojun Liao 已提交
1824 1825
      STSRow* row2 = NULL;
      STSRow* row1 = getSRowInTableMem(pCheckInfo, pTsdbReadHandle->order, pCfg->update, &row2);
1826
      if (row1 == NULL) {
H
[td-32]  
hjxilinx 已提交
1827
        break;
1828
      }
1829

H
Haojun Liao 已提交
1830
      TSKEY key = TD_ROW_KEY(row1);
1831 1832
      if ((key > pTsdbReadHandle->window.ekey && ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
          (key < pTsdbReadHandle->window.ekey && !ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
1833 1834 1835
        break;
      }

1836 1837
      if (((pos > endPos || tsArray[pos] > pTsdbReadHandle->window.ekey) && ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
          ((pos < endPos || tsArray[pos] < pTsdbReadHandle->window.ekey) && !ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
1838 1839 1840
        break;
      }

1841 1842
      if ((key < tsArray[pos] && ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
          (key > tsArray[pos] && !ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
H
Haojun Liao 已提交
1843
        if (rv1 != TD_ROW_SVER(row1)) {
1844
//          pSchema1 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row1));
H
Haojun Liao 已提交
1845
          rv1 = TD_ROW_SVER(row1);
C
Cary Xu 已提交
1846
        }
H
Haojun Liao 已提交
1847
        if(row2 && rv2 != TD_ROW_SVER(row2)) {
1848
//          pSchema2 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row2));
H
Haojun Liao 已提交
1849
          rv2 = TD_ROW_SVER(row2);
1850 1851
        }
        
H
Haojun Liao 已提交
1852
        mergeTwoRowFromMem(pTsdbReadHandle, pTsdbReadHandle->outputCapacity, numOfRows, row1, row2, numOfCols, pCheckInfo->tableId, pSchema1, pSchema2, true);
1853 1854 1855 1856
        numOfRows += 1;
        if (cur->win.skey == TSKEY_INITIAL_VAL) {
          cur->win.skey = key;
        }
1857

1858
        cur->win.ekey = key;
1859 1860 1861
        cur->lastKey  = key + step;
        cur->mixBlock = true;

1862
        moveToNextRowInMem(pCheckInfo);
1863
      } else if (key == tsArray[pos]) {  // data in buffer has the same timestamp of data in file block, ignore it
H
TD-1439  
Hongze Cheng 已提交
1864
        if (pCfg->update) {
1865
          if(pCfg->update == TD_ROW_PARTIAL_UPDATE) {
1866
            doCopyRowsFromFileBlock(pTsdbReadHandle, pTsdbReadHandle->outputCapacity, numOfRows, pos, pos);
D
fix bug  
dapan1121 已提交
1867
          }
H
Haojun Liao 已提交
1868
          if (rv1 != TD_ROW_SVER(row1)) {
1869
//            pSchema1 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row1));
H
Haojun Liao 已提交
1870
            rv1 = TD_ROW_SVER(row1);
1871
          }
H
Haojun Liao 已提交
1872
          if(row2 && rv2 != TD_ROW_SVER(row2)) {
1873
//            pSchema2 = tsdbGetTableSchemaByVersion(pTable, memRowVersion(row2));
H
Haojun Liao 已提交
1874
            rv2 = TD_ROW_SVER(row2);
1875 1876 1877
          }
          
          bool forceSetNull = pCfg->update != TD_ROW_PARTIAL_UPDATE;
H
Haojun Liao 已提交
1878
          mergeTwoRowFromMem(pTsdbReadHandle, pTsdbReadHandle->outputCapacity, numOfRows, row1, row2, numOfCols, pCheckInfo->tableId, pSchema1, pSchema2, forceSetNull);
H
TD-1439  
Hongze Cheng 已提交
1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
          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);
        }
1893 1894
      } else if ((key > tsArray[pos] && ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
                  (key < tsArray[pos] && !ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
1895 1896 1897
        if (cur->win.skey == TSKEY_INITIAL_VAL) {
          cur->win.skey = tsArray[pos];
        }
1898

1899
        int32_t end = doBinarySearchKey(pCols->cols[0].pData, pCols->numOfRows, key, order);
1900 1901
        assert(end != -1);

H
Haojun Liao 已提交
1902
        if (tsArray[end] == key) { // the value of key in cache equals to the end timestamp value, ignore it
1903
          if (pCfg->update == TD_ROW_DISCARD_UPDATE) {
H
Hongze Cheng 已提交
1904 1905 1906 1907
            moveToNextRowInMem(pCheckInfo);
          } else {
            end -= step;
          }
H
Haojun Liao 已提交
1908
        }
1909

1910
        int32_t qstart = 0, qend = 0;
1911
        getQualifiedRowsPos(pTsdbReadHandle, pos, end, numOfRows, &qstart, &qend);
1912

1913
        numOfRows = doCopyRowsFromFileBlock(pTsdbReadHandle, pTsdbReadHandle->outputCapacity, numOfRows, qstart, qend);
1914 1915
        pos += (qend - qstart + 1) * step;

1916
        cur->win.ekey = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? tsArray[qend]:tsArray[qstart];
1917
        cur->lastKey  = cur->win.ekey + step;
1918
      }
1919
    } while (numOfRows < pTsdbReadHandle->outputCapacity);
H
Haojun Liao 已提交
1920

1921
    if (numOfRows < pTsdbReadHandle->outputCapacity) {
H
Haojun Liao 已提交
1922 1923 1924 1925
      /**
       * 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.
       */
1926
      if (node == NULL ||
H
Haojun Liao 已提交
1927
          ((TD_ROW_KEY((STSRow*)SL_GET_NODE_DATA(node)) > pTsdbReadHandle->window.ekey) &&
1928
           ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
H
Haojun Liao 已提交
1929
          ((TD_ROW_KEY((STSRow*)SL_GET_NODE_DATA(node)) < pTsdbReadHandle->window.ekey) &&
1930
           !ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
1931 1932 1933 1934 1935
        // 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];
        }

1936
        int32_t start = -1, end = -1;
1937
        getQualifiedRowsPos(pTsdbReadHandle, pos, endPos, numOfRows, &start, &end);
1938

1939
        numOfRows = doCopyRowsFromFileBlock(pTsdbReadHandle, pTsdbReadHandle->outputCapacity, numOfRows, start, end);
1940
        pos += (end - start + 1) * step;
1941

1942
        cur->win.ekey = ASCENDING_TRAVERSE(pTsdbReadHandle->order)? tsArray[end]:tsArray[start];
1943
        cur->lastKey  = cur->win.ekey + step;
H
Haojun Liao 已提交
1944
        cur->mixBlock = true;
1945
      }
1946 1947
    }
  }
H
Haojun Liao 已提交
1948 1949

  cur->blockCompleted =
1950 1951
      (((pos > endPos || cur->lastKey > pTsdbReadHandle->window.ekey) && ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
       ((pos < endPos || cur->lastKey < pTsdbReadHandle->window.ekey) && !ASCENDING_TRAVERSE(pTsdbReadHandle->order)));
1952

1953
  if (!ASCENDING_TRAVERSE(pTsdbReadHandle->order)) {
dengyihao's avatar
dengyihao 已提交
1954
    TSWAP(cur->win.skey, cur->win.ekey, TSKEY);
1955
  }
1956

1957 1958 1959
  moveDataToFront(pTsdbReadHandle, numOfRows, numOfCols);
  updateInfoAfterMerge(pTsdbReadHandle, pCheckInfo, numOfRows, pos);
  doCheckGeneratedBlockRange(pTsdbReadHandle);
H
Haojun Liao 已提交
1960

H
Haojun Liao 已提交
1961 1962
  tsdbDebug("%p uid:%" PRIu64", data block created, mixblock:%d, brange:%"PRIu64"-%"PRIu64" rows:%d, %s",
      pTsdbReadHandle, pCheckInfo->tableId, cur->mixBlock, cur->win.skey, cur->win.ekey, cur->rows, pTsdbReadHandle->idStr);
1963 1964
}

1965
int32_t binarySearchForKey(char* pValue, int num, TSKEY key, int order) {
H
[td-32]  
hjxilinx 已提交
1966
  int    firstPos, lastPos, midPos = -1;
H
Haojun Liao 已提交
1967
  int    numOfRows;
1968 1969
  TSKEY* keyList;

H
[td-32]  
hjxilinx 已提交
1970
  if (num <= 0) return -1;
1971 1972

  keyList = (TSKEY*)pValue;
H
[td-32]  
hjxilinx 已提交
1973 1974
  firstPos = 0;
  lastPos = num - 1;
1975

1976
  if (order == TSDB_ORDER_DESC) {
H
[td-32]  
hjxilinx 已提交
1977 1978 1979 1980 1981
    // 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;
1982

H
Haojun Liao 已提交
1983 1984
      numOfRows = lastPos - firstPos + 1;
      midPos = (numOfRows >> 1) + firstPos;
1985

H
[td-32]  
hjxilinx 已提交
1986 1987 1988 1989 1990 1991 1992 1993
      if (key < keyList[midPos]) {
        lastPos = midPos - 1;
      } else if (key > keyList[midPos]) {
        firstPos = midPos + 1;
      } else {
        break;
      }
    }
1994

H
[td-32]  
hjxilinx 已提交
1995 1996 1997 1998 1999
  } 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;
2000

H
[td-32]  
hjxilinx 已提交
2001 2002 2003 2004 2005 2006 2007
      if (key > keyList[lastPos]) {
        lastPos = lastPos + 1;
        if (lastPos >= num)
          return -1;
        else
          return lastPos;
      }
2008

H
Haojun Liao 已提交
2009 2010
      numOfRows = lastPos - firstPos + 1;
      midPos = (numOfRows >> 1) + firstPos;
2011

H
[td-32]  
hjxilinx 已提交
2012 2013 2014 2015 2016 2017 2018 2019 2020
      if (key < keyList[midPos]) {
        lastPos = midPos - 1;
      } else if (key > keyList[midPos]) {
        firstPos = midPos + 1;
      } else {
        break;
      }
    }
  }
2021

H
[td-32]  
hjxilinx 已提交
2022 2023 2024
  return midPos;
}

2025
static void cleanBlockOrderSupporter(SBlockOrderSupporter* pSupporter, int32_t numOfTables) {
S
TD-1848  
Shengliang Guan 已提交
2026 2027
  tfree(pSupporter->numOfBlocksPerTable);
  tfree(pSupporter->blockIndexArray);
2028 2029

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

S
TD-1848  
Shengliang Guan 已提交
2034
  tfree(pSupporter->pDataBlockInfo);
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
}

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

2046
  if (leftTableBlockIndex > pSupporter->numOfBlocksPerTable[leftTableIndex]) {
2047 2048
    /* left block is empty */
    return 1;
2049
  } else if (rightTableBlockIndex > pSupporter->numOfBlocksPerTable[rightTableIndex]) {
2050 2051 2052 2053 2054 2055 2056
    /* right block is empty */
    return -1;
  }

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

H
Haojun Liao 已提交
2057
  //    assert(pLeftBlockInfoEx->compBlock->offset != pRightBlockInfoEx->compBlock->offset);
2058
#if 0	// TODO: temporarily comment off requested by Dr. Liao
H
Haojun Liao 已提交
2059 2060
  if (pLeftBlockInfoEx->compBlock->offset == pRightBlockInfoEx->compBlock->offset &&
      pLeftBlockInfoEx->compBlock->last == pRightBlockInfoEx->compBlock->last) {
B
Bomin Zhang 已提交
2061
    tsdbError("error in header file, two block with same offset:%" PRId64, (int64_t)pLeftBlockInfoEx->compBlock->offset);
2062
  }
H
Haojun Liao 已提交
2063
#endif
2064

H
Haojun Liao 已提交
2065
  return pLeftBlockInfoEx->compBlock->offset > pRightBlockInfoEx->compBlock->offset ? 1 : -1;
2066 2067
}

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

2071 2072 2073
  if (pTsdbReadHandle->allocSize < size) {
    pTsdbReadHandle->allocSize = (int32_t)size;
    char* tmp = realloc(pTsdbReadHandle->pDataBlockInfo, pTsdbReadHandle->allocSize);
H
Haojun Liao 已提交
2074 2075 2076 2077
    if (tmp == NULL) {
      return TSDB_CODE_TDB_OUT_OF_MEMORY;
    }

2078
    pTsdbReadHandle->pDataBlockInfo = (STableBlockInfo*) tmp;
2079 2080
  }

2081
  memset(pTsdbReadHandle->pDataBlockInfo, 0, size);
2082 2083
  *numOfAllocBlocks = numOfBlocks;

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

2087 2088
  SBlockOrderSupporter sup = {0};
  sup.numOfTables = numOfTables;
2089
  sup.numOfBlocksPerTable = calloc(1, sizeof(int32_t) * numOfTables);
2090 2091 2092
  sup.blockIndexArray = calloc(1, sizeof(int32_t) * numOfTables);
  sup.pDataBlockInfo = calloc(1, POINTER_BYTES * numOfTables);

2093
  if (sup.numOfBlocksPerTable == NULL || sup.blockIndexArray == NULL || sup.pDataBlockInfo == NULL) {
2094
    cleanBlockOrderSupporter(&sup, 0);
2095
    return TSDB_CODE_TDB_OUT_OF_MEMORY;
2096
  }
H
Haojun Liao 已提交
2097

2098
  int32_t cnt = 0;
2099
  int32_t numOfQualTables = 0;
H
Haojun Liao 已提交
2100

2101
  for (int32_t j = 0; j < numOfTables; ++j) {
2102
    STableCheckInfo* pTableCheck = (STableCheckInfo*)taosArrayGet(pTsdbReadHandle->pTableCheckInfo, j);
2103 2104 2105
    if (pTableCheck->numOfBlocks <= 0) {
      continue;
    }
H
Haojun Liao 已提交
2106

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

H
Haojun Liao 已提交
2110
    char* buf = malloc(sizeof(STableBlockInfo) * pTableCheck->numOfBlocks);
2111
    if (buf == NULL) {
2112
      cleanBlockOrderSupporter(&sup, numOfQualTables);
2113
      return TSDB_CODE_TDB_OUT_OF_MEMORY;
2114 2115
    }

2116
    sup.pDataBlockInfo[numOfQualTables] = (STableBlockInfo*)buf;
2117 2118

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

H
Haojun Liao 已提交
2121 2122
      pBlockInfo->compBlock = &pBlock[k];
      pBlockInfo->pTableCheckInfo = pTableCheck;
2123 2124 2125
      cnt++;
    }

2126
    numOfQualTables++;
2127 2128
  }

H
Haojun Liao 已提交
2129
  assert(numOfBlocks == cnt);
2130

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

H
Haojun Liao 已提交
2136 2137
    tsdbDebug("%p create data blocks info struct completed for 1 table, %d blocks not sorted %s", pTsdbReadHandle, cnt,
        pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
2138 2139
    return TSDB_CODE_SUCCESS;
  }
2140

H
Haojun Liao 已提交
2141 2142
  tsdbDebug("%p create data blocks info struct completed, %d blocks in %d tables %s", pTsdbReadHandle, cnt,
      numOfQualTables, pTsdbReadHandle->idStr);
2143

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

2147 2148
  SMultiwayMergeTreeInfo* pTree = NULL;
  uint8_t ret = tMergeTreeCreate(&pTree, sup.numOfTables, &sup, dataBlockOrderCompar);
2149 2150
  if (ret != TSDB_CODE_SUCCESS) {
    cleanBlockOrderSupporter(&sup, numOfTables);
2151
    return TSDB_CODE_TDB_OUT_OF_MEMORY;
2152 2153 2154 2155 2156
  }

  int32_t numOfTotal = 0;

  while (numOfTotal < cnt) {
2157
    int32_t pos = tMergeTreeGetChosenIndex(pTree);
2158 2159
    int32_t index = sup.blockIndexArray[pos]++;

H
Haojun Liao 已提交
2160
    STableBlockInfo* pBlocksInfo = sup.pDataBlockInfo[pos];
2161
    pTsdbReadHandle->pDataBlockInfo[numOfTotal++] = pBlocksInfo[index];
2162 2163

    // set data block index overflow, in order to disable the offset comparator
2164 2165
    if (sup.blockIndexArray[pos] >= sup.numOfBlocksPerTable[pos]) {
      sup.blockIndexArray[pos] = sup.numOfBlocksPerTable[pos] + 1;
2166
    }
2167

H
Haojun Liao 已提交
2168
    tMergeTreeAdjust(pTree, tMergeTreeGetAdjustIndex(pTree));
2169 2170 2171 2172 2173
  }

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

H
Haojun Liao 已提交
2178
  tsdbDebug("%p %d data blocks sort completed, %s", pTsdbReadHandle, cnt, pTsdbReadHandle->idStr);
2179 2180 2181 2182 2183 2184
  cleanBlockOrderSupporter(&sup, numOfTables);
  free(pTree);

  return TSDB_CODE_SUCCESS;
}

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

2187 2188 2189
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 已提交
2190 2191

  while(1) {
2192
    int32_t code = loadFileDataBlock(pTsdbReadHandle, pNext->compBlock, pNext->pTableCheckInfo, exists);
H
Haojun Liao 已提交
2193 2194 2195 2196
    if (code != TSDB_CODE_SUCCESS || *exists) {
      return code;
    }

2197 2198
    if ((cur->slot == pTsdbReadHandle->numOfBlocks - 1 && ASCENDING_TRAVERSE(pTsdbReadHandle->order)) ||
        (cur->slot == 0 && !ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
H
Haojun Liao 已提交
2199
      // all data blocks in current file has been checked already, try next file if exists
2200
      return getFirstFileDataBlock(pTsdbReadHandle, exists);
H
Haojun Liao 已提交
2201 2202 2203 2204
    } else {  // next block of the same file
      cur->slot += step;
      cur->mixBlock = false;
      cur->blockCompleted = false;
2205
      pNext = &pTsdbReadHandle->pDataBlockInfo[cur->slot];
H
Haojun Liao 已提交
2206 2207 2208 2209
    }
  }
}

2210 2211 2212
static int32_t getFirstFileDataBlock(STsdbReadHandle* pTsdbReadHandle, bool* exists) {
  pTsdbReadHandle->numOfBlocks = 0;
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
H
Haojun Liao 已提交
2213 2214 2215

  int32_t code = TSDB_CODE_SUCCESS;

2216
  int32_t numOfBlocks = 0;
2217
  int32_t numOfTables = (int32_t)taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
2218

2219
  STsdbCfg* pCfg = &pTsdbReadHandle->pTsdb->config;
2220 2221
  STimeWindow win = TSWINDOW_INITIALIZER;

H
Hongze Cheng 已提交
2222
  while (true) {
2223
    tsdbRLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Hongze Cheng 已提交
2224

2225 2226
    if ((pTsdbReadHandle->pFileGroup = tsdbFSIterNext(&pTsdbReadHandle->fileIter)) == NULL) {
      tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Hongze Cheng 已提交
2227 2228 2229
      break;
    }

2230
    tsdbGetFidKeyRange(pCfg->daysPerFile, pCfg->precision, pTsdbReadHandle->pFileGroup->fid, &win.skey, &win.ekey);
2231 2232

    // current file are not overlapped with query time window, ignore remain files
2233 2234 2235
    if ((ASCENDING_TRAVERSE(pTsdbReadHandle->order) && win.skey > pTsdbReadHandle->window.ekey) ||
        (!ASCENDING_TRAVERSE(pTsdbReadHandle->order) && win.ekey < pTsdbReadHandle->window.ekey)) {
      tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Haojun Liao 已提交
2236 2237
      tsdbDebug("%p remain files are not qualified for qrange:%" PRId64 "-%" PRId64 ", ignore, %s", pTsdbReadHandle,
                pTsdbReadHandle->window.skey, pTsdbReadHandle->window.ekey, pTsdbReadHandle->idStr);
2238 2239
      pTsdbReadHandle->pFileGroup = NULL;
      assert(pTsdbReadHandle->numOfBlocks == 0);
2240 2241 2242
      break;
    }

2243 2244
    if (tsdbSetAndOpenReadFSet(&pTsdbReadHandle->rhelper, pTsdbReadHandle->pFileGroup) < 0) {
      tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Hongze Cheng 已提交
2245 2246 2247 2248
      code = terrno;
      break;
    }

2249
    tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Hongze Cheng 已提交
2250

2251
    if (tsdbLoadBlockIdx(&pTsdbReadHandle->rhelper) < 0) {
H
Hongze Cheng 已提交
2252 2253 2254 2255
      code = terrno;
      break;
    }

2256
    if ((code = getFileCompInfo(pTsdbReadHandle, &numOfBlocks)) != TSDB_CODE_SUCCESS) {
2257 2258
      break;
    }
H
Haojun Liao 已提交
2259

H
Haojun Liao 已提交
2260 2261
    tsdbDebug("%p %d blocks found in file for %d table(s), fid:%d, %s", pTsdbReadHandle, numOfBlocks, numOfTables,
              pTsdbReadHandle->pFileGroup->fid, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
2262

2263 2264 2265 2266
    assert(numOfBlocks >= 0);
    if (numOfBlocks == 0) {
      continue;
    }
H
Haojun Liao 已提交
2267

2268
    // todo return error code to query engine
2269
    if ((code = createDataBlocksInfo(pTsdbReadHandle, numOfBlocks, &pTsdbReadHandle->numOfBlocks)) != TSDB_CODE_SUCCESS) {
2270 2271
      break;
    }
H
Haojun Liao 已提交
2272

2273 2274
    assert(numOfBlocks >= pTsdbReadHandle->numOfBlocks);
    if (pTsdbReadHandle->numOfBlocks > 0) {
2275 2276 2277
      break;
    }
  }
H
Haojun Liao 已提交
2278

2279
  // no data in file anymore
2280
  if (pTsdbReadHandle->numOfBlocks <= 0 || code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2281
    if (code == TSDB_CODE_SUCCESS) {
2282
      assert(pTsdbReadHandle->pFileGroup == NULL);
H
Haojun Liao 已提交
2283 2284
    }

D
dapan1121 已提交
2285
    cur->fid = INT32_MIN;  // denote that there are no data in file anymore
H
Haojun Liao 已提交
2286 2287
    *exists = false;
    return code;
2288
  }
H
Haojun Liao 已提交
2289

2290 2291 2292
  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 已提交
2293

2294 2295
  STableBlockInfo* pBlockInfo = &pTsdbReadHandle->pDataBlockInfo[cur->slot];
  return getDataBlockRv(pTsdbReadHandle, pBlockInfo, exists);
H
Haojun Liao 已提交
2296 2297 2298 2299 2300 2301 2302
}

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

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

2306 2307
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
  assert(cur->slot < pTsdbReadHandle->numOfBlocks && cur->slot >= 0);
H
Haojun Liao 已提交
2308 2309 2310 2311

  cur->slot += step;
  cur->mixBlock       = false;
  cur->blockCompleted = false;
2312
}
2313
#if 0
H
Haojun Liao 已提交
2314
int32_t tsdbGetFileBlocksDistInfo(tsdbReaderT* queryHandle, STableBlockDist* pTableBlockInfo) {
2315
  STsdbReadHandle* pTsdbReadHandle = (STsdbReadHandle*) queryHandle;
H
Haojun Liao 已提交
2316

H
Haojun Liao 已提交
2317
  pTableBlockInfo->totalSize = 0;
2318
  pTableBlockInfo->totalRows = 0;
2319
  STsdbFS* pFileHandle = REPO_FS(pTsdbReadHandle->pTsdb);
H
Haojun Liao 已提交
2320 2321

  // find the start data block in file
2322 2323 2324
  pTsdbReadHandle->locateStart = true;
  STsdbCfg* pCfg = &pTsdbReadHandle->pTsdb->config;
  int32_t   fid = getFileIdFromKey(pTsdbReadHandle->window.skey, pCfg->daysPerFile, pCfg->precision);
H
Haojun Liao 已提交
2325 2326

  tsdbRLockFS(pFileHandle);
2327 2328
  tsdbFSIterInit(&pTsdbReadHandle->fileIter, pFileHandle, pTsdbReadHandle->order);
  tsdbFSIterSeek(&pTsdbReadHandle->fileIter, fid);
H
Haojun Liao 已提交
2329 2330
  tsdbUnLockFS(pFileHandle);

H
Haojun Liao 已提交
2331
  pTableBlockInfo->numOfFiles += 1;
H
Haojun Liao 已提交
2332

H
Haojun Liao 已提交
2333
  int32_t     code = TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2334
  int32_t     numOfBlocks = 0;
2335
  int32_t     numOfTables = (int32_t)taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
2336
  int         defaultRows = TSDB_DEFAULT_BLOCK_ROWS(pCfg->maxRowsPerFileBlock);
H
Haojun Liao 已提交
2337 2338 2339 2340
  STimeWindow win = TSWINDOW_INITIALIZER;

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

2343 2344
    if ((pTsdbReadHandle->pFileGroup = tsdbFSIterNext(&pTsdbReadHandle->fileIter)) == NULL) {
      tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Haojun Liao 已提交
2345 2346 2347
      break;
    }

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

    // current file are not overlapped with query time window, ignore remain files
2351 2352 2353
    if ((ASCENDING_TRAVERSE(pTsdbReadHandle->order) && win.skey > pTsdbReadHandle->window.ekey) ||
    (!ASCENDING_TRAVERSE(pTsdbReadHandle->order) && win.ekey < pTsdbReadHandle->window.ekey)) {
      tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Haojun Liao 已提交
2354 2355
      tsdbDebug("%p remain files are not qualified for qrange:%" PRId64 "-%" PRId64 ", ignore, %s", pTsdbReadHandle,
                pTsdbReadHandle->window.skey, pTsdbReadHandle->window.ekey, pTsdbReadHandle->idStr);
2356
      pTsdbReadHandle->pFileGroup = NULL;
H
Haojun Liao 已提交
2357 2358 2359
      break;
    }

H
Haojun Liao 已提交
2360
    pTableBlockInfo->numOfFiles += 1;
2361 2362
    if (tsdbSetAndOpenReadFSet(&pTsdbReadHandle->rhelper, pTsdbReadHandle->pFileGroup) < 0) {
      tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Haojun Liao 已提交
2363 2364 2365 2366
      code = terrno;
      break;
    }

2367
    tsdbUnLockFS(REPO_FS(pTsdbReadHandle->pTsdb));
H
Haojun Liao 已提交
2368

2369
    if (tsdbLoadBlockIdx(&pTsdbReadHandle->rhelper) < 0) {
H
Haojun Liao 已提交
2370 2371 2372 2373
      code = terrno;
      break;
    }

2374
    if ((code = getFileCompInfo(pTsdbReadHandle, &numOfBlocks)) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2375 2376 2377
      break;
    }

H
Haojun Liao 已提交
2378 2379
    tsdbDebug("%p %d blocks found in file for %d table(s), fid:%d, %s", pTsdbReadHandle, numOfBlocks, numOfTables,
              pTsdbReadHandle->pFileGroup->fid, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
2380 2381 2382 2383 2384 2385

    if (numOfBlocks == 0) {
      continue;
    }

    for (int32_t i = 0; i < numOfTables; ++i) {
2386
      STableCheckInfo* pCheckInfo = taosArrayGet(pTsdbReadHandle->pTableCheckInfo, i);
H
Haojun Liao 已提交
2387 2388 2389

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

H
Haojun Liao 已提交
2392
        int32_t numOfRows = pBlock[j].numOfRows;
2393 2394 2395
        pTableBlockInfo->totalRows += numOfRows;
        if (numOfRows > pTableBlockInfo->maxRows) pTableBlockInfo->maxRows = numOfRows;
        if (numOfRows < pTableBlockInfo->minRows) pTableBlockInfo->minRows = numOfRows;
2396
        if (numOfRows < defaultRows) pTableBlockInfo->numOfSmallBlocks+=1;
2397 2398 2399
        int32_t  stepIndex = (numOfRows-1)/TSDB_BLOCK_DIST_STEP_ROWS;
        SFileBlockInfo *blockInfo = (SFileBlockInfo*)taosArrayGet(pTableBlockInfo->dataBlockInfos, stepIndex);
        blockInfo->numBlocksOfStep++;
H
Haojun Liao 已提交
2400 2401 2402 2403 2404 2405
      }
    }
  }

  return code;
}
2406
#endif
H
Haojun Liao 已提交
2407

2408 2409 2410
static int32_t getDataBlocksInFiles(STsdbReadHandle* pTsdbReadHandle, bool* exists) {
  STsdbFS*       pFileHandle = REPO_FS(pTsdbReadHandle->pTsdb);
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
2411 2412

  // find the start data block in file
2413 2414 2415 2416
  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 已提交
2417

H
Hongze Cheng 已提交
2418
    tsdbRLockFS(pFileHandle);
2419 2420
    tsdbFSIterInit(&pTsdbReadHandle->fileIter, pFileHandle, pTsdbReadHandle->order);
    tsdbFSIterSeek(&pTsdbReadHandle->fileIter, fid);
H
Hongze Cheng 已提交
2421
    tsdbUnLockFS(pFileHandle);
2422

2423
    return getFirstFileDataBlock(pTsdbReadHandle, exists);
2424
  } else {
2425
    // check if current file block is all consumed
2426
    STableBlockInfo* pBlockInfo = &pTsdbReadHandle->pDataBlockInfo[cur->slot];
2427
    STableCheckInfo* pCheckInfo = pBlockInfo->pTableCheckInfo;
H
Haojun Liao 已提交
2428

2429
    // current block is done, try next
H
Haojun Liao 已提交
2430
    if ((!cur->mixBlock) || cur->blockCompleted) {
H
Haojun Liao 已提交
2431
      // all data blocks in current file has been checked already, try next file if exists
2432
    } else {
H
Haojun Liao 已提交
2433 2434
      tsdbDebug("%p continue in current data block, index:%d, pos:%d, %s", pTsdbReadHandle, cur->slot, cur->pos,
                pTsdbReadHandle->idStr);
2435 2436
      int32_t code = handleDataMergeIfNeeded(pTsdbReadHandle, pBlockInfo->compBlock, pCheckInfo);
      *exists = (pTsdbReadHandle->realNumOfRows > 0);
H
Haojun Liao 已提交
2437

H
Haojun Liao 已提交
2438 2439 2440 2441 2442 2443 2444
      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
2445 2446
    if (isEndFileDataBlock(cur, pTsdbReadHandle->numOfBlocks, ASCENDING_TRAVERSE(pTsdbReadHandle->order))) {
      return getFirstFileDataBlock(pTsdbReadHandle, exists);
H
Haojun Liao 已提交
2447
    } else {
2448 2449 2450
      moveToNextDataBlockInCurrentFile(pTsdbReadHandle);
      STableBlockInfo* pNext = &pTsdbReadHandle->pDataBlockInfo[cur->slot];
      return getDataBlockRv(pTsdbReadHandle, pNext, exists);
2451 2452
    }
  }
2453 2454
}

2455 2456
static bool doHasDataInBuffer(STsdbReadHandle* pTsdbReadHandle) {
  size_t numOfTables = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
2457
  
2458 2459
  while (pTsdbReadHandle->activeIndex < numOfTables) {
    if (hasMoreDataInCache(pTsdbReadHandle)) {
2460 2461
      return true;
    }
H
Haojun Liao 已提交
2462

2463
    pTsdbReadHandle->activeIndex += 1;
2464
  }
H
Haojun Liao 已提交
2465

2466 2467 2468
  return false;
}

2469
//todo not unref yet, since it is not support multi-group interpolation query
H
Haojun Liao 已提交
2470
static UNUSED_FUNC void changeQueryHandleForInterpQuery(tsdbReaderT pHandle) {
H
Haojun Liao 已提交
2471
  // filter the queried time stamp in the first place
2472
  STsdbReadHandle* pTsdbReadHandle = (STsdbReadHandle*) pHandle;
H
Haojun Liao 已提交
2473 2474

  // starts from the buffer in case of descending timestamp order check data blocks
2475
  size_t numOfTables = taosArrayGetSize(pTsdbReadHandle->pTableCheckInfo);
H
Haojun Liao 已提交
2476 2477 2478

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

    // the first qualified table for interpolation query
2482 2483 2484 2485
//    if ((pTsdbReadHandle->window.skey <= pCheckInfo->pTableObj->lastKey) &&
//        (pCheckInfo->pTableObj->lastKey != TSKEY_INITIAL_VAL)) {
//      break;
//    }
H
Haojun Liao 已提交
2486 2487 2488 2489 2490 2491 2492 2493 2494

    i++;
  }

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

2495 2496
  STableCheckInfo info = *(STableCheckInfo*) taosArrayGet(pTsdbReadHandle->pTableCheckInfo, i);
  taosArrayClear(pTsdbReadHandle->pTableCheckInfo);
H
Haojun Liao 已提交
2497

2498 2499
  info.lastKey = pTsdbReadHandle->window.skey;
  taosArrayPush(pTsdbReadHandle->pTableCheckInfo, &info);
H
Haojun Liao 已提交
2500 2501 2502
}

static int tsdbReadRowsFromCache(STableCheckInfo* pCheckInfo, TSKEY maxKey, int maxRowsToRead, STimeWindow* win,
2503
                                 STsdbReadHandle* pTsdbReadHandle) {
H
Haojun Liao 已提交
2504
  int     numOfRows = 0;
2505 2506
  int32_t numOfCols = (int32_t)taosArrayGetSize(pTsdbReadHandle->pColumns);
  STsdbCfg* pCfg = &pTsdbReadHandle->pTsdb->config;
H
Haojun Liao 已提交
2507 2508 2509
  win->skey = TSKEY_INITIAL_VAL;

  int64_t st = taosGetTimestampUs();
D
fix bug  
dapan1121 已提交
2510 2511
  int16_t rv = -1;
  STSchema* pSchema = NULL;
H
Haojun Liao 已提交
2512 2513

  do {
H
Haojun Liao 已提交
2514
    STSRow* row = getSRowInTableMem(pCheckInfo, pTsdbReadHandle->order, pCfg->update, NULL);
H
Haojun Liao 已提交
2515 2516 2517 2518
    if (row == NULL) {
      break;
    }

H
Haojun Liao 已提交
2519
    TSKEY key = TD_ROW_KEY(row);
2520 2521 2522
    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 已提交
2523 2524 2525 2526 2527 2528 2529 2530 2531

      break;
    }

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

    win->ekey = key;
H
Haojun Liao 已提交
2532
    if (rv != TD_ROW_SVER(row)) {
2533
      pSchema = metaGetTbTSchema(pTsdbReadHandle->pTsdb->pMeta, pCheckInfo->tableId, 0);
H
Haojun Liao 已提交
2534
      rv = TD_ROW_SVER(row);
D
fix bug  
dapan1121 已提交
2535
    }
2536
    mergeTwoRowFromMem(pTsdbReadHandle, maxRowsToRead, numOfRows, row, NULL, numOfCols, pCheckInfo->tableId, pSchema, NULL, true);
H
Haojun Liao 已提交
2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547

    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
2548
  if (!ASCENDING_TRAVERSE(pTsdbReadHandle->order) && numOfRows < maxRowsToRead) {
H
Haojun Liao 已提交
2549 2550 2551
    int32_t emptySize = maxRowsToRead - numOfRows;

    for(int32_t i = 0; i < numOfCols; ++i) {
2552
      SColumnInfoData* pColInfo = taosArrayGet(pTsdbReadHandle->pColumns, i);
H
Haojun Liao 已提交
2553 2554 2555 2556 2557
      memmove((char*)pColInfo->pData, (char*)pColInfo->pData + emptySize * pColInfo->info.bytes, numOfRows * pColInfo->info.bytes);
    }
  }

  int64_t elapsedTime = taosGetTimestampUs() - st;
H
Haojun Liao 已提交
2558 2559
  tsdbDebug("%p build data block from cache completed, elapsed time:%"PRId64" us, numOfRows:%d, numOfCols:%d, %s", pTsdbReadHandle,
            elapsedTime, numOfRows, numOfCols, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
2560 2561 2562 2563

  return numOfRows;
}

2564 2565
static int32_t getAllTableList(SMeta* pMeta, uint64_t uid, SArray* list) {
  SMCtbCursor* pCur = metaOpenCtbCursor(pMeta, uid);
H
Haojun Liao 已提交
2566

2567 2568 2569 2570 2571
  while (1) {
    tb_uid_t id = metaCtbCursorNext(pCur);
    if (id == 0) {
      break;
    }
H
Haojun Liao 已提交
2572

2573
    STableKeyInfo info = {.lastKey = TSKEY_INITIAL_VAL, uid = id};
H
Haojun Liao 已提交
2574 2575 2576
    taosArrayPush(list, &info);
  }

2577
  metaCloseCtbCurosr(pCur);
H
Haojun Liao 已提交
2578 2579 2580 2581 2582 2583 2584 2585
  return TSDB_CODE_SUCCESS;
}

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

2586 2587 2588 2589 2590 2591
//  tQueryInfo* pInfo = (tQueryInfo*)param;
//  if (pInfo->optr != TSDB_RELATION_IN) {
//    tfree(pInfo->q);
//  } else {
//    taosHashCleanup((SHashObj *)(pInfo->q));
//  }
H
Haojun Liao 已提交
2592 2593 2594 2595

  free(param);
}

2596 2597 2598 2599 2600
#define TSDB_PREV_ROW  0x1
#define TSDB_NEXT_ROW  0x2

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

2604
    int32_t code = getDataBlocksInFiles(pTsdbReadHandle, &exists);
H
Haojun Liao 已提交
2605
    if (code != TSDB_CODE_SUCCESS) {
2606
      pTsdbReadHandle->checkFiles = false;
H
Haojun Liao 已提交
2607 2608
      return false;
    }
H
Haojun Liao 已提交
2609

H
Haojun Liao 已提交
2610
    if (exists) {
H
Haojun Liao 已提交
2611
      tsdbRetrieveDataBlock((tsdbReaderT*) pTsdbReadHandle, NULL);
2612 2613 2614
      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 已提交
2615 2616
      }

2617
      pTsdbReadHandle->currentLoadExternalRows = false; // clear the flag, since the exact matched row is found.
H
Haojun Liao 已提交
2618 2619
      return exists;
    }
H
Haojun Liao 已提交
2620

2621
    pTsdbReadHandle->checkFiles = false;
H
Haojun Liao 已提交
2622
  }
H
Haojun Liao 已提交
2623

2624 2625
  if (hasMoreDataInCache(pTsdbReadHandle)) {
    pTsdbReadHandle->currentLoadExternalRows = false;
H
Haojun Liao 已提交
2626 2627
    return true;
  }
H
Haojun Liao 已提交
2628

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

2633 2634
//    doGetExternalRow(pTsdbReadHandle, TSDB_PREV_ROW, pMemRef);
//    doGetExternalRow(pTsdbReadHandle, TSDB_NEXT_ROW, pMemRef);
H
Haojun Liao 已提交
2635

2636
    bool result = tsdbGetExternalRow(pTsdbReadHandle);
H
Haojun Liao 已提交
2637

2638 2639 2640
//    pTsdbReadHandle->prev = doFreeColumnInfoData(pTsdbReadHandle->prev);
//    pTsdbReadHandle->next = doFreeColumnInfoData(pTsdbReadHandle->next);
    pTsdbReadHandle->currentLoadExternalRows = false;
H
Haojun Liao 已提交
2641 2642

    return result;
2643
  }
H
Haojun Liao 已提交
2644

H
Haojun Liao 已提交
2645 2646
  return false;
}
2647

2648
static bool loadCachedLastRow(STsdbReadHandle* pTsdbReadHandle) {
H
Haojun Liao 已提交
2649
  // the last row is cached in buffer, return it directly.
2650 2651 2652
  // 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 已提交
2653 2654
  assert(numOfTables > 0 && numOfCols > 0);

2655
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
2656

H
Haojun Liao 已提交
2657
  STSRow*  pRow = NULL;
H
Haojun Liao 已提交
2658
  TSKEY    key  = TSKEY_INITIAL_VAL;
2659 2660 2661 2662 2663 2664 2665 2666
  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;
//    }
H
Haojun Liao 已提交
2667
    mergeTwoRowFromMem(pTsdbReadHandle, pTsdbReadHandle->outputCapacity, 0, pRow, NULL, numOfCols, pCheckInfo->tableId, NULL, NULL, true);
H
Haojun Liao 已提交
2668
    tfree(pRow);
H
Haojun Liao 已提交
2669

H
Haojun Liao 已提交
2670 2671 2672 2673 2674 2675 2676 2677 2678 2679
    // 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;
2680
  }
H
Haojun Liao 已提交
2681

H
Haojun Liao 已提交
2682 2683 2684
  return false;
}

D
init  
dapan1121 已提交
2685

D
update  
dapan1121 已提交
2686

2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 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
//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 已提交
2839 2840 2841
  assert(numOfTables > 0);

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

2843 2844
  while(pTsdbReadHandle->activeIndex < numOfTables) {
    if (loadBlockOfActiveTable(pTsdbReadHandle)) {
H
Haojun Liao 已提交
2845 2846 2847
      return true;
    }

2848
    STableCheckInfo* pCheckInfo = taosArrayGet(pTsdbReadHandle->pTableCheckInfo, pTsdbReadHandle->activeIndex);
H
Haojun Liao 已提交
2849 2850
    pCheckInfo->numOfBlocks = 0;

2851 2852 2853 2854 2855
    pTsdbReadHandle->activeIndex += 1;
    pTsdbReadHandle->locateStart = false;
    pTsdbReadHandle->checkFiles  = true;
    pTsdbReadHandle->cur.rows    = 0;
    pTsdbReadHandle->currentLoadExternalRows = pTsdbReadHandle->loadExternalRow;
H
Haojun Liao 已提交
2856 2857 2858 2859

    terrno = TSDB_CODE_SUCCESS;

    int64_t elapsedTime = taosGetTimestampUs() - stime;
2860
    pTsdbReadHandle->cost.checkForNextTime += elapsedTime;
H
Haojun Liao 已提交
2861 2862 2863
  }

  return false;
2864 2865
}

H
Haojun Liao 已提交
2866
// handle data in cache situation
H
Haojun Liao 已提交
2867
bool tsdbNextDataBlock(tsdbReaderT pHandle) {
2868
  STsdbReadHandle* pTsdbReadHandle = (STsdbReadHandle*) pHandle;
Y
yihaoDeng 已提交
2869

2870
  if (emptyQueryTimewindow(pTsdbReadHandle)) {
H
Haojun Liao 已提交
2871
    tsdbDebug("%p query window not overlaps with the data set, no result returned, %s", pTsdbReadHandle, pTsdbReadHandle->idStr);
2872 2873 2874
    return false;
  }

Y
yihaoDeng 已提交
2875 2876 2877
  int64_t stime = taosGetTimestampUs();
  int64_t elapsedTime = stime;

2878
  // TODO refactor: remove "type"
2879 2880 2881 2882 2883
  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 已提交
2884
    }
H
Haojun Liao 已提交
2885
  }
Y
yihaoDeng 已提交
2886

2887 2888
  if (pTsdbReadHandle->loadType == BLOCK_LOAD_TABLE_SEQ_ORDER) {
    return loadDataBlockFromTableSeq(pTsdbReadHandle);
H
Haojun Liao 已提交
2889
  } else { // loadType == RR and Offset Order
2890
    if (pTsdbReadHandle->checkFiles) {
H
Haojun Liao 已提交
2891 2892 2893
      // check if the query range overlaps with the file data block
      bool exists = true;

2894
      int32_t code = getDataBlocksInFiles(pTsdbReadHandle, &exists);
H
Haojun Liao 已提交
2895
      if (code != TSDB_CODE_SUCCESS) {
2896 2897
        pTsdbReadHandle->activeIndex = 0;
        pTsdbReadHandle->checkFiles = false;
H
Haojun Liao 已提交
2898 2899 2900 2901 2902

        return false;
      }

      if (exists) {
2903
        pTsdbReadHandle->cost.checkForNextTime += (taosGetTimestampUs() - stime);
H
Haojun Liao 已提交
2904 2905
        return exists;
      }
Y
yihaoDeng 已提交
2906

2907 2908
      pTsdbReadHandle->activeIndex = 0;
      pTsdbReadHandle->checkFiles = false;
Y
yihaoDeng 已提交
2909 2910
    }

H
Haojun Liao 已提交
2911
    // TODO: opt by consider the scan order
2912
    bool ret = doHasDataInBuffer(pTsdbReadHandle);
H
Haojun Liao 已提交
2913
    terrno = TSDB_CODE_SUCCESS;
Y
yihaoDeng 已提交
2914

H
Haojun Liao 已提交
2915
    elapsedTime = taosGetTimestampUs() - stime;
2916
    pTsdbReadHandle->cost.checkForNextTime += elapsedTime;
H
Haojun Liao 已提交
2917
    return ret;
Y
yihaoDeng 已提交
2918 2919
  }
}
2920

2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985
//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));
//  }
//
H
Haojun Liao 已提交
2986
//  pSecQueryHandle = tsdbQueryTablesImpl(pTsdbReadHandle->pTsdb, &cond, pTsdbReadHandle->idStr, pMemRef);
2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 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
//  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:
3027
//  tsdbCleanupReadHandle(pSecQueryHandle);
3028 3029 3030
//  return terrno;
//}

H
Haojun Liao 已提交
3031
bool tsdbGetExternalRow(tsdbReaderT pHandle) {
3032 3033
  STsdbReadHandle* pTsdbReadHandle = (STsdbReadHandle*) pHandle;
  SQueryFilePos* cur = &pTsdbReadHandle->cur;
H
Haojun Liao 已提交
3034

H
Haojun Liao 已提交
3035 3036
  cur->fid = INT32_MIN;
  cur->mixBlock = true;
3037
  if (pTsdbReadHandle->prev == NULL || pTsdbReadHandle->next == NULL) {
H
Haojun Liao 已提交
3038 3039
    cur->rows = 0;
    return false;
H
Haojun Liao 已提交
3040 3041
  }

3042
  int32_t numOfCols = (int32_t) QH_GET_NUM_OF_COLS(pTsdbReadHandle);
H
Haojun Liao 已提交
3043
  for (int32_t i = 0; i < numOfCols; ++i) {
3044 3045
    SColumnInfoData* pColInfoData = taosArrayGet(pTsdbReadHandle->pColumns, i);
    SColumnInfoData* first = taosArrayGet(pTsdbReadHandle->prev, i);
H
Haojun Liao 已提交
3046 3047 3048

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

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

    if (i == 0 && pColInfoData->info.type == TSDB_DATA_TYPE_TIMESTAMP) {
H
Haojun Liao 已提交
3053
      cur->win.skey = *(TSKEY*)pColInfoData->pData;
sangshuduo's avatar
sangshuduo 已提交
3054
      cur->win.ekey = *(TSKEY*)(((char*)pColInfoData->pData) + TSDB_KEYSIZE);
H
Haojun Liao 已提交
3055 3056 3057
    }
  }

H
Haojun Liao 已提交
3058 3059
  cur->rows = 2;
  return true;
3060 3061
}

3062
/*
3063
 * if lastRow == NULL, return TSDB_CODE_TDB_NO_CACHE_LAST_ROW
3064
 * else set pRes and return TSDB_CODE_SUCCESS and save lastKey
3065
 */
H
Haojun Liao 已提交
3066
// int32_t tsdbGetCachedLastRow(STable* pTable, STSRow** pRes, TSKEY* lastKey) {
3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082
//  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;
//    }
//  }
//
H
Haojun Liao 已提交
3083
// out:
3084 3085 3086 3087
//  TSDB_RUNLOCK_TABLE(pTable);
//  return code;
//}

H
Haojun Liao 已提交
3088
bool isTsdbCacheLastRow(tsdbReaderT* pTsdbReadHandle) {
3089
  return ((STsdbReadHandle *)pTsdbReadHandle)->cachelastrow > TSDB_CACHED_TYPE_NONE;
D
fix bug  
dapan1121 已提交
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 3115 3116 3117 3118
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 已提交
3119

3120
  return TSDB_CODE_SUCCESS;
3121 3122
}

3123 3124
int32_t checkForCachedLast(STsdbReadHandle* pTsdbReadHandle) {
  assert(pTsdbReadHandle != NULL);
D
update  
dapan1121 已提交
3125 3126

  int32_t code = 0;
3127 3128 3129
//  if (pTsdbReadHandle->pTsdb && atomic_load_8(&pTsdbReadHandle->pTsdb->hasCachedLastColumn)){
//    pTsdbReadHandle->cachelastrow = TSDB_CACHED_TYPE_LAST;
//  }
D
update  
dapan1121 已提交
3130 3131

  // update the tsdb query time range
3132 3133 3134
  if (pTsdbReadHandle->cachelastrow) {
    pTsdbReadHandle->checkFiles  = false;
    pTsdbReadHandle->activeIndex = -1;  // start from -1
D
update  
dapan1121 已提交
3135 3136 3137 3138 3139 3140
  }

  return code;
}


3141
STimeWindow updateLastrowForEachGroup(STableGroupInfo *groupList) {
H
Haojun Liao 已提交
3142
  STimeWindow window = {INT64_MAX, INT64_MIN};
H
Haojun Liao 已提交
3143

H
Haojun Liao 已提交
3144
  int32_t totalNumOfTable = 0;
3145
  SArray* emptyGroup = taosArrayInit(16, sizeof(int32_t));
H
Haojun Liao 已提交
3146

H
Haojun Liao 已提交
3147 3148 3149 3150 3151
  // 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 已提交
3152

H
Haojun Liao 已提交
3153
    STableKeyInfo keyInfo = {0};
H
Haojun Liao 已提交
3154

H
Haojun Liao 已提交
3155 3156
    size_t numOfTables = taosArrayGetSize(pGroup);
    for(int32_t i = 0; i < numOfTables; ++i) {
3157
      STableKeyInfo* pInfo = (STableKeyInfo*) taosArrayGet(pGroup, i);
H
Haojun Liao 已提交
3158

H
Haojun Liao 已提交
3159
      // if the lastKey equals to INT64_MIN, there is no data in this table
3160
      TSKEY lastKey = 0;//((STable*)(pInfo->pTable))->lastKey;
H
Haojun Liao 已提交
3161 3162
      if (key < lastKey) {
        key = lastKey;
H
Haojun Liao 已提交
3163

3164
//        keyInfo.pTable  = pInfo->pTable;
H
Haojun Liao 已提交
3165
        keyInfo.lastKey = key;
3166
        pInfo->lastKey  = key;
H
Haojun Liao 已提交
3167

H
Haojun Liao 已提交
3168 3169 3170
        if (key < window.skey) {
          window.skey = key;
        }
3171

H
Haojun Liao 已提交
3172 3173 3174 3175
        if (key > window.ekey) {
          window.ekey = key;
        }
      }
3176
    }
H
Haojun Liao 已提交
3177

H
Haojun Liao 已提交
3178
    // more than one table in each group, only one table left for each group
3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190
//    if (keyInfo.pTable != NULL) {
//      totalNumOfTable++;
//      if (taosArrayGetSize(pGroup) == 1) {
//        // do nothing
//      } else {
//        taosArrayClear(pGroup);
//        taosArrayPush(pGroup, &keyInfo);
//      }
//    } else {  // mark all the empty groups, and remove it later
//      taosArrayDestroy(pGroup);
//      taosArrayPush(emptyGroup, &j);
//    }
3191
  }
H
Haojun Liao 已提交
3192

H
Haojun Liao 已提交
3193 3194 3195
  // window does not being updated, so set the original
  if (window.skey == INT64_MAX && window.ekey == INT64_MIN) {
    window = TSWINDOW_INITIALIZER;
H
Haojun Liao 已提交
3196
    assert(totalNumOfTable == 0 && taosArrayGetSize(groupList->pGroupList) == numOfGroups);
H
Haojun Liao 已提交
3197 3198
  }

H
Haojun Liao 已提交
3199
  taosArrayRemoveBatch(groupList->pGroupList, TARRAY_GET_START(emptyGroup), (int32_t) taosArrayGetSize(emptyGroup));
3200 3201
  taosArrayDestroy(emptyGroup);

H
Haojun Liao 已提交
3202
  groupList->numOfTables = totalNumOfTable;
H
Haojun Liao 已提交
3203
  return window;
H
hjxilinx 已提交
3204 3205
}

H
Haojun Liao 已提交
3206
void tsdbRetrieveDataBlockInfo(tsdbReaderT* pTsdbReadHandle, SDataBlockInfo* pDataBlockInfo) {
3207
  STsdbReadHandle* pHandle = (STsdbReadHandle*)pTsdbReadHandle;
3208
  SQueryFilePos* cur = &pHandle->cur;
3209 3210

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

3212
  // there are data in file
D
dapan1121 已提交
3213
  if (pHandle->cur.fid != INT32_MIN) {
3214
    STableBlockInfo* pBlockInfo = &pHandle->pDataBlockInfo[cur->slot];
3215
    uid = pBlockInfo->pTableCheckInfo->tableId;
H
[td-32]  
hjxilinx 已提交
3216
  } else {
3217
    STableCheckInfo* pCheckInfo = taosArrayGet(pHandle->pTableCheckInfo, pHandle->activeIndex);
3218
    uid = pCheckInfo->tableId;
3219
  }
3220

3221 3222
  pDataBlockInfo->uid    = uid;
  pDataBlockInfo->rows   = cur->rows;
H
Haojun Liao 已提交
3223
  pDataBlockInfo->window = cur->win;
S
TD-1057  
Shengliang Guan 已提交
3224
  pDataBlockInfo->numOfCols = (int32_t)(QH_GET_NUM_OF_COLS(pHandle));
3225
}
H
hjxilinx 已提交
3226

H
Haojun Liao 已提交
3227 3228 3229
/*
 * return null for mixed data block, if not a complete file data block, the statistics value will always return NULL
 */
H
Haojun Liao 已提交
3230
int32_t tsdbRetrieveDataBlockStatisInfo(tsdbReaderT* pTsdbReadHandle, SDataStatis** pBlockStatis) {
3231
  STsdbReadHandle* pHandle = (STsdbReadHandle*) pTsdbReadHandle;
H
Haojun Liao 已提交
3232

H
Haojun Liao 已提交
3233 3234
  SQueryFilePos* c = &pHandle->cur;
  if (c->mixBlock) {
H
Haojun Liao 已提交
3235 3236 3237
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
  }
H
Haojun Liao 已提交
3238

H
Haojun Liao 已提交
3239 3240 3241 3242
  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 已提交
3243 3244 3245 3246
  if (pBlockInfo->compBlock->numOfSubBlocks > 1) {
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
  }
H
Haojun Liao 已提交
3247 3248

  int64_t stime = taosGetTimestampUs();
3249 3250
  int     statisStatus = tsdbLoadBlockStatis(&pHandle->rhelper, pBlockInfo->compBlock);
  if (statisStatus < TSDB_STATIS_OK) {
H
Hongze Cheng 已提交
3251
    return terrno;
3252 3253 3254
  } else if (statisStatus > TSDB_STATIS_OK) {
    *pBlockStatis = NULL;
    return TSDB_CODE_SUCCESS;
H
Hongze Cheng 已提交
3255
  }
H
Haojun Liao 已提交
3256

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

H
Haojun Liao 已提交
3259
  size_t numOfCols = QH_GET_NUM_OF_COLS(pHandle);
H
Haojun Liao 已提交
3260
  memset(pHandle->statis, 0, numOfCols * sizeof(SDataStatis));
3261
  for(int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
3262
    pHandle->statis[i].colId = colIds[i];
3263
  }
H
Haojun Liao 已提交
3264

3265
  tsdbGetBlockStatis(&pHandle->rhelper, pHandle->statis, (int)numOfCols, pBlockInfo->compBlock);
H
Haojun Liao 已提交
3266 3267 3268

  // always load the first primary timestamp column data
  SDataStatis* pPrimaryColStatis = &pHandle->statis[0];
3269
  assert(pPrimaryColStatis->colId == PRIMARYKEY_TIMESTAMP_COL_ID);
H
Haojun Liao 已提交
3270 3271 3272 3273 3274

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

H
Haojun Liao 已提交
3275
  //update the number of NULL data rows
H
Haojun Liao 已提交
3276
  for(int32_t i = 1; i < numOfCols; ++i) {
3277
    if (pHandle->statis[i].numOfNull == -1) { // set the column data are all NULL
H
Haojun Liao 已提交
3278 3279 3280
      pHandle->statis[i].numOfNull = pBlockInfo->compBlock->numOfRows;
    }
  }
H
Haojun Liao 已提交
3281 3282 3283 3284

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

H
Haojun Liao 已提交
3285
  *pBlockStatis = pHandle->statis;
3286
  return TSDB_CODE_SUCCESS;
H
hjxilinx 已提交
3287 3288
}

H
Haojun Liao 已提交
3289
SArray* tsdbRetrieveDataBlock(tsdbReaderT* pTsdbReadHandle, SArray* pIdList) {
H
[td-32]  
hjxilinx 已提交
3290
  /**
H
hjxilinx 已提交
3291
   * In the following two cases, the data has been loaded to SColumnInfoData.
H
[td-32]  
hjxilinx 已提交
3292 3293
   * 1. data is from cache, 2. data block is not completed qualified to query time range
   */
3294
  STsdbReadHandle* pHandle = (STsdbReadHandle*)pTsdbReadHandle;
3295

D
dapan1121 已提交
3296
  if (pHandle->cur.fid == INT32_MIN) {
H
[td-32]  
hjxilinx 已提交
3297 3298
    return pHandle->pColumns;
  } else {
H
Haojun Liao 已提交
3299 3300
    STableBlockInfo* pBlockInfo = &pHandle->pDataBlockInfo[pHandle->cur.slot];
    STableCheckInfo* pCheckInfo = pBlockInfo->pTableCheckInfo;
3301

3302
    if (pHandle->cur.mixBlock) {
H
[td-32]  
hjxilinx 已提交
3303 3304
      return pHandle->pColumns;
    } else {
H
Haojun Liao 已提交
3305
      SDataBlockInfo binfo = GET_FILE_DATA_BLOCK_INFO(pCheckInfo, pBlockInfo->compBlock);
3306
      assert(pHandle->realNumOfRows <= binfo.rows);
H
Haojun Liao 已提交
3307

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

H
Hongze Cheng 已提交
3311
      if (pBlockLoadInfo->slot == pHandle->cur.slot && pBlockLoadInfo->fileGroup->fid == pHandle->cur.fid &&
H
Haojun Liao 已提交
3312
          pBlockLoadInfo->uid == pCheckInfo->tableId) {
H
hjxilinx 已提交
3313
        return pHandle->pColumns;
H
Haojun Liao 已提交
3314
      } else {  // only load the file block
H
refact  
Hongze Cheng 已提交
3315
        SBlock* pBlock = pBlockInfo->compBlock;
H
Haojun Liao 已提交
3316
        if (doLoadFileDataBlock(pHandle, pBlock, pCheckInfo, pHandle->cur.slot) != TSDB_CODE_SUCCESS) {
3317 3318
          return NULL;
        }
H
Haojun Liao 已提交
3319

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

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

H
Haojun Liao 已提交
3328 3329
          for(int32_t i = 0; i < reqNumOfCols; ++i) {
            SColumnInfoData* pColInfo = taosArrayGet(pHandle->pColumns, i);
S
TD-1057  
Shengliang Guan 已提交
3330
            memmove((char*)pColInfo->pData, (char*)pColInfo->pData + emptySize * pColInfo->info.bytes, numOfRows * pColInfo->info.bytes);
H
Haojun Liao 已提交
3331 3332
          }
        }
H
Haojun Liao 已提交
3333

H
hjxilinx 已提交
3334 3335
        return pHandle->pColumns;
      }
H
[td-32]  
hjxilinx 已提交
3336 3337
    }
  }
H
hjxilinx 已提交
3338
}
3339
#if 0
3340
void filterPrepare(void* expr, void* param) {
3341
  tExprNode* pExpr = (tExprNode*)expr;
H
[td-32]  
hjxilinx 已提交
3342
  if (pExpr->_node.info != NULL) {
3343 3344
    return;
  }
3345

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

3348
  STSchema*   pTSSchema = (STSchema*) param;
H
hjxilinx 已提交
3349 3350 3351
  tQueryInfo* pInfo = pExpr->_node.info;
  tVariant*   pCond = pExpr->_node.pRight->pVal;
  SSchema*    pSchema = pExpr->_node.pLeft->pSchema;
3352

3353 3354
  pInfo->sch      = *pSchema;
  pInfo->optr     = pExpr->_node.optr;
Y
yihaoDeng 已提交
3355
  pInfo->compare  = getComparFunc(pInfo->sch.type, pInfo->optr);
H
Haojun Liao 已提交
3356
  pInfo->indexed  = pTSSchema->columns->colId == pInfo->sch.colId;
H
Haojun Liao 已提交
3357

H
hjxilinx 已提交
3358
  if (pInfo->optr == TSDB_RELATION_IN) {
Y
yihaoDeng 已提交
3359
     int dummy = -1;
3360
     SHashObj *pObj = NULL;
Y
yihaoDeng 已提交
3361 3362 3363 3364
     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 已提交
3365
          char* p = taosArrayGetP(arr, i);
3366 3367
          strntolower_s(varDataVal(p), varDataVal(p), varDataLen(p));
          taosHashPut(pObj, varDataVal(p), varDataLen(p), &dummy, sizeof(dummy));
Y
yihaoDeng 已提交
3368 3369 3370 3371
        }
     } else {
       buildFilterSetFromBinary((void **)&pObj, pCond->pz, pCond->nLen);
     }
3372
     pInfo->q = (char *)pObj;
H
Haojun Liao 已提交
3373
  } else if (pCond != NULL) {
3374 3375 3376 3377
    uint32_t size = pCond->nLen * TSDB_NCHAR_SIZE;
    if (size < (uint32_t)pSchema->bytes) {
      size = pSchema->bytes;
    }
wafwerar's avatar
wafwerar 已提交
3378
    // to make sure tonchar does not cause invalid write, since the '\0' needs at least sizeof(TdUcs4) space.
3379
    pInfo->q = calloc(1, size + TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE);
3380
    tVariantDump(pCond, pInfo->q, pSchema->type, true);
weixin_48148422's avatar
weixin_48148422 已提交
3381
  }
3382 3383
}

3384
#endif
3385

H
Haojun Liao 已提交
3386
static int32_t tableGroupComparFn(const void *p1, const void *p2, const void *param) {
3387
#if 0
3388
  STableGroupSupporter* pTableGroupSupp = (STableGroupSupporter*) param;
3389 3390
  STable* pTable1 = ((STableKeyInfo*) p1)->uid;
  STable* pTable2 = ((STableKeyInfo*) p2)->uid;
H
Haojun Liao 已提交
3391

3392 3393 3394
  for (int32_t i = 0; i < pTableGroupSupp->numOfCols; ++i) {
    SColIndex* pColIndex = &pTableGroupSupp->pCols[i];
    int32_t colIndex = pColIndex->colIndex;
H
Haojun Liao 已提交
3395

H
Haojun Liao 已提交
3396
    assert(colIndex >= TSDB_TBNAME_COLUMN_INDEX);
H
Haojun Liao 已提交
3397

3398 3399 3400 3401
    char *  f1 = NULL;
    char *  f2 = NULL;
    int32_t type = 0;
    int32_t bytes = 0;
H
Haojun Liao 已提交
3402

H
Haojun Liao 已提交
3403 3404 3405
    if (colIndex == TSDB_TBNAME_COLUMN_INDEX) {
      f1 = (char*) TABLE_NAME(pTable1);
      f2 = (char*) TABLE_NAME(pTable2);
3406
      type = TSDB_DATA_TYPE_BINARY;
3407
      bytes = tGetTbnameColumnSchema()->bytes;
3408
    } else {
Y
yihaoDeng 已提交
3409 3410 3411 3412 3413 3414 3415
      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);
      } 
3416
    }
H
Haojun Liao 已提交
3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430

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

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

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

3431 3432 3433 3434 3435 3436 3437
    int32_t ret = doCompare(f1, f2, type, bytes);
    if (ret == 0) {
      continue;
    } else {
      return ret;
    }
  }
3438
#endif
3439 3440 3441
  return 0;
}

H
Haojun Liao 已提交
3442
static int tsdbCheckInfoCompar(const void* key1, const void* key2) {
3443
  if (((STableCheckInfo*)key1)->tableId < ((STableCheckInfo*)key2)->tableId) {
H
Haojun Liao 已提交
3444
    return -1;
3445
  } else if (((STableCheckInfo*)key1)->tableId > ((STableCheckInfo*)key2)->tableId) {
H
Haojun Liao 已提交
3446 3447 3448 3449 3450 3451 3452 3453 3454
    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) {
3455
  STable* pTable = taosArrayGetP(pTableList, 0);
H
Haojun Liao 已提交
3456 3457
  SArray* g = taosArrayInit(16, sizeof(STableKeyInfo));

3458
  STableKeyInfo info = {.lastKey = skey};
H
Haojun Liao 已提交
3459
  taosArrayPush(g, &info);
3460

3461
  for (int32_t i = 1; i < numOfTables; ++i) {
3462 3463
    STable** prev = taosArrayGet(pTableList, i - 1);
    STable** p = taosArrayGet(pTableList, i);
H
Haojun Liao 已提交
3464

H
hjxilinx 已提交
3465
    int32_t ret = compareFn(prev, p, pSupp);
3466
    assert(ret == 0 || ret == -1);
H
Haojun Liao 已提交
3467

3468
    if (ret == 0) {
3469
      STableKeyInfo info1 = {.lastKey = skey};
H
Haojun Liao 已提交
3470
      taosArrayPush(g, &info1);
3471 3472
    } else {
      taosArrayPush(pGroups, &g);  // current group is ended, start a new group
H
Haojun Liao 已提交
3473 3474
      g = taosArrayInit(16, sizeof(STableKeyInfo));

3475
      STableKeyInfo info1 = {.lastKey = skey};
H
Haojun Liao 已提交
3476
      taosArrayPush(g, &info1);
3477 3478
    }
  }
H
Haojun Liao 已提交
3479

3480
  taosArrayPush(pGroups, &g);
3481 3482
}

3483
SArray* createTableGroup(SArray* pTableList, SSchemaWrapper* pTagSchema, SColIndex* pCols, int32_t numOfOrderCols, TSKEY skey) {
3484
  assert(pTableList != NULL);
3485
  SArray* pTableGroup = taosArrayInit(1, POINTER_BYTES);
H
Haojun Liao 已提交
3486

3487 3488
  size_t size = taosArrayGetSize(pTableList);
  if (size == 0) {
S
Shengliang Guan 已提交
3489
    tsdbDebug("no qualified tables");
3490 3491
    return pTableGroup;
  }
H
Haojun Liao 已提交
3492

3493
  if (numOfOrderCols == 0 || size == 1) { // no group by tags clause or only one table
3494
    SArray* sa = taosArrayDup(pTableList);
H
Haojun Liao 已提交
3495 3496 3497 3498
    if (sa == NULL) {
      taosArrayDestroy(pTableGroup);
      return NULL;
    }
H
Haojun Liao 已提交
3499

3500
    taosArrayPush(pTableGroup, &sa);
S
TD-1057  
Shengliang Guan 已提交
3501
    tsdbDebug("all %" PRIzu " tables belong to one group", size);
3502
  } else {
H
Haojun Liao 已提交
3503 3504
    STableGroupSupporter sup = {0};
    sup.numOfCols = numOfOrderCols;
3505
    sup.pTagSchema = pTagSchema->pSchema;
H
Haojun Liao 已提交
3506 3507
    sup.pCols = pCols;

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

3512 3513 3514
  return pTableGroup;
}

3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598
//static bool tableFilterFp(const void* pNode, void* param) {
//  tQueryInfo* pInfo = (tQueryInfo*) param;
//
//  STable* pTable = (STable*)(SL_GET_NODE_DATA((SSkipListNode*)pNode));
//
//  char* val = NULL;
//  if (pInfo->sch.colId == TSDB_TBNAME_COLUMN_INDEX) {
//    val = (char*) TABLE_NAME(pTable);
//  } else {
//    val = tdGetKVRowValOfCol(pTable->tagVal, pInfo->sch.colId);
//  }
//
//  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));
//    }
//  } else if (pInfo->optr == TSDB_RELATION_IN) {
//     int type = pInfo->sch.type;
//     if (type == TSDB_DATA_TYPE_BOOL || IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_TIMESTAMP) {
//       int64_t v;
//       GET_TYPED_DATA(v, int64_t, pInfo->sch.type, val);
//       return NULL != taosHashGet((SHashObj *)pInfo->q, (char *)&v, sizeof(v));
//     } 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));
//     }
//     else if (type == TSDB_DATA_TYPE_DOUBLE || type == TSDB_DATA_TYPE_FLOAT) {
//       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));
//     }
//
//  }
//
//  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);
//  }
//
//  switch (pInfo->optr) {
//    case TSDB_RELATION_EQUAL: {
//      return ret == 0;
//    }
//    case TSDB_RELATION_NOT_EQUAL: {
//      return ret != 0;
//    }
//    case TSDB_RELATION_GREATER_EQUAL: {
//      return ret >= 0;
//    }
//    case TSDB_RELATION_GREATER: {
//      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;
//    }
//    case TSDB_RELATION_MATCH: {
//      return ret == 0;
//    }
//    case TSDB_RELATION_NMATCH: {
//      return ret == 0;
//    }
//    case TSDB_RELATION_IN: {
//      return ret == 1;
//    }
//
//    default:
//      assert(false);
//  }
//
//  return true;
//}
H
Haojun Liao 已提交
3599

3600
//static void getTableListfromSkipList(tExprNode *pExpr, SSkipList *pSkipList, SArray *result, SExprTraverseSupp *param);
3601

3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613
//static int32_t doQueryTableList(STable* pSTable, SArray* pRes, tExprNode* pExpr) {
//  // query according to the expression tree
//  SExprTraverseSupp supp = {
//      .nodeFilterFn = (__result_filter_fn_t) tableFilterFp,
//      .setupInfoFn = filterPrepare,
//      .pExtInfo = pSTable->tagSchema,
//      };
//
//  getTableListfromSkipList(pExpr, pSTable->pIndex, pRes, &supp);
//  tExprTreeDestroy(pExpr, destroyHelper);
//  return TSDB_CODE_SUCCESS;
//}
3614

H
Haojun Liao 已提交
3615
int32_t tsdbQuerySTableByTagCond(void* pMeta, uint64_t uid, TSKEY skey, const char* pTagCond, size_t len,
3616
                                 int16_t tagNameRelType, const char* tbnameCond, STableGroupInfo* pGroupInfo,
3617
                                 SColIndex* pColIndex, int32_t numOfCols, uint64_t reqId, uint64_t taskId) {
H
Haojun Liao 已提交
3618
  STbCfg* pTbCfg = metaGetTbInfoByUid(pMeta, uid);
3619
  if (pTbCfg == NULL) {
H
Haojun Liao 已提交
3620
    tsdbError("%p failed to get stable, uid:%"PRIu64", TID:0x%"PRIx64" QID:0x%"PRIx64, pMeta, uid, taskId, reqId);
3621 3622
    terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
    goto _error;
3623
  }
H
Haojun Liao 已提交
3624

3625
  if (pTbCfg->type != META_SUPER_TABLE) {
H
Haojun Liao 已提交
3626
    tsdbError("%p query normal tag not allowed, uid:%" PRIu64 ", TID:0x%"PRIx64" QID:0x%"PRIx64, pMeta, uid, taskId, reqId);
3627
    terrno = TSDB_CODE_OPS_NOT_SUPPORT; //basically, this error is caused by invalid sql issued by client
3628
    goto _error;
H
hjxilinx 已提交
3629
  }
3630 3631

  //NOTE: not add ref count for super table
H
Haojun Liao 已提交
3632
  SArray* res = taosArrayInit(8, sizeof(STableKeyInfo));
H
Haojun Liao 已提交
3633
  SSchemaWrapper* pTagSchema = metaGetTableSchema(pMeta, uid, 0, true);
H
Haojun Liao 已提交
3634

weixin_48148422's avatar
weixin_48148422 已提交
3635 3636
  // no tags and tbname condition, all child tables of this stable are involved
  if (tbnameCond == NULL && (pTagCond == NULL || len == 0)) {
H
Haojun Liao 已提交
3637
    int32_t ret = getAllTableList(pMeta, uid, res);
3638 3639
    if (ret != TSDB_CODE_SUCCESS) {
      goto _error;
3640
    }
3641

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

H
Haojun Liao 已提交
3645 3646
    tsdbDebug("%p no table name/tag condition, all tables qualified, numOfTables:%u, group:%zu, TID:0x%"PRIx64" QID:0x%"PRIx64, pMeta,
              pGroupInfo->numOfTables, taosArrayGetSize(pGroupInfo->pGroupList), taskId, reqId);
3647

3648
    taosArrayDestroy(res);
3649 3650
    return ret;
  }
3651

H
hjxilinx 已提交
3652
  int32_t ret = TSDB_CODE_SUCCESS;
3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696
//  tExprNode* expr = NULL;
//
//  TRY(TSDB_MAX_TAG_CONDITIONS) {
//    expr = exprTreeFromTableName(tbnameCond);
//    if (expr == NULL) {
//      expr = exprTreeFromBinary(pTagCond, len);
//    } else {
//      CLEANUP_PUSH_VOID_PTR_PTR(true, tExprTreeDestroy, expr, NULL);
//      tExprNode* tagExpr = exprTreeFromBinary(pTagCond, len);
//      if (tagExpr != NULL) {
//        CLEANUP_PUSH_VOID_PTR_PTR(true, tExprTreeDestroy, tagExpr, NULL);
//        tExprNode* tbnameExpr = expr;
//        expr = calloc(1, sizeof(tExprNode));
//        if (expr == NULL) {
//          THROW( TSDB_CODE_TDB_OUT_OF_MEMORY );
//        }
//        expr->nodeType = TSQL_NODE_EXPR;
//        expr->_node.optr = (uint8_t)tagNameRelType;
//        expr->_node.pLeft = tagExpr;
//        expr->_node.pRight = tbnameExpr;
//      }
//    }
//    CLEANUP_EXECUTE();
//
//  } CATCH( code ) {
//    CLEANUP_EXECUTE();
//    terrno = code;
//    tsdbUnlockRepoMeta(tsdb);     // unlock tsdb in any cases
//
//    goto _error;
//    // TODO: more error handling
//  } END_TRY
//
//  doQueryTableList(pTable, res, expr);
//  pGroupInfo->numOfTables = (uint32_t)taosArrayGetSize(res);
//  pGroupInfo->pGroupList  = createTableGroup(res, pTagSchema, pColIndex, numOfCols, skey);
//
//  tsdbDebug("%p stable tid:%d, uid:%"PRIu64" query, numOfTables:%u, belong to %" PRIzu " groups", tsdb, pTable->tableId,
//      pTable->uid, pGroupInfo->numOfTables, taosArrayGetSize(pGroupInfo->pGroupList));
//
//  taosArrayDestroy(res);
//
//  if (tsdbUnlockRepoMeta(tsdb) < 0) goto _error;
//  return ret;
3697 3698 3699

  _error:
  return terrno;
3700
}
3701

H
Haojun Liao 已提交
3702 3703
int32_t tsdbGetOneTableGroup(void* pMeta, uint64_t uid, TSKEY startKey, STableGroupInfo* pGroupInfo) {
  STbCfg* pTbCfg = metaGetTbInfoByUid(pMeta, uid);
3704
  if (pTbCfg == NULL) {
3705 3706
    terrno = TSDB_CODE_TDB_INVALID_TABLE_ID;
    goto _error;
3707
  }
3708

3709 3710
  pGroupInfo->numOfTables = 1;
  pGroupInfo->pGroupList = taosArrayInit(1, POINTER_BYTES);
H
Haojun Liao 已提交
3711

H
Haojun Liao 已提交
3712 3713
  SArray* group = taosArrayInit(1, sizeof(STableKeyInfo));

3714
  STableKeyInfo info = {.lastKey = startKey, .uid = uid};
H
Haojun Liao 已提交
3715
  taosArrayPush(group, &info);
H
Haojun Liao 已提交
3716

3717
  taosArrayPush(pGroupInfo->pGroupList, &group);
3718
  return TSDB_CODE_SUCCESS;
3719 3720 3721

  _error:
  return terrno;
3722
}
3723

3724
#if 0
3725
int32_t tsdbGetTableGroupFromIdList(STsdb* tsdb, SArray* pTableIdList, STableGroupInfo* pGroupInfo) {
B
Bomin Zhang 已提交
3726 3727 3728
  if (tsdbRLockRepoMeta(tsdb) < 0) {
    return terrno;
  }
3729 3730 3731 3732

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

B
Bomin Zhang 已提交
3735
  for(int32_t i = 0; i < size; ++i) {
3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746
    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 已提交
3747 3748 3749
      tsdbUnlockRepoMeta(tsdb);
      taosArrayDestroy(group);
      return terrno;
3750 3751
    }

H
Haojun Liao 已提交
3752 3753
    STableKeyInfo info = {.pTable = pTable, .lastKey = id->key};
    taosArrayPush(group, &info);
3754 3755
  }

B
Bomin Zhang 已提交
3756 3757 3758 3759
  if (tsdbUnlockRepoMeta(tsdb) < 0) {
    taosArrayDestroy(group);
    return terrno;
  }
3760

sangshuduo's avatar
sangshuduo 已提交
3761
  pGroupInfo->numOfTables = (uint32_t) taosArrayGetSize(group);
B
Bomin Zhang 已提交
3762 3763 3764 3765 3766
  if (pGroupInfo->numOfTables > 0) {
    taosArrayPush(pGroupInfo->pGroupList, &group);
  } else {
    taosArrayDestroy(group);
  }
3767 3768 3769

  return TSDB_CODE_SUCCESS;
}
3770
#endif
3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785
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 已提交
3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798
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;
}

3799

H
Haojun Liao 已提交
3800
void tsdbCleanupReadHandle(tsdbReaderT queryHandle) {
3801 3802
  STsdbReadHandle* pTsdbReadHandle = (STsdbReadHandle*)queryHandle;
  if (pTsdbReadHandle == NULL) {
3803 3804
    return;
  }
3805

3806
  pTsdbReadHandle->pColumns = doFreeColumnInfoData(pTsdbReadHandle->pColumns);
3807

3808 3809 3810
  taosArrayDestroy(pTsdbReadHandle->defaultLoadColumn);
  tfree(pTsdbReadHandle->pDataBlockInfo);
  tfree(pTsdbReadHandle->statis);
3811

3812
  if (!emptyQueryTimewindow(pTsdbReadHandle)) {
3813
//    tsdbMayUnTakeMemSnapshot(pTsdbReadHandle);
3814
  } else {
3815
    assert(pTsdbReadHandle->pTableCheckInfo == NULL);
3816 3817
  }

3818 3819
  if (pTsdbReadHandle->pTableCheckInfo != NULL) {
    pTsdbReadHandle->pTableCheckInfo = destroyTableCheckInfo(pTsdbReadHandle->pTableCheckInfo);
3820
  }
3821

3822
  tsdbDestroyReadH(&pTsdbReadHandle->rhelper);
H
Haojun Liao 已提交
3823

3824 3825
  tdFreeDataCols(pTsdbReadHandle->pDataCols);
  pTsdbReadHandle->pDataCols = NULL;
H
Haojun Liao 已提交
3826

3827 3828
  pTsdbReadHandle->prev = doFreeColumnInfoData(pTsdbReadHandle->prev);
  pTsdbReadHandle->next = doFreeColumnInfoData(pTsdbReadHandle->next);
3829

3830
  SIOCostSummary* pCost = &pTsdbReadHandle->cost;
3831

H
Haojun Liao 已提交
3832 3833
  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, %s",
      pTsdbReadHandle, pCost->headFileLoad, pCost->headFileLoadTime, pCost->statisInfoLoadTime, pCost->blockLoadTime, pCost->checkForNextTime, pTsdbReadHandle->idStr);
H
Haojun Liao 已提交
3834

3835
  tfree(pTsdbReadHandle);
3836
}
3837

3838
#if 0
H
Haojun Liao 已提交
3839
void tsdbDestroyTableGroup(STableGroupInfo *pGroupList) {
3840 3841 3842 3843 3844 3845 3846 3847 3848 3849
  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);
3850 3851 3852 3853
      if (pTable != NULL) { // in case of handling retrieve data from tsdb
        tsdbUnRefTable(pTable);
      }
      //assert(pTable != NULL);
3854 3855 3856 3857 3858
    }

    taosArrayDestroy(p);
  }

3859
  taosHashCleanup(pGroupList->map);
3860
  taosArrayDestroy(pGroupList->pGroupList);
H
Haojun Liao 已提交
3861
  pGroupList->numOfTables = 0;
3862
}
H
Haojun Liao 已提交
3863 3864 3865 3866 3867 3868 3869

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 已提交
3870
    if (exprTreeApplyFilter(pExpr, pNode, param)) {
H
Haojun Liao 已提交
3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893
      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 已提交
3894
    pCond->start       = calloc(1, sizeof(SEndPoint));
H
Haojun Liao 已提交
3895
    pCond->start->optr = queryColInfo->optr;
Y
yihaoDeng 已提交
3896
    pCond->start->v    = queryColInfo->q;
H
Haojun Liao 已提交
3897
  } else if (optr == TSDB_RELATION_LESS || optr == TSDB_RELATION_LESS_EQUAL) {
Y
yihaoDeng 已提交
3898
    pCond->end       = calloc(1, sizeof(SEndPoint));
H
Haojun Liao 已提交
3899
    pCond->end->optr = queryColInfo->optr;
Y
yihaoDeng 已提交
3900 3901 3902 3903 3904 3905
    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 已提交
3906
    assert(0);
3907 3908
  } else if (optr == TSDB_RELATION_MATCH) {
    assert(0);
3909 3910
  } else if (optr == TSDB_RELATION_NMATCH) {
    assert(0);
H
Haojun Liao 已提交
3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993
  }

  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 已提交
3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006
    } 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 已提交
4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 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
    } 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);
4068 4069 4070
      } else if (pQueryInfo->optr == TSDB_RELATION_LIKE ||
                 pQueryInfo->optr == TSDB_RELATION_MATCH ||
                 pQueryInfo->optr == TSDB_RELATION_NMATCH) {
H
Haojun Liao 已提交
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
        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;
4102 4103
    if (pQueryInfo->indexed && (pQueryInfo->optr != TSDB_RELATION_LIKE
                                && pQueryInfo->optr != TSDB_RELATION_MATCH && pQueryInfo->optr != TSDB_RELATION_NMATCH
4104
                                && pQueryInfo->optr != TSDB_RELATION_IN)) {
H
Haojun Liao 已提交
4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119
      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);
}
4120
#endif