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

16 17
#include "function.h"
#include "functionMgt.h"
dengyihao's avatar
dengyihao 已提交
18 19
#include "index.h"
#include "os.h"
20
#include "tdatablock.h"
21
#include "thash.h"
22
#include "tmsg.h"
23
#include "ttime.h"
24

25 26
#include "executil.h"
#include "executorimpl.h"
H
Haojun Liao 已提交
27
#include "tcompression.h"
H
Haojun Liao 已提交
28

H
Haojun Liao 已提交
29 30 31 32
// If the numOfOutputGroups is 1, the data blocks that belongs to different groups will be provided randomly
// The numOfOutputGroups is specified by physical plan. and will not be affect by numOfGroups
struct STableListInfo {
  bool      oneTableForEachGroup;
dengyihao's avatar
dengyihao 已提交
33 34
  int32_t   numOfOuputGroups;  // the data block will be generated one by one
  int32_t*  groupOffset;       // keep the offset value for each group in the tableList
H
Haojun Liao 已提交
35
  SArray*   pTableList;
dengyihao's avatar
dengyihao 已提交
36
  SHashObj* map;  // speedup acquire the tableQueryInfo by table uid
H
Haojun Liao 已提交
37 38 39 40 41 42 43 44 45
  uint64_t  suid;
};

typedef struct tagFilterAssist {
  SHashObj* colHash;
  int32_t   index;
  SArray*   cInfoList;
} tagFilterAssist;

46
static int32_t removeInvalidUid(SArray* uids, SHashObj* tags);
H
Haojun Liao 已提交
47 48
static int32_t optimizeTbnameInCond(void* metaHandle, int64_t suid, SArray* pRes, SNode* pTagCond, SHashObj* tags);
static int32_t optimizeTbnameInCondImpl(void* metaHandle, SArray* pExistedUidList, SNode* pTagCond);
49 50
static int32_t getTableList(void* metaHandle, void* pVnode, SScanPhysiNode* pScanNode, SNode* pTagCond,
                            SNode* pTagIndexCond, STableListInfo* pListInfo);
dengyihao's avatar
dengyihao 已提交
51

H
Haojun Liao 已提交
52 53
static int64_t getLimit(const SNode* pLimit) { return NULL == pLimit ? -1 : ((SLimitNode*)pLimit)->limit; }
static int64_t getOffset(const SNode* pLimit) { return NULL == pLimit ? -1 : ((SLimitNode*)pLimit)->offset; }
dengyihao's avatar
dengyihao 已提交
54

dengyihao's avatar
dengyihao 已提交
55 56
void initResultRowInfo(SResultRowInfo* pResultRowInfo) {
  pResultRowInfo->size = 0;
57
  pResultRowInfo->cur.pageId = -1;
58 59
}

dengyihao's avatar
dengyihao 已提交
60
void closeResultRow(SResultRow* pResultRow) { pResultRow->closed = true; }
61

62 63 64 65 66 67 68 69 70 71 72
void resetResultRow(SResultRow* pResultRow, size_t entrySize) {
  pResultRow->numOfRows = 0;
  pResultRow->closed = false;
  pResultRow->endInterp = false;
  pResultRow->startInterp = false;

  if (entrySize > 0) {
    memset(pResultRow->pEntryInfo, 0, entrySize);
  }
}

H
Haojun Liao 已提交
73
// TODO refactor: use macro
74
SResultRowEntryInfo* getResultEntryInfo(const SResultRow* pRow, int32_t index, const int32_t* offset) {
H
Haojun Liao 已提交
75
  assert(index >= 0 && offset != NULL);
dengyihao's avatar
dengyihao 已提交
76
  return (SResultRowEntryInfo*)((char*)pRow->pEntryInfo + offset[index]);
H
Haojun Liao 已提交
77 78
}

79 80 81
size_t getResultRowSize(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  int32_t rowSize = (numOfOutput * sizeof(SResultRowEntryInfo)) + sizeof(SResultRow);

dengyihao's avatar
dengyihao 已提交
82
  for (int32_t i = 0; i < numOfOutput; ++i) {
83 84 85
    rowSize += pCtx[i].resDataInfo.interBufSize;
  }

86 87
  rowSize += (numOfOutput * sizeof(bool));
  // expand rowSize to mark if col is null for top/bottom result(saveTupleData)
88
  return rowSize;
89 90
}

H
Haojun Liao 已提交
91
void cleanupGroupResInfo(SGroupResInfo* pGroupResInfo) {
H
Haojun Liao 已提交
92
  taosMemoryFreeClear(pGroupResInfo->pBuf);
H
Haojun Liao 已提交
93
  pGroupResInfo->pRows = taosArrayDestroy(pGroupResInfo->pRows);
dengyihao's avatar
dengyihao 已提交
94
  pGroupResInfo->index = 0;
H
Haojun Liao 已提交
95 96
}

5
54liuyao 已提交
97
int32_t resultrowComparAsc(const void* p1, const void* p2) {
dengyihao's avatar
dengyihao 已提交
98 99
  SResKeyPos* pp1 = *(SResKeyPos**)p1;
  SResKeyPos* pp2 = *(SResKeyPos**)p2;
100 101

  if (pp1->groupId == pp2->groupId) {
dengyihao's avatar
dengyihao 已提交
102 103
    int64_t pts1 = *(int64_t*)pp1->key;
    int64_t pts2 = *(int64_t*)pp2->key;
104 105 106 107

    if (pts1 == pts2) {
      return 0;
    } else {
dengyihao's avatar
dengyihao 已提交
108
      return pts1 < pts2 ? -1 : 1;
109 110
    }
  } else {
dengyihao's avatar
dengyihao 已提交
111
    return pp1->groupId < pp2->groupId ? -1 : 1;
112 113 114
  }
}

dengyihao's avatar
dengyihao 已提交
115
static int32_t resultrowComparDesc(const void* p1, const void* p2) { return resultrowComparAsc(p2, p1); }
116

117
void initGroupedResultInfo(SGroupResInfo* pGroupResInfo, SSHashObj* pHashmap, int32_t order) {
H
Haojun Liao 已提交
118 119 120 121
  if (pGroupResInfo->pRows != NULL) {
    taosArrayDestroy(pGroupResInfo->pRows);
  }

122
  // extract the result rows information from the hash map
H
Haojun Liao 已提交
123 124
  int32_t size = tSimpleHashGetSize(pHashmap);

125
  void* pData = NULL;
H
Haojun Liao 已提交
126
  pGroupResInfo->pRows = taosArrayInit(size, POINTER_BYTES);
127

128
  size_t  keyLen = 0;
H
Haojun Liao 已提交
129 130
  int32_t num = 0, iter = 0, itemSize = 0;

131 132
  while ((pData = tSimpleHashIterate(pHashmap, pData, &iter)) != NULL) {
    void* key = tSimpleHashGetKey(pData, &keyLen);
133

H
Haojun Liao 已提交
134 135 136 137 138 139
    if (pGroupResInfo->pBuf == NULL) {
      itemSize = keyLen + sizeof(SResultRowPosition);
      pGroupResInfo->pBuf = taosMemoryMalloc(size * itemSize);
    }

    SResKeyPos* p = (SResKeyPos*)(pGroupResInfo->pBuf + num * itemSize);
140

dengyihao's avatar
dengyihao 已提交
141 142
    p->groupId = *(uint64_t*)key;
    p->pos = *(SResultRowPosition*)pData;
143
    memcpy(p->key, (char*)key + sizeof(uint64_t), keyLen - sizeof(uint64_t));
144
    taosArrayPush(pGroupResInfo->pRows, &p);
145
    num += 1;
146 147
  }

148
  if (order == TSDB_ORDER_ASC || order == TSDB_ORDER_DESC) {
dengyihao's avatar
dengyihao 已提交
149
    __compar_fn_t fn = (order == TSDB_ORDER_ASC) ? resultrowComparAsc : resultrowComparDesc;
150
    size = POINTER_BYTES;
H
Haojun Liao 已提交
151
    taosSort(pGroupResInfo->pRows->pData, taosArrayGetSize(pGroupResInfo->pRows), size, fn);
152 153
  }

H
Haojun Liao 已提交
154
  pGroupResInfo->index = 0;
H
Haojun Liao 已提交
155 156 157
  assert(pGroupResInfo->index <= getNumOfTotalRes(pGroupResInfo));
}

H
Haojun Liao 已提交
158 159
void initMultiResInfoFromArrayList(SGroupResInfo* pGroupResInfo, SArray* pArrayList) {
  if (pGroupResInfo->pRows != NULL) {
5
54liuyao 已提交
160
    taosArrayDestroyP(pGroupResInfo->pRows, taosMemoryFree);
H
Haojun Liao 已提交
161 162
  }

163
  pGroupResInfo->pRows = pArrayList;
H
Haojun Liao 已提交
164
  pGroupResInfo->index = 0;
165
  ASSERT(pGroupResInfo->index <= getNumOfTotalRes(pGroupResInfo));
H
Haojun Liao 已提交
166 167
}

168
bool hasRemainResults(SGroupResInfo* pGroupResInfo) {
H
Haojun Liao 已提交
169 170 171 172 173 174 175 176 177 178 179 180
  if (pGroupResInfo->pRows == NULL) {
    return false;
  }

  return pGroupResInfo->index < taosArrayGetSize(pGroupResInfo->pRows);
}

int32_t getNumOfTotalRes(SGroupResInfo* pGroupResInfo) {
  if (pGroupResInfo->pRows == 0) {
    return 0;
  }

dengyihao's avatar
dengyihao 已提交
181
  return (int32_t)taosArrayGetSize(pGroupResInfo->pRows);
H
Haojun Liao 已提交
182 183
}

184
SArray* createSortInfo(SNodeList* pNodeList) {
185
  size_t numOfCols = 0;
186

187 188 189 190 191
  if (pNodeList != NULL) {
    numOfCols = LIST_LENGTH(pNodeList);
  } else {
    numOfCols = 0;
  }
192

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
  SArray* pList = taosArrayInit(numOfCols, sizeof(SBlockOrderInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return pList;
  }

  for (int32_t i = 0; i < numOfCols; ++i) {
    SOrderByExprNode* pSortKey = (SOrderByExprNode*)nodesListGetNode(pNodeList, i);
    SBlockOrderInfo   bi = {0};
    bi.order = (pSortKey->order == ORDER_ASC) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
    bi.nullFirst = (pSortKey->nullOrder == NULL_ORDER_FIRST);

    SColumnNode* pColNode = (SColumnNode*)pSortKey->pExpr;
    bi.slotId = pColNode->slotId;
    taosArrayPush(pList, &bi);
  }

  return pList;
}

H
Haojun Liao 已提交
213
SSDataBlock* createDataBlockFromDescNode(SDataBlockDescNode* pNode) {
214
  int32_t numOfCols = LIST_LENGTH(pNode->pSlots);
H
Haojun Liao 已提交
215

216
  SSDataBlock* pBlock = createDataBlock();
H
Haojun Liao 已提交
217

H
Haojun Liao 已提交
218
  pBlock->info.id.blockId = pNode->dataBlockId;
219
  pBlock->info.type = STREAM_INVALID;
5
54liuyao 已提交
220
  pBlock->info.calWin = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
221
  pBlock->info.watermark = INT64_MIN;
H
Haojun Liao 已提交
222

223
  for (int32_t i = 0; i < numOfCols; ++i) {
M
Minglei Jin 已提交
224
    SSlotDescNode*  pDescNode = (SSlotDescNode*)nodesListGetNode(pNode->pSlots, i);
dengyihao's avatar
dengyihao 已提交
225 226
    SColumnInfoData idata =
        createColumnInfoData(pDescNode->dataType.type, pDescNode->dataType.bytes, pDescNode->slotId);
227 228 229
    idata.info.scale = pDescNode->dataType.scale;
    idata.info.precision = pDescNode->dataType.precision;

230
    blockDataAppendColInfo(pBlock, &idata);
H
Haojun Liao 已提交
231 232
  }

233 234 235
  return pBlock;
}

wmmhello's avatar
wmmhello 已提交
236 237
EDealRes doTranslateTagExpr(SNode** pNode, void* pContext) {
  SMetaReader* mr = (SMetaReader*)pContext;
dengyihao's avatar
dengyihao 已提交
238
  if (nodeType(*pNode) == QUERY_NODE_COLUMN) {
wmmhello's avatar
wmmhello 已提交
239 240
    SColumnNode* pSColumnNode = *(SColumnNode**)pNode;

dengyihao's avatar
dengyihao 已提交
241
    SValueNode* res = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE);
wmmhello's avatar
wmmhello 已提交
242 243 244 245 246 247 248 249 250
    if (NULL == res) {
      return DEAL_RES_ERROR;
    }

    res->translate = true;
    res->node.resType = pSColumnNode->node.resType;

    STagVal tagVal = {0};
    tagVal.cid = pSColumnNode->colId;
251
    const char* p = metaGetTableTagVal(mr->me.ctbEntry.pTags, pSColumnNode->node.resType.type, &tagVal);
wmmhello's avatar
wmmhello 已提交
252 253
    if (p == NULL) {
      res->node.resType.type = TSDB_DATA_TYPE_NULL;
dengyihao's avatar
dengyihao 已提交
254 255
    } else if (pSColumnNode->node.resType.type == TSDB_DATA_TYPE_JSON) {
      int32_t len = ((const STag*)p)->len;
wmmhello's avatar
wmmhello 已提交
256 257 258 259 260 261 262 263 264 265 266
      res->datum.p = taosMemoryCalloc(len + 1, 1);
      memcpy(res->datum.p, p, len);
    } else if (IS_VAR_DATA_TYPE(pSColumnNode->node.resType.type)) {
      res->datum.p = taosMemoryCalloc(tagVal.nData + VARSTR_HEADER_SIZE + 1, 1);
      memcpy(varDataVal(res->datum.p), tagVal.pData, tagVal.nData);
      varDataSetLen(res->datum.p, tagVal.nData);
    } else {
      nodesSetValueNodeValue(res, &(tagVal.i64));
    }
    nodesDestroyNode(*pNode);
    *pNode = (SNode*)res;
dengyihao's avatar
dengyihao 已提交
267 268 269 270
  } else if (nodeType(*pNode) == QUERY_NODE_FUNCTION) {
    SFunctionNode* pFuncNode = *(SFunctionNode**)pNode;
    if (pFuncNode->funcType == FUNCTION_TYPE_TBNAME) {
      SValueNode* res = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE);
wmmhello's avatar
wmmhello 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
      if (NULL == res) {
        return DEAL_RES_ERROR;
      }

      res->translate = true;
      res->node.resType = pFuncNode->node.resType;

      int32_t len = strlen(mr->me.name);
      res->datum.p = taosMemoryCalloc(len + VARSTR_HEADER_SIZE + 1, 1);
      memcpy(varDataVal(res->datum.p), mr->me.name, len);
      varDataSetLen(res->datum.p, len);
      nodesDestroyNode(*pNode);
      *pNode = (SNode*)res;
    }
  }

  return DEAL_RES_CONTINUE;
}

H
Haojun Liao 已提交
290
int32_t isQualifiedTable(STableKeyInfo* info, SNode* pTagCond, void* metaHandle, bool* pQualified) {
291
  int32_t     code = TSDB_CODE_SUCCESS;
dengyihao's avatar
dengyihao 已提交
292
  SMetaReader mr = {0};
293

wmmhello's avatar
wmmhello 已提交
294
  metaReaderInit(&mr, metaHandle, 0);
H
Haojun Liao 已提交
295
  code = metaGetTableEntryByUidCache(&mr, info->uid);
296 297
  if (TSDB_CODE_SUCCESS != code) {
    metaReaderClear(&mr);
M
Minglei Jin 已提交
298
    *pQualified = false;
299

M
Minglei Jin 已提交
300
    return TSDB_CODE_SUCCESS;
301
  }
wmmhello's avatar
wmmhello 已提交
302

dengyihao's avatar
dengyihao 已提交
303
  SNode* pTagCondTmp = nodesCloneNode(pTagCond);
wmmhello's avatar
wmmhello 已提交
304 305 306 307

  nodesRewriteExprPostOrder(&pTagCondTmp, doTranslateTagExpr, &mr);
  metaReaderClear(&mr);

308 309
  SNode* pNew = NULL;
  code = scalarCalculateConstants(pTagCondTmp, &pNew);
wmmhello's avatar
wmmhello 已提交
310
  if (TSDB_CODE_SUCCESS != code) {
wmmhello's avatar
wmmhello 已提交
311
    terrno = code;
wmmhello's avatar
wmmhello 已提交
312
    nodesDestroyNode(pTagCondTmp);
313 314 315
    *pQualified = false;

    return code;
wmmhello's avatar
wmmhello 已提交
316 317
  }

318
  ASSERT(nodeType(pNew) == QUERY_NODE_VALUE);
dengyihao's avatar
dengyihao 已提交
319
  SValueNode* pValue = (SValueNode*)pNew;
wmmhello's avatar
wmmhello 已提交
320

321
  ASSERT(pValue->node.resType.type == TSDB_DATA_TYPE_BOOL);
322 323
  *pQualified = pValue->datum.b;

wmmhello's avatar
wmmhello 已提交
324
  nodesDestroyNode(pNew);
325
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
326 327
}

wmmhello's avatar
wmmhello 已提交
328 329 330 331
static EDealRes getColumn(SNode** pNode, void* pContext) {
  SColumnNode* pSColumnNode = NULL;
  if (QUERY_NODE_COLUMN == nodeType((*pNode))) {
    pSColumnNode = *(SColumnNode**)pNode;
H
Haojun Liao 已提交
332
  } else if (QUERY_NODE_FUNCTION == nodeType((*pNode))) {
wmmhello's avatar
wmmhello 已提交
333 334 335 336 337 338 339 340 341 342 343 344
    SFunctionNode* pFuncNode = *(SFunctionNode**)(pNode);
    if (pFuncNode->funcType == FUNCTION_TYPE_TBNAME) {
      pSColumnNode = (SColumnNode*)nodesMakeNode(QUERY_NODE_COLUMN);
      if (NULL == pSColumnNode) {
        return DEAL_RES_ERROR;
      }
      pSColumnNode->colId = -1;
      pSColumnNode->colType = COLUMN_TYPE_TBNAME;
      pSColumnNode->node.resType.type = TSDB_DATA_TYPE_VARCHAR;
      pSColumnNode->node.resType.bytes = TSDB_TABLE_FNAME_LEN - 1 + VARSTR_HEADER_SIZE;
      nodesDestroyNode(*pNode);
      *pNode = (SNode*)pSColumnNode;
H
Haojun Liao 已提交
345
    } else {
346
      return DEAL_RES_CONTINUE;
wmmhello's avatar
wmmhello 已提交
347
    }
H
Haojun Liao 已提交
348
  } else {
wmmhello's avatar
wmmhello 已提交
349
    return DEAL_RES_CONTINUE;
wmmhello's avatar
wmmhello 已提交
350
  }
wmmhello's avatar
wmmhello 已提交
351

H
Haojun Liao 已提交
352 353 354
  tagFilterAssist* pData = (tagFilterAssist*)pContext;
  void*            data = taosHashGet(pData->colHash, &pSColumnNode->colId, sizeof(pSColumnNode->colId));
  if (!data) {
wmmhello's avatar
wmmhello 已提交
355 356
    taosHashPut(pData->colHash, &pSColumnNode->colId, sizeof(pSColumnNode->colId), pNode, sizeof((*pNode)));
    pSColumnNode->slotId = pData->index++;
H
Haojun Liao 已提交
357 358 359
    SColumnInfo cInfo = {.colId = pSColumnNode->colId,
                         .type = pSColumnNode->node.resType.type,
                         .bytes = pSColumnNode->node.resType.bytes};
360 361 362
#if TAG_FILTER_DEBUG
    qDebug("tagfilter build column info, slotId:%d, colId:%d, type:%d", pSColumnNode->slotId, cInfo.colId, cInfo.type);
#endif
wmmhello's avatar
wmmhello 已提交
363
    taosArrayPush(pData->cInfoList, &cInfo);
H
Haojun Liao 已提交
364
  } else {
365 366
    SColumnNode* col = *(SColumnNode**)data;
    pSColumnNode->slotId = col->slotId;
wmmhello's avatar
wmmhello 已提交
367 368
  }

wmmhello's avatar
wmmhello 已提交
369 370 371 372 373 374 375 376 377 378
  return DEAL_RES_CONTINUE;
}

static int32_t createResultData(SDataType* pType, int32_t numOfRows, SScalarParam* pParam) {
  SColumnInfoData* pColumnData = taosMemoryCalloc(1, sizeof(SColumnInfoData));
  if (pColumnData == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

H
Haojun Liao 已提交
379 380 381
  pColumnData->info.type = pType->type;
  pColumnData->info.bytes = pType->bytes;
  pColumnData->info.scale = pType->scale;
wmmhello's avatar
wmmhello 已提交
382 383
  pColumnData->info.precision = pType->precision;

H
Haojun Liao 已提交
384
  int32_t code = colInfoDataEnsureCapacity(pColumnData, numOfRows, true);
wmmhello's avatar
wmmhello 已提交
385
  if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
386
    terrno = code;
wmmhello's avatar
wmmhello 已提交
387 388 389 390 391 392 393 394 395
    taosMemoryFree(pColumnData);
    return terrno;
  }

  pParam->columnData = pColumnData;
  pParam->colAlloced = true;
  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
396
static SColumnInfoData* getColInfoResult(void* metaHandle, int64_t suid, SArray* uidList, SNode* pTagCond) {
H
Haojun Liao 已提交
397 398
  int32_t      code = TSDB_CODE_SUCCESS;
  SArray*      pBlockList = NULL;
wmmhello's avatar
wmmhello 已提交
399
  SSDataBlock* pResBlock = NULL;
H
Haojun Liao 已提交
400
  SHashObj*    tags = NULL;
wmmhello's avatar
wmmhello 已提交
401 402 403
  SScalarParam output = {0};

  tagFilterAssist ctx = {0};
wmmhello's avatar
wmmhello 已提交
404

wmmhello's avatar
wmmhello 已提交
405
  ctx.colHash = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_SMALLINT), false, HASH_NO_LOCK);
H
Haojun Liao 已提交
406
  if (ctx.colHash == NULL) {
wmmhello's avatar
wmmhello 已提交
407 408 409
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
410

wmmhello's avatar
wmmhello 已提交
411
  ctx.cInfoList = taosArrayInit(4, sizeof(SColumnInfo));
H
Haojun Liao 已提交
412
  if (ctx.cInfoList == NULL) {
wmmhello's avatar
wmmhello 已提交
413 414 415
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
wmmhello's avatar
wmmhello 已提交
416

H
Haojun Liao 已提交
417
  nodesRewriteExprPostOrder(&pTagCond, getColumn, (void*)&ctx);
wmmhello's avatar
wmmhello 已提交
418

H
Haojun Liao 已提交
419
  SDataType type = {.type = TSDB_DATA_TYPE_BOOL, .bytes = sizeof(bool)};
wmmhello's avatar
wmmhello 已提交
420

H
Haojun Liao 已提交
421
  //  int64_t stt = taosGetTimestampUs();
H
Haojun Liao 已提交
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
  SArray* pRes = taosArrayInit(10, sizeof(SFilterTableInfo));
  int32_t filter = optimizeTbnameInCond(metaHandle, suid, pRes, pTagCond, tags);
  if (filter == 0) {  // tbname in filter is activated, do nothing and return
    int32_t numOfRows = taosArrayGetSize(pRes);
    code = createResultData(&type, numOfRows, &output);
    if (code != TSDB_CODE_SUCCESS) {
      terrno = code;
      qError("failed to create result, reason:%s", tstrerror(code));
      goto end;
    }

    bool* b = (bool*)output.columnData->pData;
    taosArrayEnsureCap(uidList, numOfRows);

    for(int32_t i = 0; i < numOfRows; ++i) {
      b[i] = true;
      SFilterTableInfo* pInfo = taosArrayGet(pRes, i);
      taosArrayPush(uidList, &pInfo->uid);
    }
dengyihao's avatar
dengyihao 已提交
441

H
Haojun Liao 已提交
442 443 444
    terrno = 0;
    goto end;
  } else {
445
    // here we retrieve all tags from the vnode table-meta store
dengyihao's avatar
dengyihao 已提交
446 447 448 449 450 451
    code = metaGetTableTags(metaHandle, suid, uidList, tags);
    if (code != TSDB_CODE_SUCCESS) {
      qError("failed to get table tags from meta, reason:%s, suid:%" PRIu64, tstrerror(code), suid);
      terrno = code;
      goto end;
    }
wmmhello's avatar
wmmhello 已提交
452
  }
453

dengyihao's avatar
dengyihao 已提交
454
  if (suid != 0) {
H
Haojun Liao 已提交
455 456 457 458 459 460 461 462 463 464 465 466 467
//    removeInvalidUid(uidList, tags);
  }

  pResBlock = createDataBlock();
  if (pResBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }

  for (int32_t i = 0; i < taosArrayGetSize(ctx.cInfoList); ++i) {
    SColumnInfoData colInfo = {0};
    colInfo.info = *(SColumnInfo*)taosArrayGet(ctx.cInfoList, i);
    blockDataAppendColInfo(pResBlock, &colInfo);
dengyihao's avatar
dengyihao 已提交
468
  }
wmmhello's avatar
wmmhello 已提交
469

H
Haojun Liao 已提交
470
  int32_t size = taosArrayGetSize(pRes);
471
  if (size == 0) {
472 473
    goto end;
  }
wmmhello's avatar
wmmhello 已提交
474

475
  code = blockDataEnsureCapacity(pResBlock, size);
476 477 478 479
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    goto end;
  }
wmmhello's avatar
wmmhello 已提交
480

H
Haojun Liao 已提交
481 482
  int32_t numOfCols = taosArrayGetSize(pResBlock->pDataBlock);

483
  for (int32_t i = 0; i < size; i++) {
H
Haojun Liao 已提交
484 485 486
    SFilterTableInfo* p1 = taosArrayGet(pRes, i);

    for (int32_t j = 0; j < numOfCols; j++) {
wmmhello's avatar
wmmhello 已提交
487
      SColumnInfoData* pColInfo = (SColumnInfoData*)taosArrayGet(pResBlock->pDataBlock, j);
488

H
Haojun Liao 已提交
489
      if (pColInfo->info.colId == -1) {  // tbname
490
        char str[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
H
Haojun Liao 已提交
491
        STR_TO_VARSTR(str, p1->name);
492
        colDataAppend(pColInfo, i, str, false);
493
#if TAG_FILTER_DEBUG
H
Haojun Liao 已提交
494
        qDebug("tagfilter uid:%ld, tbname:%s", *uid, str + 2);
495
#endif
H
Haojun Liao 已提交
496
      } else {
wmmhello's avatar
wmmhello 已提交
497 498
        STagVal tagVal = {0};
        tagVal.cid = pColInfo->info.colId;
H
Haojun Liao 已提交
499
        const char* p = metaGetTableTagVal(p1->pTagVal, pColInfo->info.type, &tagVal);
wmmhello's avatar
wmmhello 已提交
500

H
Haojun Liao 已提交
501
        if (p == NULL || (pColInfo->info.type == TSDB_DATA_TYPE_JSON && ((STag*)p)->nTag == 0)) {
wmmhello's avatar
wmmhello 已提交
502
          colDataAppend(pColInfo, i, p, true);
wmmhello's avatar
wmmhello 已提交
503 504
        } else if (pColInfo->info.type == TSDB_DATA_TYPE_JSON) {
          colDataAppend(pColInfo, i, p, false);
wmmhello's avatar
wmmhello 已提交
505
        } else if (IS_VAR_DATA_TYPE(pColInfo->info.type)) {
506
          char* tmp = alloca(tagVal.nData + VARSTR_HEADER_SIZE + 1);
wmmhello's avatar
wmmhello 已提交
507 508 509
          varDataSetLen(tmp, tagVal.nData);
          memcpy(tmp + VARSTR_HEADER_SIZE, tagVal.pData, tagVal.nData);
          colDataAppend(pColInfo, i, tmp, false);
510
#if TAG_FILTER_DEBUG
H
Haojun Liao 已提交
511
          qDebug("tagfilter varch:%s", tmp + 2);
512
#endif
wmmhello's avatar
wmmhello 已提交
513 514
        } else {
          colDataAppend(pColInfo, i, (const char*)&tagVal.i64, false);
515
#if TAG_FILTER_DEBUG
H
Haojun Liao 已提交
516
          if (pColInfo->info.type == TSDB_DATA_TYPE_INT) {
517
            qDebug("tagfilter int:%d", *(int*)(&tagVal.i64));
H
Haojun Liao 已提交
518 519
          } else if (pColInfo->info.type == TSDB_DATA_TYPE_DOUBLE) {
            qDebug("tagfilter double:%f", *(double*)(&tagVal.i64));
520 521
          }
#endif
wmmhello's avatar
wmmhello 已提交
522
        }
wmmhello's avatar
wmmhello 已提交
523 524 525
      }
    }
  }
H
Haojun Liao 已提交
526

527
  pResBlock->info.rows = size;
wmmhello's avatar
wmmhello 已提交
528

H
Haojun Liao 已提交
529 530
  //  int64_t st1 = taosGetTimestampUs();
  //  qDebug("generate tag block rows:%d, cost:%ld us", rows, st1-st);
wmmhello's avatar
wmmhello 已提交
531 532 533 534 535

  pBlockList = taosArrayInit(2, POINTER_BYTES);
  taosArrayPush(pBlockList, &pResBlock);

  code = scalarCalculate(pTagCond, pBlockList, &output);
H
Haojun Liao 已提交
536 537
  if (code != TSDB_CODE_SUCCESS) {
    qError("failed to calculate scalar, reason:%s", tstrerror(code));
wmmhello's avatar
wmmhello 已提交
538
    terrno = code;
H
Haojun Liao 已提交
539
    goto end;
wmmhello's avatar
wmmhello 已提交
540
  }
H
Haojun Liao 已提交
541 542
  //  int64_t st2 = taosGetTimestampUs();
  //  qDebug("calculate tag block rows:%d, cost:%ld us", rows, st2-st1);
wmmhello's avatar
wmmhello 已提交
543 544

end:
545
  taosHashCleanup(tags);
wmmhello's avatar
wmmhello 已提交
546 547 548 549 550 551 552
  taosHashCleanup(ctx.colHash);
  taosArrayDestroy(ctx.cInfoList);
  blockDataDestroy(pResBlock);
  taosArrayDestroy(pBlockList);
  return output.columnData;
}

H
Haojun Liao 已提交
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
static void releaseColInfoData(void* pCol) {
  if (pCol) {
    SColumnInfoData* col = (SColumnInfoData*)pCol;
    colDataDestroy(col);
    taosMemoryFree(col);
  }
}

int32_t getColInfoResultForGroupby(void* metaHandle, SNodeList* group, STableListInfo* pTableListInfo) {
  int32_t      code = TSDB_CODE_SUCCESS;
  SArray*      pBlockList = NULL;
  SSDataBlock* pResBlock = NULL;
  SHashObj*    tags = NULL;
  SArray*      uidList = NULL;
  void*        keyBuf = NULL;
  SArray*      groupData = NULL;

  int32_t rows = taosArrayGetSize(pTableListInfo->pTableList);
  if (rows == 0) {
    return TDB_CODE_SUCCESS;
  }

  tagFilterAssist ctx = {0};
  ctx.colHash = taosHashInit(4, taosGetDefaultHashFunction(TSDB_DATA_TYPE_SMALLINT), false, HASH_NO_LOCK);
  if (ctx.colHash == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
581

H
Haojun Liao 已提交
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
  ctx.index = 0;
  ctx.cInfoList = taosArrayInit(4, sizeof(SColumnInfo));
  if (ctx.cInfoList == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }

  SNode* pNode = NULL;
  FOREACH(pNode, group) {
    nodesRewriteExprPostOrder(&pNode, getColumn, (void*)&ctx);
    REPLACE_NODE(pNode);
  }

  pResBlock = createDataBlock();
  if (pResBlock == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }

  for (int32_t i = 0; i < taosArrayGetSize(ctx.cInfoList); ++i) {
H
Haojun Liao 已提交
602
    SColumnInfoData colInfo = {0};
H
Haojun Liao 已提交
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
    colInfo.info = *(SColumnInfo*)taosArrayGet(ctx.cInfoList, i);
    blockDataAppendColInfo(pResBlock, &colInfo);
  }

  uidList = taosArrayInit(rows, sizeof(uint64_t));
  for (int32_t i = 0; i < rows; ++i) {
    STableKeyInfo* pkeyInfo = taosArrayGet(pTableListInfo->pTableList, i);
    taosArrayPush(uidList, &pkeyInfo->uid);
  }

  //  int64_t stt = taosGetTimestampUs();
  tags = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
  code = metaGetTableTags(metaHandle, pTableListInfo->suid, uidList, tags);
  if (code != TSDB_CODE_SUCCESS) {
    goto end;
  }

  //  int64_t stt1 = taosGetTimestampUs();
  //  qDebug("generate tag meta rows:%d, cost:%ld us", rows, stt1-stt);

  code = blockDataEnsureCapacity(pResBlock, rows);
  if (code != TSDB_CODE_SUCCESS) {
    goto end;
  }

  //  int64_t st = taosGetTimestampUs();
  for (int32_t i = 0; i < rows; i++) {
    int64_t* uid = taosArrayGet(uidList, i);
    for (int32_t j = 0; j < taosArrayGetSize(pResBlock->pDataBlock); j++) {
      SColumnInfoData* pColInfo = (SColumnInfoData*)taosArrayGet(pResBlock->pDataBlock, j);

      if (pColInfo->info.colId == -1) {  // tbname
        char str[TSDB_TABLE_FNAME_LEN + VARSTR_HEADER_SIZE] = {0};
        metaGetTableNameByUid(metaHandle, *uid, str);
        colDataAppend(pColInfo, i, str, false);
#if TAG_FILTER_DEBUG
        qDebug("tagfilter uid:%ld, tbname:%s", *uid, str + 2);
#endif
      } else {
        void* tag = taosHashGet(tags, uid, sizeof(int64_t));
643
        ASSERT(tag);
644

H
Haojun Liao 已提交
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
        STagVal tagVal = {0};
        tagVal.cid = pColInfo->info.colId;
        const char* p = metaGetTableTagVal(tag, pColInfo->info.type, &tagVal);

        if (p == NULL || (pColInfo->info.type == TSDB_DATA_TYPE_JSON && ((STag*)p)->nTag == 0)) {
          colDataAppend(pColInfo, i, p, true);
        } else if (pColInfo->info.type == TSDB_DATA_TYPE_JSON) {
          colDataAppend(pColInfo, i, p, false);
        } else if (IS_VAR_DATA_TYPE(pColInfo->info.type)) {
          char* tmp = taosMemoryCalloc(tagVal.nData + VARSTR_HEADER_SIZE + 1, 1);
          varDataSetLen(tmp, tagVal.nData);
          memcpy(tmp + VARSTR_HEADER_SIZE, tagVal.pData, tagVal.nData);
          colDataAppend(pColInfo, i, tmp, false);
#if TAG_FILTER_DEBUG
          qDebug("tagfilter varch:%s", tmp + 2);
#endif
          taosMemoryFree(tmp);
        } else {
          colDataAppend(pColInfo, i, (const char*)&tagVal.i64, false);
#if TAG_FILTER_DEBUG
          if (pColInfo->info.type == TSDB_DATA_TYPE_INT) {
            qDebug("tagfilter int:%d", *(int*)(&tagVal.i64));
          } else if (pColInfo->info.type == TSDB_DATA_TYPE_DOUBLE) {
            qDebug("tagfilter double:%f", *(double*)(&tagVal.i64));
          }
#endif
        }
      }
    }
  }
675

H
Haojun Liao 已提交
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
  pResBlock->info.rows = rows;

  //  int64_t st1 = taosGetTimestampUs();
  //  qDebug("generate tag block rows:%d, cost:%ld us", rows, st1-st);

  pBlockList = taosArrayInit(2, POINTER_BYTES);
  taosArrayPush(pBlockList, &pResBlock);

  groupData = taosArrayInit(2, POINTER_BYTES);
  FOREACH(pNode, group) {
    SScalarParam output = {0};

    switch (nodeType(pNode)) {
      case QUERY_NODE_VALUE:
        break;
      case QUERY_NODE_COLUMN:
      case QUERY_NODE_OPERATOR:
      case QUERY_NODE_FUNCTION: {
        SExprNode* expNode = (SExprNode*)pNode;
        code = createResultData(&expNode->resType, rows, &output);
        if (code != TSDB_CODE_SUCCESS) {
          goto end;
        }
        break;
      }
701

H
Haojun Liao 已提交
702 703 704 705
      default:
        code = TSDB_CODE_OPS_NOT_SUPPORT;
        goto end;
    }
706

H
Haojun Liao 已提交
707 708 709 710 711 712 713 714 715
    if (nodeType(pNode) == QUERY_NODE_COLUMN) {
      SColumnNode*     pSColumnNode = (SColumnNode*)pNode;
      SColumnInfoData* pColInfo = (SColumnInfoData*)taosArrayGet(pResBlock->pDataBlock, pSColumnNode->slotId);
      code = colDataAssign(output.columnData, pColInfo, rows, NULL);
    } else if (nodeType(pNode) == QUERY_NODE_VALUE) {
      continue;
    } else {
      code = scalarCalculate(pNode, pBlockList, &output);
    }
716

H
Haojun Liao 已提交
717 718 719 720
    if (code != TSDB_CODE_SUCCESS) {
      releaseColInfoData(output.columnData);
      goto end;
    }
721

H
Haojun Liao 已提交
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
    taosArrayPush(groupData, &output.columnData);
  }

  int32_t keyLen = 0;
  SNode*  node;
  FOREACH(node, group) {
    SExprNode* pExpr = (SExprNode*)node;
    keyLen += pExpr->resType.bytes;
  }

  int32_t nullFlagSize = sizeof(int8_t) * LIST_LENGTH(group);
  keyLen += nullFlagSize;

  keyBuf = taosMemoryCalloc(1, keyLen);
  if (keyBuf == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
740

H
Haojun Liao 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
  for (int i = 0; i < rows; i++) {
    STableKeyInfo* info = taosArrayGet(pTableListInfo->pTableList, i);

    char* isNull = (char*)keyBuf;
    char* pStart = (char*)keyBuf + sizeof(int8_t) * LIST_LENGTH(group);
    for (int j = 0; j < taosArrayGetSize(groupData); j++) {
      SColumnInfoData* pValue = (SColumnInfoData*)taosArrayGetP(groupData, j);

      if (colDataIsNull_s(pValue, i)) {
        isNull[j] = 1;
      } else {
        isNull[j] = 0;
        char* data = colDataGetData(pValue, i);
        if (pValue->info.type == TSDB_DATA_TYPE_JSON) {
          if (tTagIsJson(data)) {
            code = TSDB_CODE_QRY_JSON_IN_GROUP_ERROR;
            goto end;
          }
          if (tTagIsJsonNull(data)) {
            isNull[j] = 1;
            continue;
          }
          int32_t len = getJsonValueLen(data);
          memcpy(pStart, data, len);
          pStart += len;
        } else if (IS_VAR_DATA_TYPE(pValue->info.type)) {
          memcpy(pStart, data, varDataTLen(data));
          pStart += varDataTLen(data);
        } else {
          memcpy(pStart, data, pValue->info.bytes);
          pStart += pValue->info.bytes;
        }
      }
    }

    int32_t len = (int32_t)(pStart - (char*)keyBuf);
    info->groupId = calcGroupId(keyBuf, len);
  }

  //  int64_t st2 = taosGetTimestampUs();
  //  qDebug("calculate tag block rows:%d, cost:%ld us", rows, st2-st1);

end:
  taosMemoryFreeClear(keyBuf);
  taosHashCleanup(tags);
  taosHashCleanup(ctx.colHash);
  taosArrayDestroy(ctx.cInfoList);
  blockDataDestroy(pResBlock);
  taosArrayDestroy(pBlockList);
  taosArrayDestroy(uidList);
  taosArrayDestroyP(groupData, releaseColInfoData);
  return code;
}

H
Haojun Liao 已提交
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
static int32_t nameComparFn(const void* p1, const void* p2) {
  const char* pName1 = *(const char**)p1;
  const char* pName2 = *(const char**)p2;

  int32_t ret = strcmp(pName1, pName2);
  if (ret == 0) {
    return 0;
  } else {
    return (ret > 0) ? 1 : -1;
  }
}

static SArray* getTableNameList(const SNodeListNode* pList) {
  int32_t    len = LIST_LENGTH(pList->pNodeList);
  SListCell* cell = pList->pNodeList->pHead;

  SArray* pTbList = taosArrayInit(len, POINTER_BYTES);
  for (int i = 0; i < pList->pNodeList->length; i++) {
    SValueNode* valueNode = (SValueNode*)cell->pNode;
    if (!IS_VAR_DATA_TYPE(valueNode->node.resType.type)) {
      terrno = TSDB_CODE_INVALID_PARA;
      taosArrayDestroy(pTbList);
      return NULL;
    }

    char* name = varDataVal(valueNode->datum.p);
    taosArrayPush(pTbList, &name);
    cell = cell->pNext;
  }

  size_t numOfTables = taosArrayGetSize(pTbList);

  // order the name
  taosArraySort(pTbList, nameComparFn);

  // remove the duplicates
  SArray* pNewList = taosArrayInit(taosArrayGetSize(pTbList), sizeof(void*));
  taosArrayPush(pNewList, taosArrayGet(pTbList, 0));

  for (int32_t i = 1; i < numOfTables; ++i) {
    char** name = taosArrayGetLast(pNewList);
    char** nameInOldList = taosArrayGet(pTbList, i);
    if (strcmp(*name, *nameInOldList) == 0) {
      continue;
    }

    taosArrayPush(pNewList, nameInOldList);
  }

  taosArrayDestroy(pTbList);
  return pNewList;
}

dengyihao's avatar
dengyihao 已提交
848
static int tableUidCompare(const void* a, const void* b) {
H
Haojun Liao 已提交
849 850 851
  uint64_t u1 = *(uint64_t*)a;
  uint64_t u2 = *(uint64_t*)b;

dengyihao's avatar
dengyihao 已提交
852 853 854
  if (u1 == u2) {
    return 0;
  }
H
Haojun Liao 已提交
855

dengyihao's avatar
dengyihao 已提交
856 857
  return u1 < u2 ? -1 : 1;
}
H
Haojun Liao 已提交
858

H
Haojun Liao 已提交
859 860 861 862 863 864 865 866 867 868 869 870
static int32_t filterTableInfoCompare(const void* a, const void* b) {
  SFilterTableInfo* p1 = (SFilterTableInfo*) a;
  SFilterTableInfo* p2 = (SFilterTableInfo*) b;

  if (p1->uid == p2->uid) {
    return 0;
  }

  return p1->uid < p2->uid? -1:1;
}

static int32_t optimizeTbnameInCond(void* metaHandle, int64_t suid, SArray* pRes, SNode* cond, SHashObj* tags) {
dengyihao's avatar
dengyihao 已提交
871
  int32_t ret = -1;
872 873 874
  int32_t ntype = nodeType(cond);

  if (ntype == QUERY_NODE_OPERATOR) {
H
Haojun Liao 已提交
875
    ret = optimizeTbnameInCondImpl(metaHandle, pRes, cond);
dengyihao's avatar
dengyihao 已提交
876 877
  }

878
  if (ntype != QUERY_NODE_LOGIC_CONDITION || ((SLogicConditionNode*)cond)->condType != LOGIC_COND_TYPE_AND) {
dengyihao's avatar
dengyihao 已提交
879
    return ret;
dengyihao's avatar
dengyihao 已提交
880 881
  }

dengyihao's avatar
dengyihao 已提交
882
  bool                 hasTbnameCond = false;
dengyihao's avatar
dengyihao 已提交
883
  SLogicConditionNode* pNode = (SLogicConditionNode*)cond;
dengyihao's avatar
dengyihao 已提交
884
  SNodeList*           pList = (SNodeList*)pNode->pParameterList;
dengyihao's avatar
dengyihao 已提交
885

dengyihao's avatar
dengyihao 已提交
886
  int32_t len = LIST_LENGTH(pList);
H
Haojun Liao 已提交
887 888 889
  if (len <= 0) {
    return ret;
  }
dengyihao's avatar
dengyihao 已提交
890

dengyihao's avatar
dengyihao 已提交
891
  SListCell* cell = pList->pHead;
dengyihao's avatar
dengyihao 已提交
892
  for (int i = 0; i < len; i++) {
dengyihao's avatar
dengyihao 已提交
893
    if (cell == NULL) break;
H
Haojun Liao 已提交
894
    if (optimizeTbnameInCondImpl(metaHandle, pRes, cell->pNode) == 0) {
dengyihao's avatar
dengyihao 已提交
895
      hasTbnameCond = true;
dengyihao's avatar
dengyihao 已提交
896
      break;
dengyihao's avatar
dengyihao 已提交
897 898 899
    }
    cell = cell->pNext;
  }
H
Haojun Liao 已提交
900

H
Haojun Liao 已提交
901 902
  taosArraySort(pRes, filterTableInfoCompare);
  taosArrayRemoveDuplicate(pRes, filterTableInfoCompare, NULL);
dengyihao's avatar
dengyihao 已提交
903

dengyihao's avatar
dengyihao 已提交
904
  if (hasTbnameCond) {
905
    ret = metaGetTableTagsByUids(metaHandle, suid, pRes);
H
Haojun Liao 已提交
906
    removeInvalidUid(pRes, tags);
dengyihao's avatar
dengyihao 已提交
907
  }
H
Haojun Liao 已提交
908

dengyihao's avatar
dengyihao 已提交
909 910 911 912 913 914
  return ret;
}

/*
 * handle invalid uid
 */
915 916 917 918 919
static int32_t removeInvalidUid(SArray* uids, SHashObj* tags) {
  int32_t size = taosArrayGetSize(uids);
  if (size <= 0) {
    return 0;
  }
dengyihao's avatar
dengyihao 已提交
920

H
Haojun Liao 已提交
921
  SArray* validUid = taosArrayInit(size, sizeof(SFilterTableInfo));
dengyihao's avatar
dengyihao 已提交
922

923
  for (int32_t i = 0; i < size; i++) {
H
Haojun Liao 已提交
924 925 926
    SFilterTableInfo* p = taosArrayGet(uids, i);
    if (taosHashGet(tags, &p->uid, sizeof(int64_t)) != NULL) {
      taosArrayPush(validUid, p);
dengyihao's avatar
dengyihao 已提交
927 928
    }
  }
H
Haojun Liao 已提交
929

dengyihao's avatar
dengyihao 已提交
930 931 932
  taosArraySwap(uids, validUid);
  taosArrayDestroy(validUid);
  return 0;
dengyihao's avatar
dengyihao 已提交
933
}
934

935
// only return uid that does not contained in pExistedUidList
H
Haojun Liao 已提交
936
static int32_t optimizeTbnameInCondImpl(void* metaHandle, SArray* pExistedUidList, SNode* pTagCond) {
dengyihao's avatar
dengyihao 已提交
937 938 939
  if (nodeType(pTagCond) != QUERY_NODE_OPERATOR) {
    return -1;
  }
940

dengyihao's avatar
dengyihao 已提交
941 942 943 944
  SOperatorNode* pNode = (SOperatorNode*)pTagCond;
  if (pNode->opType != OP_TYPE_IN) {
    return -1;
  }
945

dengyihao's avatar
dengyihao 已提交
946 947 948 949 950 951
  if ((pNode->pLeft != NULL && nodeType(pNode->pLeft) == QUERY_NODE_COLUMN &&
       ((SColumnNode*)pNode->pLeft)->colType == COLUMN_TYPE_TBNAME) &&
      (pNode->pRight != NULL && nodeType(pNode->pRight) == QUERY_NODE_NODE_LIST)) {
    SNodeListNode* pList = (SNodeListNode*)pNode->pRight;

    int32_t len = LIST_LENGTH(pList->pNodeList);
H
Haojun Liao 已提交
952 953
    if (len <= 0) {
      return -1;
dengyihao's avatar
dengyihao 已提交
954 955
    }

dengyihao's avatar
dengyihao 已提交
956 957 958
    SArray*   pTbList = getTableNameList(pList);
    int32_t   numOfTables = taosArrayGetSize(pTbList);
    SHashObj* uHash = NULL;
H
Haojun Liao 已提交
959

960 961 962 963
    size_t    numOfExisted = taosArrayGetSize(pExistedUidList);  // len > 0 means there already have uids
    if (numOfExisted > 0) {
      uHash = taosHashInit(numOfExisted / 0.7, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_NO_LOCK);
      for (int i = 0; i < numOfExisted; i++) {
H
Haojun Liao 已提交
964 965
        SFilterTableInfo* pTInfo = taosArrayGet(pExistedUidList, i);
        taosHashPut(uHash, &pTInfo->uid, sizeof(uint64_t), &i, sizeof(i));
D
dapan1121 已提交
966 967
      }
    }
dengyihao's avatar
dengyihao 已提交
968

969 970
    for (int i = 0; i < numOfTables; i++) {
      char* name = taosArrayGetP(pTbList, i);
dengyihao's avatar
dengyihao 已提交
971 972 973

      uint64_t uid = 0;
      if (metaGetTableUidByName(metaHandle, name, &uid) == 0) {
dengyihao's avatar
dengyihao 已提交
974 975
        ETableType tbType = TSDB_TABLE_MAX;
        if (metaGetTableTypeByName(metaHandle, name, &tbType) == 0 && tbType == TSDB_CHILD_TABLE) {
D
dapan1121 已提交
976
          if (NULL == uHash || taosHashGet(uHash, &uid, sizeof(uid)) == NULL) {
H
Haojun Liao 已提交
977 978
            SFilterTableInfo s = {.uid = uid, .name = name, .pTagVal = NULL};
            taosArrayPush(pExistedUidList, &s);
D
dapan1121 已提交
979
          }
dengyihao's avatar
dengyihao 已提交
980 981
        } else {
          taosArrayDestroy(pTbList);
D
dapan1121 已提交
982
          taosHashCleanup(uHash);
dengyihao's avatar
dengyihao 已提交
983 984
          return -1;
        }
dengyihao's avatar
dengyihao 已提交
985
      } else {
H
Haojun Liao 已提交
986
//        qWarn("failed to get tableIds from by table name: %s, reason: %s", name, tstrerror(terrno));
dengyihao's avatar
dengyihao 已提交
987 988 989
        terrno = 0;
      }
    }
990

D
dapan1121 已提交
991
    taosHashCleanup(uHash);
dengyihao's avatar
dengyihao 已提交
992
    taosArrayDestroy(pTbList);
dengyihao's avatar
dengyihao 已提交
993
    return 0;
dengyihao's avatar
dengyihao 已提交
994
  }
H
Haojun Liao 已提交
995

dengyihao's avatar
dengyihao 已提交
996
  return -1;
dengyihao's avatar
dengyihao 已提交
997
}
H
Haojun Liao 已提交
998

999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
static void genTagFilterDigest(const SNode* pTagCond, T_MD5_CTX* pContext) {
  if (pTagCond == NULL) {
    return;
  }

  char*   payload = NULL;
  int32_t len = 0;
  nodesNodeToMsg(pTagCond, &payload, &len);

  tMD5Init(pContext);
  tMD5Update(pContext, (uint8_t*)payload, (uint32_t)len);
  tMD5Final(pContext);

  taosMemoryFree(payload);
}

H
Haojun Liao 已提交
1015
static int32_t doFilterByTagCond(STableListInfo* pListInfo, SArray* pRes, SNode* pTagCond, void* metaHandle) {
1016 1017 1018 1019 1020
  if (pTagCond == NULL) {
    return TSDB_CODE_SUCCESS;
  }

  terrno = TDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1021
  SColumnInfoData* pColInfoData = getColInfoResult(metaHandle, pListInfo->suid, pRes, pTagCond);
1022 1023 1024
  if (terrno != TDB_CODE_SUCCESS) {
    colDataDestroy(pColInfoData);
    taosMemoryFreeClear(pColInfoData);
H
Haojun Liao 已提交
1025
    taosArrayDestroy(pRes);
1026 1027 1028 1029 1030
    qError("failed to getColInfoResult, code: %s", tstrerror(terrno));
    return terrno;
  }

  int32_t i = 0;
H
Haojun Liao 已提交
1031
  int32_t len = taosArrayGetSize(pRes);
1032 1033 1034

  if (pColInfoData != NULL) {
    bool*   pResult = (bool*)pColInfoData->pData;
H
Haojun Liao 已提交
1035
    SArray* p = taosArrayInit(taosArrayGetSize(pRes), sizeof(uint64_t));
1036 1037

    while (i < len && pColInfoData) {
H
Haojun Liao 已提交
1038
      int64_t* uid = taosArrayGet(pRes, i);
1039 1040 1041 1042 1043
      qDebug("tagfilter get uid:%" PRId64 ", res:%d", *uid, pResult[i]);

      if (pResult[i]) {
        taosArrayPush(p, uid);
      }
H
Haojun Liao 已提交
1044

1045 1046 1047
      i += 1;
    }

H
Haojun Liao 已提交
1048
    taosArraySwap(pRes, p);
1049 1050 1051 1052 1053 1054 1055 1056 1057
    taosArrayDestroy(p);
  }

  colDataDestroy(pColInfoData);
  taosMemoryFreeClear(pColInfoData);

  return TSDB_CODE_SUCCESS;
}

1058 1059
int32_t getTableList(void* metaHandle, void* pVnode, SScanPhysiNode* pScanNode, SNode* pTagCond, SNode* pTagIndexCond,
                     STableListInfo* pListInfo) {
1060
  int32_t code = TSDB_CODE_SUCCESS;
1061
  size_t  numOfTables = 0;
1062

1063
  uint64_t tableUid = pScanNode->uid;
D
dapan1121 已提交
1064
  pListInfo->suid = pScanNode->suid;
1065
  SArray* res = taosArrayInit(8, sizeof(uint64_t));
dengyihao's avatar
dengyihao 已提交
1066

1067
  if (pScanNode->tableType != TSDB_SUPER_TABLE) {
H
Haojun Liao 已提交
1068
    if (metaIsTableExist(metaHandle, tableUid)) {
1069 1070
      taosArrayPush(res, &tableUid);
    }
1071

1072 1073 1074
    code = doFilterByTagCond(pListInfo, res, pTagCond, metaHandle);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
H
Haojun Liao 已提交
1075
    }
1076 1077 1078 1079
  } else {
    // try to retrieve the result from meta cache
    T_MD5_CTX context = {0};
    genTagFilterDigest(pTagCond, &context);
H
Haojun Liao 已提交
1080 1081

    bool acquired = false;
H
Haojun Liao 已提交
1082
    metaGetCachedTableUidList(metaHandle, pScanNode->suid, context.digest, tListLen(context.digest), res, &acquired);
1083 1084 1085
    if (acquired) {
      qDebug("retrieve table uid list from cache, numOfTables:%d", (int32_t)taosArrayGetSize(res));
      goto _end;
wmmhello's avatar
wmmhello 已提交
1086 1087
    }

1088
    if (!pTagCond) {  // no tag filter condition exists, let's fetch all tables of this super table
1089
      ASSERT(pTagIndexCond == NULL);
1090 1091
      vnodeGetCtbIdList(pVnode, pScanNode->suid, res);
    } else {
H
Haojun Liao 已提交
1092 1093 1094 1095 1096 1097 1098
      // failed to find the result in the cache, let try to calculate the results
      if (pTagIndexCond) {
        SIndexMetaArg metaArg = {
            .metaEx = metaHandle, .idx = tsdbGetIdx(metaHandle), .ivtIdx = tsdbGetIvtIdx(metaHandle), .suid = tableUid};

        SIdxFltStatus status = SFLT_NOT_INDEX;
        code = doFilterTag(pTagIndexCond, &metaArg, res, &status);
H
Haojun Liao 已提交
1099 1100
        if (code != 0 || status == SFLT_NOT_INDEX) {  // temporarily disable it for performance sake
//          qError("failed to get tableIds from index, reason:%s, suid:%" PRIu64, tstrerror(code), tableUid);
H
Haojun Liao 已提交
1101 1102
          code = TDB_CODE_SUCCESS;
        }
wmmhello's avatar
wmmhello 已提交
1103 1104
      }
    }
1105

1106 1107 1108
    code = doFilterByTagCond(pListInfo, res, pTagCond, metaHandle);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
wmmhello's avatar
wmmhello 已提交
1109 1110
    }

1111 1112 1113 1114 1115
    // let's add the filter results into meta-cache
    numOfTables = taosArrayGetSize(res);
    size_t size = numOfTables * sizeof(uint64_t) + sizeof(int32_t);
    char*  pPayload = taosMemoryMalloc(size);
    *(int32_t*)pPayload = numOfTables;
1116

1117 1118
    if (numOfTables > 0) {
      memcpy(pPayload + sizeof(int32_t), taosArrayGet(res, 0), numOfTables * sizeof(uint64_t));
wmmhello's avatar
wmmhello 已提交
1119
    }
1120 1121

    metaUidFilterCachePut(metaHandle, pScanNode->suid, context.digest, tListLen(context.digest), pPayload, size, 1);
wmmhello's avatar
wmmhello 已提交
1122 1123
  }

1124 1125
_end:
  numOfTables = taosArrayGetSize(res);
H
Haojun Liao 已提交
1126
  for (int i = 0; i < numOfTables; i++) {
1127
    STableKeyInfo info = {.uid = *(uint64_t*)taosArrayGet(res, i), .groupId = 0};
1128 1129

    void* p = taosArrayPush(pListInfo->pTableList, &info);
H
Haojun Liao 已提交
1130 1131 1132 1133 1134
    if (p == NULL) {
      taosArrayDestroy(res);
      return TSDB_CODE_OUT_OF_MEMORY;
    }

H
Haojun Liao 已提交
1135
    qTrace("tagfilter get uid:%" PRIu64 "", info.uid);
1136 1137 1138
  }

  taosArrayDestroy(res);
1139 1140
  return code;
}
H
Haojun Liao 已提交
1141

1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
size_t getTableTagsBufLen(const SNodeList* pGroups) {
  size_t keyLen = 0;

  SNode* node;
  FOREACH(node, pGroups) {
    SExprNode* pExpr = (SExprNode*)node;
    keyLen += pExpr->resType.bytes;
  }

  keyLen += sizeof(int8_t) * LIST_LENGTH(pGroups);
  return keyLen;
}

H
Haojun Liao 已提交
1155
int32_t getGroupIdFromTagsVal(void* pMeta, uint64_t uid, SNodeList* pGroupNode, char* keyBuf, uint64_t* pGroupId) {
M
Minglei Jin 已提交
1156
  SMetaReader mr = {0};
1157
  metaReaderInit(&mr, pMeta, 0);
H
Haojun Liao 已提交
1158
  if (metaGetTableEntryByUidCache(&mr, uid) != 0) {  // table not exist
1159 1160 1161
    metaReaderClear(&mr);
    return TSDB_CODE_PAR_TABLE_NOT_EXIST;
  }
1162 1163 1164 1165 1166

  SNodeList* groupNew = nodesCloneList(pGroupNode);

  nodesRewriteExprsPostOrder(groupNew, doTranslateTagExpr, &mr);
  char* isNull = (char*)keyBuf;
M
Minglei Jin 已提交
1167
  char* pStart = (char*)keyBuf + sizeof(int8_t) * LIST_LENGTH(pGroupNode);
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182

  SNode*  pNode;
  int32_t index = 0;
  FOREACH(pNode, groupNew) {
    SNode*  pNew = NULL;
    int32_t code = scalarCalculateConstants(pNode, &pNew);
    if (TSDB_CODE_SUCCESS == code) {
      REPLACE_NODE(pNew);
    } else {
      taosMemoryFree(keyBuf);
      nodesDestroyList(groupNew);
      metaReaderClear(&mr);
      return code;
    }

1183
    ASSERT(nodeType(pNew) == QUERY_NODE_VALUE);
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
    SValueNode* pValue = (SValueNode*)pNew;

    if (pValue->node.resType.type == TSDB_DATA_TYPE_NULL || pValue->isNull) {
      isNull[index++] = 1;
      continue;
    } else {
      isNull[index++] = 0;
      char* data = nodesGetValueFromNode(pValue);
      if (pValue->node.resType.type == TSDB_DATA_TYPE_JSON) {
        if (tTagIsJson(data)) {
          terrno = TSDB_CODE_QRY_JSON_IN_GROUP_ERROR;
          taosMemoryFree(keyBuf);
          nodesDestroyList(groupNew);
          metaReaderClear(&mr);
          return terrno;
        }
        int32_t len = getJsonValueLen(data);
        memcpy(pStart, data, len);
        pStart += len;
      } else if (IS_VAR_DATA_TYPE(pValue->node.resType.type)) {
        memcpy(pStart, data, varDataTLen(data));
        pStart += varDataTLen(data);
      } else {
        memcpy(pStart, data, pValue->node.resType.bytes);
        pStart += pValue->node.resType.bytes;
      }
    }
  }

M
Minglei Jin 已提交
1213
  int32_t len = (int32_t)(pStart - (char*)keyBuf);
1214 1215 1216 1217 1218 1219 1220
  *pGroupId = calcGroupId(keyBuf, len);

  nodesDestroyList(groupNew);
  metaReaderClear(&mr);
  return TSDB_CODE_SUCCESS;
}

1221
SArray* extractPartitionColInfo(SNodeList* pNodeList) {
dengyihao's avatar
dengyihao 已提交
1222
  if (!pNodeList) {
1223 1224
    return NULL;
  }
H
Haojun Liao 已提交
1225

1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
  size_t  numOfCols = LIST_LENGTH(pNodeList);
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColumn));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnNode* pColNode = (SColumnNode*)nodesListGetNode(pNodeList, i);

    // todo extract method
    SColumn c = {0};
    c.slotId = pColNode->slotId;
    c.colId = pColNode->colId;
    c.type = pColNode->node.resType.type;
    c.bytes = pColNode->node.resType.bytes;
    c.precision = pColNode->node.resType.precision;
    c.scale = pColNode->node.resType.scale;

    taosArrayPush(pList, &c);
  }
H
Haojun Liao 已提交
1247

1248
  return pList;
H
Haojun Liao 已提交
1249 1250
}

H
Haojun Liao 已提交
1251 1252
int32_t extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols,
                            int32_t type, SColMatchInfo* pMatchInfo) {
H
Haojun Liao 已提交
1253
  size_t  numOfCols = LIST_LENGTH(pNodeList);
H
Haojun Liao 已提交
1254 1255 1256 1257
  int32_t code = 0;

  pMatchInfo->matchType = type;

1258
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColMatchItem));
1259
  if (pList == NULL) {
H
Haojun Liao 已提交
1260 1261
    code = TSDB_CODE_OUT_OF_MEMORY;
    return code;
1262 1263 1264 1265
  }

  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
1266 1267 1268
    if (nodeType(pNode->pExpr) == QUERY_NODE_COLUMN) {
      SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

H
Haojun Liao 已提交
1269
      SColMatchItem c = {.needOutput = true};
1270 1271
      c.colId = pColNode->colId;
      c.srcSlotId = pColNode->slotId;
H
Haojun Liao 已提交
1272
      c.dstSlotId = pNode->slotId;
1273 1274
      taosArrayPush(pList, &c);
    }
1275 1276
  }

H
Haojun Liao 已提交
1277
  // set the output flag for each column in SColMatchInfo, according to the
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
  *numOfOutputCols = 0;
  int32_t num = LIST_LENGTH(pOutputNodeList->pSlots);
  for (int32_t i = 0; i < num; ++i) {
    SSlotDescNode* pNode = (SSlotDescNode*)nodesListGetNode(pOutputNodeList->pSlots, i);

    // todo: add reserve flag check
    // it is a column reserved for the arithmetic expression calculation
    if (pNode->slotId >= numOfCols) {
      (*numOfOutputCols) += 1;
      continue;
    }

H
Haojun Liao 已提交
1290
    SColMatchItem* info = NULL;
1291 1292
    for (int32_t j = 0; j < taosArrayGetSize(pList); ++j) {
      info = taosArrayGet(pList, j);
H
Haojun Liao 已提交
1293
      if (info->dstSlotId == pNode->slotId) {
1294 1295 1296
        break;
      }
    }
1297

1298 1299
    if (pNode->output) {
      (*numOfOutputCols) += 1;
H
Haojun Liao 已提交
1300 1301
    } else if (info != NULL) {
      // select distinct tbname from stb where tbname='abc';
H
Haojun Liao 已提交
1302
      info->needOutput = false;
1303
    }
1304
  }
1305

H
Haojun Liao 已提交
1306
  pMatchInfo->pList = pList;
H
Haojun Liao 已提交
1307
  return code;
1308 1309
}

1310 1311 1312 1313 1314 1315 1316 1317
static SResSchema createResSchema(int32_t type, int32_t bytes, int32_t slotId, int32_t scale, int32_t precision,
                                  const char* name) {
  SResSchema s = {0};
  s.scale = scale;
  s.type = type;
  s.bytes = bytes;
  s.slotId = slotId;
  s.precision = precision;
H
Haojun Liao 已提交
1318
  tstrncpy(s.name, name, tListLen(s.name));
1319 1320 1321

  return s;
}
1322

H
Haojun Liao 已提交
1323
static SColumn* createColumn(int32_t blockId, int32_t slotId, int32_t colId, SDataType* pType, EColumnType colType) {
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
  SColumn* pCol = taosMemoryCalloc(1, sizeof(SColumn));
  if (pCol == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  pCol->slotId = slotId;
  pCol->colId = colId;
  pCol->bytes = pType->bytes;
  pCol->type = pType->type;
  pCol->scale = pType->scale;
  pCol->precision = pType->precision;
  pCol->dataBlockId = blockId;
H
Haojun Liao 已提交
1337
  pCol->colType = colType;
1338 1339 1340
  return pCol;
}

1341
void createExprFromOneNode(SExprInfo* pExp, SNode* pNode, int16_t slotId) {
1342 1343 1344 1345
  pExp->pExpr = taosMemoryCalloc(1, sizeof(tExprNode));
  pExp->pExpr->_function.num = 1;
  pExp->pExpr->_function.functionId = -1;

1346
  int32_t type = nodeType(pNode);
1347 1348 1349
  // it is a project query, or group by column
  if (type == QUERY_NODE_COLUMN) {
    pExp->pExpr->nodeType = QUERY_NODE_COLUMN;
1350
    SColumnNode* pColNode = (SColumnNode*)pNode;
1351 1352 1353 1354 1355

    pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
    pExp->base.numOfParams = 1;

    SDataType* pType = &pColNode->node.resType;
1356 1357
    pExp->base.resSchema =
        createResSchema(pType->type, pType->bytes, slotId, pType->scale, pType->precision, pColNode->colName);
1358 1359 1360 1361 1362
    pExp->base.pParam[0].pCol =
        createColumn(pColNode->dataBlockId, pColNode->slotId, pColNode->colId, pType, pColNode->colType);
    pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
  } else if (type == QUERY_NODE_VALUE) {
    pExp->pExpr->nodeType = QUERY_NODE_VALUE;
1363
    SValueNode* pValNode = (SValueNode*)pNode;
1364 1365 1366 1367 1368

    pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
    pExp->base.numOfParams = 1;

    SDataType* pType = &pValNode->node.resType;
1369 1370
    pExp->base.resSchema =
        createResSchema(pType->type, pType->bytes, slotId, pType->scale, pType->precision, pValNode->node.aliasName);
1371 1372 1373 1374
    pExp->base.pParam[0].type = FUNC_PARAM_TYPE_VALUE;
    nodesValueNodeToVariant(pValNode, &pExp->base.pParam[0].param);
  } else if (type == QUERY_NODE_FUNCTION) {
    pExp->pExpr->nodeType = QUERY_NODE_FUNCTION;
1375
    SFunctionNode* pFuncNode = (SFunctionNode*)pNode;
1376 1377

    SDataType* pType = &pFuncNode->node.resType;
1378 1379
    pExp->base.resSchema =
        createResSchema(pType->type, pType->bytes, slotId, pType->scale, pType->precision, pFuncNode->node.aliasName);
1380

H
Haojun Liao 已提交
1381 1382 1383 1384
    tExprNode* pExprNode = pExp->pExpr;

    pExprNode->_function.functionId = pFuncNode->funcId;
    pExprNode->_function.pFunctNode = pFuncNode;
S
shenglian zhou 已提交
1385
    pExprNode->_function.functionType = pFuncNode->funcType;
H
Haojun Liao 已提交
1386 1387

    tstrncpy(pExprNode->_function.functionName, pFuncNode->functionName, tListLen(pExprNode->_function.functionName));
1388 1389 1390

#if 1
    // todo refactor: add the parameter for tbname function
H
Haojun Liao 已提交
1391
    const char* name = "tbname";
dengyihao's avatar
dengyihao 已提交
1392
    int32_t     len = strlen(name);
H
Haojun Liao 已提交
1393 1394 1395

    if (!pFuncNode->pParameterList && (memcmp(pExprNode->_function.functionName, name, len) == 0) &&
        pExprNode->_function.functionName[len] == 0) {
1396
      pFuncNode->pParameterList = nodesMakeList();
1397
      ASSERT(LIST_LENGTH(pFuncNode->pParameterList) == 0);
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
      SValueNode* res = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE);
      if (NULL == res) {  // todo handle error
      } else {
        res->node.resType = (SDataType){.bytes = sizeof(int64_t), .type = TSDB_DATA_TYPE_BIGINT};
        nodesListAppend(pFuncNode->pParameterList, (SNode*)res);
      }
    }
#endif

    int32_t numOfParam = LIST_LENGTH(pFuncNode->pParameterList);

    pExp->base.pParam = taosMemoryCalloc(numOfParam, sizeof(SFunctParam));
    pExp->base.numOfParams = numOfParam;

    for (int32_t j = 0; j < numOfParam; ++j) {
      SNode* p1 = nodesListGetNode(pFuncNode->pParameterList, j);
      if (p1->type == QUERY_NODE_COLUMN) {
        SColumnNode* pcn = (SColumnNode*)p1;

        pExp->base.pParam[j].type = FUNC_PARAM_TYPE_COLUMN;
        pExp->base.pParam[j].pCol =
            createColumn(pcn->dataBlockId, pcn->slotId, pcn->colId, &pcn->node.resType, pcn->colType);
      } else if (p1->type == QUERY_NODE_VALUE) {
        SValueNode* pvn = (SValueNode*)p1;
        pExp->base.pParam[j].type = FUNC_PARAM_TYPE_VALUE;
        nodesValueNodeToVariant(pvn, &pExp->base.pParam[j].param);
      }
    }
  } else if (type == QUERY_NODE_OPERATOR) {
    pExp->pExpr->nodeType = QUERY_NODE_OPERATOR;
1428
    SOperatorNode* pOpNode = (SOperatorNode*)pNode;
1429 1430 1431 1432

    pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
    pExp->base.numOfParams = 1;

1433 1434 1435 1436
    SDataType* pType = &pOpNode->node.resType;
    pExp->base.resSchema =
        createResSchema(pType->type, pType->bytes, slotId, pType->scale, pType->precision, pOpNode->node.aliasName);
    pExp->pExpr->_optrRoot.pRootNode = pNode;
D
dapan1121 已提交
1437 1438
  } else if (type == QUERY_NODE_CASE_WHEN) {
    pExp->pExpr->nodeType = QUERY_NODE_OPERATOR;
D
dapan1121 已提交
1439
    SCaseWhenNode* pCaseNode = (SCaseWhenNode*)pNode;
dengyihao's avatar
dengyihao 已提交
1440

D
dapan1121 已提交
1441 1442
    pExp->base.pParam = taosMemoryCalloc(1, sizeof(SFunctParam));
    pExp->base.numOfParams = 1;
dengyihao's avatar
dengyihao 已提交
1443

D
dapan1121 已提交
1444
    SDataType* pType = &pCaseNode->node.resType;
dengyihao's avatar
dengyihao 已提交
1445 1446
    pExp->base.resSchema =
        createResSchema(pType->type, pType->bytes, slotId, pType->scale, pType->precision, pCaseNode->node.aliasName);
D
dapan1121 已提交
1447
    pExp->pExpr->_optrRoot.pRootNode = pNode;
1448
  } else {
1449
    ASSERT(0);
1450 1451 1452
  }
}

1453 1454 1455 1456
void createExprFromTargetNode(SExprInfo* pExp, STargetNode* pTargetNode) {
  createExprFromOneNode(pExp, pTargetNode->pExpr, pTargetNode->slotId);
}

1457 1458 1459 1460 1461 1462 1463 1464
SExprInfo* createExprInfo(SNodeList* pNodeList, SNodeList* pGroupKeys, int32_t* numOfExprs) {
  int32_t numOfFuncs = LIST_LENGTH(pNodeList);
  int32_t numOfGroupKeys = 0;
  if (pGroupKeys != NULL) {
    numOfGroupKeys = LIST_LENGTH(pGroupKeys);
  }

  *numOfExprs = numOfFuncs + numOfGroupKeys;
1465 1466 1467 1468
  if (*numOfExprs == 0) {
    return NULL;
  }

1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
  SExprInfo* pExprs = taosMemoryCalloc(*numOfExprs, sizeof(SExprInfo));

  for (int32_t i = 0; i < (*numOfExprs); ++i) {
    STargetNode* pTargetNode = NULL;
    if (i < numOfFuncs) {
      pTargetNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    } else {
      pTargetNode = (STargetNode*)nodesListGetNode(pGroupKeys, i - numOfFuncs);
    }

    SExprInfo* pExp = &pExprs[i];
1480
    createExprFromTargetNode(pExp, pTargetNode);
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
  }

  return pExprs;
}

// set the output buffer for the selectivity + tag query
static int32_t setSelectValueColumnInfo(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  int32_t num = 0;

  SqlFunctionCtx*  p = NULL;
  SqlFunctionCtx** pValCtx = taosMemoryCalloc(numOfOutput, POINTER_BYTES);
  if (pValCtx == NULL) {
S
Shengliang Guan 已提交
1493
    return TSDB_CODE_OUT_OF_MEMORY;
1494 1495 1496
  }

  for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
1497
    const char* pName = pCtx[i].pExpr->pExpr->_function.functionName;
1498
    if ((strcmp(pName, "_select_value") == 0) || (strcmp(pName, "_group_key") == 0)) {
1499 1500 1501 1502 1503
      pValCtx[num++] = &pCtx[i];
    } else if (fmIsSelectFunc(pCtx[i].functionId)) {
      p = &pCtx[i];
    }
  }
H
Haojun Liao 已提交
1504

1505 1506 1507
  if (p != NULL) {
    p->subsidiaries.pCtx = pValCtx;
    p->subsidiaries.num = num;
1508
  } else {
1509
    taosMemoryFreeClear(pValCtx);
1510
  }
1511 1512

  return TSDB_CODE_SUCCESS;
1513 1514
}

1515
SqlFunctionCtx* createSqlFunctionCtx(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowEntryInfoOffset) {
1516 1517 1518 1519
  SqlFunctionCtx* pFuncCtx = (SqlFunctionCtx*)taosMemoryCalloc(numOfOutput, sizeof(SqlFunctionCtx));
  if (pFuncCtx == NULL) {
    return NULL;
  }
1520

1521 1522
  *rowEntryInfoOffset = taosMemoryCalloc(numOfOutput, sizeof(int32_t));
  if (*rowEntryInfoOffset == 0) {
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
    taosMemoryFreeClear(pFuncCtx);
    return NULL;
  }

  for (int32_t i = 0; i < numOfOutput; ++i) {
    SExprInfo* pExpr = &pExprInfo[i];

    SExprBasicInfo* pFunct = &pExpr->base;
    SqlFunctionCtx* pCtx = &pFuncCtx[i];

    pCtx->functionId = -1;
    pCtx->pExpr = pExpr;

    if (pExpr->pExpr->nodeType == QUERY_NODE_FUNCTION) {
      SFuncExecEnv env = {0};
      pCtx->functionId = pExpr->pExpr->_function.pFunctNode->funcId;

      if (fmIsAggFunc(pCtx->functionId) || fmIsIndefiniteRowsFunc(pCtx->functionId)) {
        bool isUdaf = fmIsUserDefinedFunc(pCtx->functionId);
        if (!isUdaf) {
          fmGetFuncExecFuncs(pCtx->functionId, &pCtx->fpSet);
        } else {
          char* udfName = pExpr->pExpr->_function.pFunctNode->functionName;
1546
          pCtx->udfName = strdup(udfName);
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
          fmGetUdafExecFuncs(pCtx->functionId, &pCtx->fpSet);
        }
        pCtx->fpSet.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
      } else {
        fmGetScalarFuncExecFuncs(pCtx->functionId, &pCtx->sfp);
        if (pCtx->sfp.getEnv != NULL) {
          pCtx->sfp.getEnv(pExpr->pExpr->_function.pFunctNode, &env);
        }
      }
      pCtx->resDataInfo.interBufSize = env.calcMemSize;
    } else if (pExpr->pExpr->nodeType == QUERY_NODE_COLUMN || pExpr->pExpr->nodeType == QUERY_NODE_OPERATOR ||
               pExpr->pExpr->nodeType == QUERY_NODE_VALUE) {
      // for simple column, the result buffer needs to hold at least one element.
      pCtx->resDataInfo.interBufSize = pFunct->resSchema.bytes;
    }

    pCtx->input.numOfInputCols = pFunct->numOfParams;
    pCtx->input.pData = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);
    pCtx->input.pColumnDataAgg = taosMemoryCalloc(pFunct->numOfParams, POINTER_BYTES);

    pCtx->pTsOutput = NULL;
    pCtx->resDataInfo.bytes = pFunct->resSchema.bytes;
    pCtx->resDataInfo.type = pFunct->resSchema.type;
    pCtx->order = TSDB_ORDER_ASC;
    pCtx->start.key = INT64_MIN;
    pCtx->end.key = INT64_MIN;
    pCtx->numOfParams = pExpr->base.numOfParams;
    pCtx->param = pFunct->pParam;
1575
    pCtx->saveHandle.currentPage = -1;
1576 1577 1578
  }

  for (int32_t i = 1; i < numOfOutput; ++i) {
dengyihao's avatar
dengyihao 已提交
1579 1580
    (*rowEntryInfoOffset)[i] = (int32_t)((*rowEntryInfoOffset)[i - 1] + sizeof(SResultRowEntryInfo) +
                                         pFuncCtx[i - 1].resDataInfo.interBufSize);
1581 1582 1583 1584
  }

  setSelectValueColumnInfo(pFuncCtx, numOfOutput);
  return pFuncCtx;
1585
}
1586 1587

// NOTE: sources columns are more than the destination SSDatablock columns.
1588 1589
// doFilter in table scan needs every column even its output is false
void relocateColumnData(SSDataBlock* pBlock, const SArray* pColMatchInfo, SArray* pCols, bool outputEveryColumn) {
1590 1591 1592 1593 1594
  size_t numOfSrcCols = taosArrayGetSize(pCols);

  int32_t i = 0, j = 0;
  while (i < numOfSrcCols && j < taosArrayGetSize(pColMatchInfo)) {
    SColumnInfoData* p = taosArrayGet(pCols, i);
H
Haojun Liao 已提交
1595
    SColMatchItem*   pmInfo = taosArrayGet(pColMatchInfo, j);
1596 1597

    if (p->info.colId == pmInfo->colId) {
H
Haojun Liao 已提交
1598
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, pmInfo->dstSlotId);
1599
      colDataAssign(pDst, p, pBlock->info.rows, &pBlock->info);
1600 1601 1602 1603 1604
      i++;
      j++;
    } else if (p->info.colId < pmInfo->colId) {
      i++;
    } else {
1605
      ASSERT(0);
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
    }
  }
}

SInterval extractIntervalInfo(const STableScanPhysiNode* pTableScanNode) {
  SInterval interval = {
      .interval = pTableScanNode->interval,
      .sliding = pTableScanNode->sliding,
      .intervalUnit = pTableScanNode->intervalUnit,
      .slidingUnit = pTableScanNode->slidingUnit,
      .offset = pTableScanNode->offset,
  };

  return interval;
}

SColumn extractColumnFromColumnNode(SColumnNode* pColNode) {
  SColumn c = {0};
H
Haojun Liao 已提交
1624

1625 1626 1627 1628 1629
  c.slotId = pColNode->slotId;
  c.colId = pColNode->colId;
  c.type = pColNode->node.resType.type;
  c.bytes = pColNode->node.resType.bytes;
  c.scale = pColNode->node.resType.scale;
1630 1631 1632 1633 1634 1635 1636
  c.precision = pColNode->node.resType.precision;
  return c;
}

int32_t initQueryTableDataCond(SQueryTableDataCond* pCond, const STableScanPhysiNode* pTableScanNode) {
  pCond->order = pTableScanNode->scanSeq[0] > 0 ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
  pCond->numOfCols = LIST_LENGTH(pTableScanNode->scan.pScanCols);
H
Haojun Liao 已提交
1637

1638
  pCond->colList = taosMemoryCalloc(pCond->numOfCols, sizeof(SColumnInfo));
dengyihao's avatar
dengyihao 已提交
1639
  pCond->pSlotList = taosMemoryMalloc(sizeof(int32_t) * pCond->numOfCols);
H
Haojun Liao 已提交
1640
  if (pCond->colList == NULL || pCond->pSlotList == NULL) {
S
Shengliang Guan 已提交
1641
    terrno = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
1642 1643
    taosMemoryFreeClear(pCond->colList);
    taosMemoryFreeClear(pCond->pSlotList);
1644 1645 1646 1647
    return terrno;
  }

  // TODO: get it from stable scan node
H
Haojun Liao 已提交
1648
  pCond->twindows = pTableScanNode->scanRange;
1649
  pCond->suid = pTableScanNode->scan.suid;
1650
  pCond->type = TIMEWINDOW_RANGE_CONTAINED;
H
Haojun Liao 已提交
1651
  pCond->startVersion = -1;
1652
  pCond->endVersion = -1;
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664

  int32_t j = 0;
  for (int32_t i = 0; i < pCond->numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pTableScanNode->scan.pScanCols, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;
    if (pColNode->colType == COLUMN_TYPE_TAG) {
      continue;
    }

    pCond->colList[j].type = pColNode->node.resType.type;
    pCond->colList[j].bytes = pColNode->node.resType.bytes;
    pCond->colList[j].colId = pColNode->colId;
H
Haojun Liao 已提交
1665 1666

    pCond->pSlotList[j] = pNode->slotId;
1667 1668 1669 1670 1671 1672 1673
    j += 1;
  }

  pCond->numOfCols = j;
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1674 1675 1676 1677
void cleanupQueryTableDataCond(SQueryTableDataCond* pCond) {
  taosMemoryFreeClear(pCond->colList);
  taosMemoryFreeClear(pCond->pSlotList);
}
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705

int32_t convertFillType(int32_t mode) {
  int32_t type = TSDB_FILL_NONE;
  switch (mode) {
    case FILL_MODE_PREV:
      type = TSDB_FILL_PREV;
      break;
    case FILL_MODE_NONE:
      type = TSDB_FILL_NONE;
      break;
    case FILL_MODE_NULL:
      type = TSDB_FILL_NULL;
      break;
    case FILL_MODE_NEXT:
      type = TSDB_FILL_NEXT;
      break;
    case FILL_MODE_VALUE:
      type = TSDB_FILL_SET_VALUE;
      break;
    case FILL_MODE_LINEAR:
      type = TSDB_FILL_LINEAR;
      break;
    default:
      type = TSDB_FILL_NONE;
  }

  return type;
}
H
Haojun Liao 已提交
1706 1707 1708

static void getInitialStartTimeWindow(SInterval* pInterval, TSKEY ts, STimeWindow* w, bool ascQuery) {
  if (ascQuery) {
1709
    *w = getAlignQueryTimeWindow(pInterval, pInterval->precision, ts);
H
Haojun Liao 已提交
1710 1711
  } else {
    // the start position of the first time window in the endpoint that spreads beyond the queried last timestamp
1712
    *w = getAlignQueryTimeWindow(pInterval, pInterval->precision, ts);
H
Haojun Liao 已提交
1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726

    int64_t key = w->skey;
    while (key < ts) {  // moving towards end
      key = taosTimeAdd(key, pInterval->sliding, pInterval->slidingUnit, pInterval->precision);
      if (key >= ts) {
        break;
      }

      w->skey = key;
    }
  }
}

static STimeWindow doCalculateTimeWindow(int64_t ts, SInterval* pInterval) {
1727
  STimeWindow w = {0};
H
Haojun Liao 已提交
1728

1729 1730
  w.skey = taosTimeTruncate(ts, pInterval, pInterval->precision);
  w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1;
H
Haojun Liao 已提交
1731 1732 1733
  return w;
}

1734
STimeWindow getFirstQualifiedTimeWindow(int64_t ts, STimeWindow* pWindow, SInterval* pInterval, int32_t order) {
1735
  int32_t factor = (order == TSDB_ORDER_ASC) ? -1 : 1;
H
Haojun Liao 已提交
1736 1737 1738

  STimeWindow win = *pWindow;
  STimeWindow save = win;
1739
  while (win.skey <= ts && win.ekey >= ts) {
H
Haojun Liao 已提交
1740 1741 1742 1743 1744 1745 1746 1747 1748
    save = win;
    win.skey = taosTimeAdd(win.skey, factor * pInterval->sliding, pInterval->slidingUnit, pInterval->precision);
    win.ekey = taosTimeAdd(win.ekey, factor * pInterval->sliding, pInterval->slidingUnit, pInterval->precision);
  }

  return save;
}

// get the correct time window according to the handled timestamp
1749
// todo refactor
H
Haojun Liao 已提交
1750 1751 1752 1753 1754 1755 1756 1757 1758
STimeWindow getActiveTimeWindow(SDiskbasedBuf* pBuf, SResultRowInfo* pResultRowInfo, int64_t ts, SInterval* pInterval,
                                int32_t order) {
  STimeWindow w = {0};
  if (pResultRowInfo->cur.pageId == -1) {  // the first window, from the previous stored value
    getInitialStartTimeWindow(pInterval, ts, &w, (order == TSDB_ORDER_ASC));
    w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1;
    return w;
  }

1759 1760 1761 1762
  SResultRow* pRow = getResultRowByPos(pBuf, &pResultRowInfo->cur, false);
  if (pRow) {
    w = pRow->win;
  }
H
Haojun Liao 已提交
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774
  // in case of typical time window, we can calculate time window directly.
  if (w.skey > ts || w.ekey < ts) {
    w = doCalculateTimeWindow(ts, pInterval);
  }

  if (pInterval->interval != pInterval->sliding) {
    // it is an sliding window query, in which sliding value is not equalled to
    // interval value, and we need to find the first qualified time window.
    w = getFirstQualifiedTimeWindow(ts, &w, pInterval, order);
  }

  return w;
1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
}

bool hasLimitOffsetInfo(SLimitInfo* pLimitInfo) {
  return (pLimitInfo->limit.limit != -1 || pLimitInfo->limit.offset != -1 || pLimitInfo->slimit.limit != -1 ||
          pLimitInfo->slimit.offset != -1);
}

void initLimitInfo(const SNode* pLimit, const SNode* pSLimit, SLimitInfo* pLimitInfo) {
  SLimit limit = {.limit = getLimit(pLimit), .offset = getOffset(pLimit)};
  SLimit slimit = {.limit = getLimit(pSLimit), .offset = getOffset(pSLimit)};

  pLimitInfo->limit = limit;
1787
  pLimitInfo->slimit = slimit;
1788 1789
  pLimitInfo->remainOffset = limit.offset;
  pLimitInfo->remainGroupOffset = slimit.offset;
1790
}
H
Haojun Liao 已提交
1791

1792 1793 1794 1795 1796
void resetLimitInfoForNextGroup(SLimitInfo* pLimitInfo) {
  pLimitInfo->numOfOutputRows = 0;
  pLimitInfo->remainOffset = pLimitInfo->limit.offset;
}

H
Haojun Liao 已提交
1797
uint64_t tableListGetSize(const STableListInfo* pTableList) {
1798
  ASSERT(taosArrayGetSize(pTableList->pTableList) == taosHashGetSize(pTableList->map));
H
Haojun Liao 已提交
1799 1800 1801
  return taosArrayGetSize(pTableList->pTableList);
}

dengyihao's avatar
dengyihao 已提交
1802
uint64_t tableListGetSuid(const STableListInfo* pTableList) { return pTableList->suid; }
H
Haojun Liao 已提交
1803 1804 1805 1806 1807 1808 1809 1810 1811

STableKeyInfo* tableListGetInfo(const STableListInfo* pTableList, int32_t index) {
  if (taosArrayGetSize(pTableList->pTableList) == 0) {
    return NULL;
  }

  return taosArrayGet(pTableList->pTableList, index);
}

H
Haojun Liao 已提交
1812 1813
uint64_t getTableGroupId(const STableListInfo* pTableList, uint64_t tableUid) {
  int32_t* slot = taosHashGet(pTableList->map, &tableUid, sizeof(tableUid));
1814
  ASSERT(pTableList->map != NULL && slot != NULL);
H
Haojun Liao 已提交
1815 1816

  STableKeyInfo* pKeyInfo = taosArrayGet(pTableList->pTableList, *slot);
1817
  ASSERT(pKeyInfo->uid == tableUid);
H
Haojun Liao 已提交
1818 1819 1820 1821

  return pKeyInfo->groupId;
}

H
Haojun Liao 已提交
1822
// TODO handle the group offset info, fix it, the rule of group output will be broken by this function
H
Haojun Liao 已提交
1823
int32_t tableListAddTableInfo(STableListInfo* pTableList, uint64_t uid, uint64_t gid) {
H
Haojun Liao 已提交
1824
  if (pTableList->map == NULL) {
1825
    ASSERT(taosArrayGetSize(pTableList->pTableList) == 0);
1826
    pTableList->map = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_ENTRY_LOCK);
H
Haojun Liao 已提交
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
  }

  STableKeyInfo keyInfo = {.uid = uid, .groupId = gid};
  taosArrayPush(pTableList->pTableList, &keyInfo);

  int32_t slot = (int32_t)taosArrayGetSize(pTableList->pTableList) - 1;
  taosHashPut(pTableList->map, &uid, sizeof(uid), &slot, sizeof(slot));

  qDebug("uid:%" PRIu64 ", groupId:%" PRIu64 " added into table list, slot:%d, total:%d", uid, gid, slot, slot + 1);
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1839
int32_t tableListGetGroupList(const STableListInfo* pTableList, int32_t ordinalGroupIndex, STableKeyInfo** pKeyInfo,
dengyihao's avatar
dengyihao 已提交
1840
                              int32_t* size) {
H
Haojun Liao 已提交
1841
  int32_t total = tableListGetOutputGroups(pTableList);
H
Haojun Liao 已提交
1842 1843 1844 1845 1846 1847 1848
  if (ordinalGroupIndex < 0 || ordinalGroupIndex >= total) {
    return TSDB_CODE_INVALID_PARA;
  }

  // here handle two special cases:
  // 1. only one group exists, and 2. one table exists for each group.
  if (total == 1) {
H
Haojun Liao 已提交
1849
    *size = tableListGetSize(pTableList);
dengyihao's avatar
dengyihao 已提交
1850
    *pKeyInfo = (*size == 0) ? NULL : taosArrayGet(pTableList->pTableList, 0);
H
Haojun Liao 已提交
1851
    return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1852
  } else if (total == tableListGetSize(pTableList)) {
H
Haojun Liao 已提交
1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
    *size = 1;
    *pKeyInfo = taosArrayGet(pTableList->pTableList, ordinalGroupIndex);
    return TSDB_CODE_SUCCESS;
  }

  int32_t offset = pTableList->groupOffset[ordinalGroupIndex];
  if (ordinalGroupIndex < total - 1) {
    *size = pTableList->groupOffset[offset + 1] - pTableList->groupOffset[offset];
  } else {
    *size = total - pTableList->groupOffset[offset] - 1;
  }

  *pKeyInfo = taosArrayGet(pTableList->pTableList, offset);
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1869
int32_t tableListGetOutputGroups(const STableListInfo* pTableList) { return pTableList->numOfOuputGroups; }
H
Haojun Liao 已提交
1870 1871 1872

bool oneTableForEachGroup(const STableListInfo* pTableList) { return pTableList->oneTableForEachGroup; }

H
Haojun Liao 已提交
1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
STableListInfo* tableListCreate() {
  STableListInfo* pListInfo = taosMemoryCalloc(1, sizeof(STableListInfo));
  if (pListInfo == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  pListInfo->pTableList = taosArrayInit(4, sizeof(STableKeyInfo));
  if (pListInfo->pTableList == NULL) {
    goto _error;
  }

1885
  pListInfo->map = taosHashInit(1024, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false, HASH_ENTRY_LOCK);
H
Haojun Liao 已提交
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
  if (pListInfo->map == NULL) {
    goto _error;
  }

  pListInfo->numOfOuputGroups = 1;
  return pListInfo;

_error:
  tableListDestroy(pListInfo);
  terrno = TSDB_CODE_OUT_OF_MEMORY;
  return NULL;
}

void* tableListDestroy(STableListInfo* pTableListInfo) {
1900 1901 1902
  if (pTableListInfo == NULL) {
    return NULL;
  }
H
Haojun Liao 已提交
1903

H
Haojun Liao 已提交
1904 1905
  pTableListInfo->pTableList = taosArrayDestroy(pTableListInfo->pTableList);
  taosMemoryFreeClear(pTableListInfo->groupOffset);
H
Haojun Liao 已提交
1906

H
Haojun Liao 已提交
1907 1908 1909 1910 1911 1912 1913 1914 1915
  taosHashCleanup(pTableListInfo->map);

  pTableListInfo->pTableList = NULL;
  pTableListInfo->map = NULL;
  taosMemoryFree(pTableListInfo);
  return NULL;
}

void tableListClear(STableListInfo* pTableListInfo) {
H
Haojun Liao 已提交
1916 1917 1918 1919
  if (pTableListInfo == NULL) {
    return;
  }

H
Haojun Liao 已提交
1920 1921 1922 1923 1924 1925 1926 1927
  taosArrayClear(pTableListInfo->pTableList);
  taosHashClear(pTableListInfo->map);
  taosMemoryFree(pTableListInfo->groupOffset);
  pTableListInfo->numOfOuputGroups = 1;
  pTableListInfo->oneTableForEachGroup = false;
}

static int32_t orderbyGroupIdComparFn(const void* p1, const void* p2) {
dengyihao's avatar
dengyihao 已提交
1928 1929
  STableKeyInfo* pInfo1 = (STableKeyInfo*)p1;
  STableKeyInfo* pInfo2 = (STableKeyInfo*)p2;
H
Haojun Liao 已提交
1930 1931 1932 1933

  if (pInfo1->groupId == pInfo2->groupId) {
    return 0;
  } else {
dengyihao's avatar
dengyihao 已提交
1934
    return pInfo1->groupId < pInfo2->groupId ? -1 : 1;
H
Haojun Liao 已提交
1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
  }
}

static int32_t sortTableGroup(STableListInfo* pTableListInfo) {
  taosArraySort(pTableListInfo->pTableList, orderbyGroupIdComparFn);
  int32_t size = taosArrayGetSize(pTableListInfo->pTableList);

  SArray* pList = taosArrayInit(4, sizeof(int32_t));

  STableKeyInfo* pInfo = taosArrayGet(pTableListInfo->pTableList, 0);
dengyihao's avatar
dengyihao 已提交
1945
  uint64_t       gid = pInfo->groupId;
1946

H
Haojun Liao 已提交
1947 1948
  int32_t start = 0;
  taosArrayPush(pList, &start);
1949

dengyihao's avatar
dengyihao 已提交
1950
  for (int32_t i = 1; i < size; ++i) {
H
Haojun Liao 已提交
1951 1952 1953 1954 1955 1956 1957 1958 1959
    pInfo = taosArrayGet(pTableListInfo->pTableList, i);
    if (pInfo->groupId != gid) {
      taosArrayPush(pList, &i);
      gid = pInfo->groupId;
    }
  }

  pTableListInfo->numOfOuputGroups = taosArrayGetSize(pList);
  pTableListInfo->groupOffset = taosMemoryMalloc(sizeof(int32_t) * pTableListInfo->numOfOuputGroups);
H
Haojun Liao 已提交
1960 1961 1962 1963 1964
  if (pTableListInfo->groupOffset == NULL) {
    taosArrayDestroy(pList);
    return TSDB_CODE_OUT_OF_MEMORY;
  }

H
Haojun Liao 已提交
1965 1966 1967 1968 1969
  memcpy(pTableListInfo->groupOffset, taosArrayGet(pList, 0), sizeof(int32_t) * pTableListInfo->numOfOuputGroups);
  taosArrayDestroy(pList);
  return TDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
1970 1971
int32_t buildGroupIdMapForAllTables(STableListInfo* pTableListInfo, SReadHandle* pHandle, SNodeList* group,
                                    bool groupSort) {
H
Haojun Liao 已提交
1972
  int32_t code = TSDB_CODE_SUCCESS;
1973
  ASSERT(pTableListInfo->map != NULL);
H
Haojun Liao 已提交
1974

dengyihao's avatar
dengyihao 已提交
1975
  bool   groupByTbname = groupbyTbname(group);
H
Haojun Liao 已提交
1976 1977 1978 1979
  size_t numOfTables = taosArrayGetSize(pTableListInfo->pTableList);
  if (group == NULL || groupByTbname) {
    for (int32_t i = 0; i < numOfTables; i++) {
      STableKeyInfo* info = taosArrayGet(pTableListInfo->pTableList, i);
dengyihao's avatar
dengyihao 已提交
1980
      info->groupId = groupByTbname ? info->uid : 0;
H
Haojun Liao 已提交
1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003
    }

    pTableListInfo->oneTableForEachGroup = groupByTbname;

    if (groupSort && groupByTbname) {
      taosArraySort(pTableListInfo->pTableList, orderbyGroupIdComparFn);
      pTableListInfo->numOfOuputGroups = numOfTables;
    } else {
      pTableListInfo->numOfOuputGroups = 1;
    }
  } else {
    code = getColInfoResultForGroupby(pHandle->meta, group, pTableListInfo);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    if (groupSort) {
      code = sortTableGroup(pTableListInfo);
    }
  }

  // add all table entry in the hash map
  size_t size = taosArrayGetSize(pTableListInfo->pTableList);
dengyihao's avatar
dengyihao 已提交
2004
  for (int32_t i = 0; i < size; ++i) {
H
Haojun Liao 已提交
2005 2006 2007 2008 2009 2010 2011 2012 2013
    STableKeyInfo* p = taosArrayGet(pTableListInfo->pTableList, i);
    taosHashPut(pTableListInfo->map, &p->uid, sizeof(uint64_t), &i, sizeof(int32_t));
  }

  return code;
}

int32_t createScanTableListInfo(SScanPhysiNode* pScanNode, SNodeList* pGroupTags, bool groupSort, SReadHandle* pHandle,
                                STableListInfo* pTableListInfo, SNode* pTagCond, SNode* pTagIndexCond,
H
Haojun Liao 已提交
2014
                                SExecTaskInfo* pTaskInfo) {
dengyihao's avatar
dengyihao 已提交
2015
  int64_t     st = taosGetTimestampUs();
H
Haojun Liao 已提交
2016
  const char* idStr = GET_TASKID(pTaskInfo);
H
Haojun Liao 已提交
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028

  if (pHandle == NULL) {
    qError("invalid handle, in creating operator tree, %s", idStr);
    return TSDB_CODE_INVALID_PARA;
  }

  int32_t code = getTableList(pHandle->meta, pHandle->vnode, pScanNode, pTagCond, pTagIndexCond, pTableListInfo);
  if (code != TSDB_CODE_SUCCESS) {
    qError("failed to getTableList, code: %s", tstrerror(code));
    return code;
  }

H
Haojun Liao 已提交
2029
  int32_t numOfTables = taosArrayGetSize(pTableListInfo->pTableList);
2030
  ASSERT(pTableListInfo->numOfOuputGroups == 1);
H
Haojun Liao 已提交
2031 2032

  int64_t st1 = taosGetTimestampUs();
H
Haojun Liao 已提交
2033
  pTaskInfo->cost.extractListTime = (st1 - st) / 1000.0;
H
Haojun Liao 已提交
2034 2035
  qDebug("extract queried table list completed, %d tables, elapsed time:%.2f ms %s", numOfTables,
         pTaskInfo->cost.extractListTime, idStr);
H
Haojun Liao 已提交
2036

H
Haojun Liao 已提交
2037
  if (numOfTables == 0) {
H
Haojun Liao 已提交
2038 2039 2040 2041
    qDebug("no table qualified for query, %s" PRIx64, idStr);
    return TSDB_CODE_SUCCESS;
  }

2042
  code = buildGroupIdMapForAllTables(pTableListInfo, pHandle, pGroupTags, groupSort);
H
Haojun Liao 已提交
2043 2044 2045 2046
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

dengyihao's avatar
dengyihao 已提交
2047
  pTaskInfo->cost.groupIdMapTime = (taosGetTimestampUs() - st1) / 1000.0;
H
Haojun Liao 已提交
2048
  qDebug("generate group id map completed, elapsed time:%.2f ms %s", pTaskInfo->cost.groupIdMapTime, idStr);
H
Haojun Liao 已提交
2049 2050

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2051
}
H
Haojun Liao 已提交
2052 2053 2054 2055 2056 2057 2058 2059 2060

void printDataBlock(SSDataBlock* pBlock, const char* flag) {
  if (!pBlock || pBlock->info.rows == 0) {
    qDebug("===stream===printDataBlock: Block is Null or Empty");
    return;
  }
  char* pBuf = NULL;
  qDebug("%s", dumpBlockData(pBlock, flag, &pBuf));
  taosMemoryFree(pBuf);
dengyihao's avatar
dengyihao 已提交
2061
}