executil.c 30.4 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/>.
 */

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

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

dengyihao's avatar
dengyihao 已提交
29 30
void initResultRowInfo(SResultRowInfo* pResultRowInfo) {
  pResultRowInfo->size = 0;
31
  pResultRowInfo->cur.pageId = -1;
32 33
}

dengyihao's avatar
dengyihao 已提交
34
void cleanupResultRowInfo(SResultRowInfo* pResultRowInfo) {
H
Haojun Liao 已提交
35
  if (pResultRowInfo == NULL) {
36 37
    return;
  }
H
Haojun Liao 已提交
38

dengyihao's avatar
dengyihao 已提交
39 40 41 42
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
    //    if (pResultRowInfo->pResult[i]) {
    //      taosMemoryFreeClear(pResultRowInfo->pResult[i]->key);
    //    }
43
  }
44 45
}

dengyihao's avatar
dengyihao 已提交
46 47
void closeAllResultRows(SResultRowInfo* pResultRowInfo) {
  // do nothing
48 49
}

dengyihao's avatar
dengyihao 已提交
50
bool isResultRowClosed(SResultRow* pRow) { return (pRow->closed == true); }
51

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

H
Haojun Liao 已提交
54
// TODO refactor: use macro
55
SResultRowEntryInfo* getResultEntryInfo(const SResultRow* pRow, int32_t index, const int32_t* offset) {
H
Haojun Liao 已提交
56
  assert(index >= 0 && offset != NULL);
dengyihao's avatar
dengyihao 已提交
57
  return (SResultRowEntryInfo*)((char*)pRow->pEntryInfo + offset[index]);
H
Haojun Liao 已提交
58 59
}

60 61 62
size_t getResultRowSize(SqlFunctionCtx* pCtx, int32_t numOfOutput) {
  int32_t rowSize = (numOfOutput * sizeof(SResultRowEntryInfo)) + sizeof(SResultRow);

dengyihao's avatar
dengyihao 已提交
63
  for (int32_t i = 0; i < numOfOutput; ++i) {
64 65 66
    rowSize += pCtx[i].resDataInfo.interBufSize;
  }

dengyihao's avatar
dengyihao 已提交
67
  rowSize +=
68
      (numOfOutput * sizeof(bool));  // expand rowSize to mark if col is null for top/bottom result(doSaveTupleData)
69
  return rowSize;
70 71
}

H
Haojun Liao 已提交
72 73 74
void cleanupGroupResInfo(SGroupResInfo* pGroupResInfo) {
  assert(pGroupResInfo != NULL);

H
Haojun Liao 已提交
75 76 77 78 79 80
  for(int32_t i = 0; i < taosArrayGetSize(pGroupResInfo->pRows); ++i) {
    SResKeyPos* pRes = taosArrayGetP(pGroupResInfo->pRows, i);
    taosMemoryFree(pRes);
  }

  pGroupResInfo->pRows = taosArrayDestroy(pGroupResInfo->pRows);
dengyihao's avatar
dengyihao 已提交
81
  pGroupResInfo->index = 0;
H
Haojun Liao 已提交
82 83
}

5
54liuyao 已提交
84
int32_t resultrowComparAsc(const void* p1, const void* p2) {
dengyihao's avatar
dengyihao 已提交
85 86
  SResKeyPos* pp1 = *(SResKeyPos**)p1;
  SResKeyPos* pp2 = *(SResKeyPos**)p2;
87 88

  if (pp1->groupId == pp2->groupId) {
dengyihao's avatar
dengyihao 已提交
89 90
    int64_t pts1 = *(int64_t*)pp1->key;
    int64_t pts2 = *(int64_t*)pp2->key;
91 92 93 94

    if (pts1 == pts2) {
      return 0;
    } else {
dengyihao's avatar
dengyihao 已提交
95
      return pts1 < pts2 ? -1 : 1;
96 97
    }
  } else {
dengyihao's avatar
dengyihao 已提交
98
    return pp1->groupId < pp2->groupId ? -1 : 1;
99 100 101
  }
}

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

void initGroupedResultInfo(SGroupResInfo* pGroupResInfo, SHashObj* pHashmap, int32_t order) {
H
Haojun Liao 已提交
105 106 107 108
  if (pGroupResInfo->pRows != NULL) {
    taosArrayDestroy(pGroupResInfo->pRows);
  }

109 110 111 112 113
  // extract the result rows information from the hash map
  void* pData = NULL;
  pGroupResInfo->pRows = taosArrayInit(10, POINTER_BYTES);

  size_t keyLen = 0;
dengyihao's avatar
dengyihao 已提交
114
  while ((pData = taosHashIterate(pHashmap, pData)) != NULL) {
115 116 117 118
    void* key = taosHashGetKey(pData, &keyLen);

    SResKeyPos* p = taosMemoryMalloc(keyLen + sizeof(SResultRowPosition));

dengyihao's avatar
dengyihao 已提交
119 120
    p->groupId = *(uint64_t*)key;
    p->pos = *(SResultRowPosition*)pData;
121
    memcpy(p->key, (char*)key + sizeof(uint64_t), keyLen - sizeof(uint64_t));
122 123 124
    taosArrayPush(pGroupResInfo->pRows, &p);
  }

125
  if (order == TSDB_ORDER_ASC || order == TSDB_ORDER_DESC) {
dengyihao's avatar
dengyihao 已提交
126
    __compar_fn_t fn = (order == TSDB_ORDER_ASC) ? resultrowComparAsc : resultrowComparDesc;
wafwerar's avatar
wafwerar 已提交
127
    taosSort(pGroupResInfo->pRows->pData, taosArrayGetSize(pGroupResInfo->pRows), POINTER_BYTES, fn);
128 129
  }

H
Haojun Liao 已提交
130
  pGroupResInfo->index = 0;
H
Haojun Liao 已提交
131 132 133
  assert(pGroupResInfo->index <= getNumOfTotalRes(pGroupResInfo));
}

H
Haojun Liao 已提交
134 135
void initMultiResInfoFromArrayList(SGroupResInfo* pGroupResInfo, SArray* pArrayList) {
  if (pGroupResInfo->pRows != NULL) {
5
54liuyao 已提交
136
    taosArrayDestroyP(pGroupResInfo->pRows, taosMemoryFree);
H
Haojun Liao 已提交
137 138
  }

139
  pGroupResInfo->pRows = pArrayList;
H
Haojun Liao 已提交
140 141 142 143
  pGroupResInfo->index = 0;
  ASSERT(pGroupResInfo->index <= getNumOfTotalRes(pGroupResInfo));
}

144
bool hasDataInGroupInfo(SGroupResInfo* pGroupResInfo) {
H
Haojun Liao 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157
  if (pGroupResInfo->pRows == NULL) {
    return false;
  }

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

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

dengyihao's avatar
dengyihao 已提交
158
  return (int32_t)taosArrayGetSize(pGroupResInfo->pRows);
H
Haojun Liao 已提交
159 160
}

161
SArray* createSortInfo(SNodeList* pNodeList) {
162 163 164 165 166 167
  size_t numOfCols = 0;
  if (pNodeList != NULL) {
    numOfCols = LIST_LENGTH(pNodeList);
  } else {
    numOfCols = 0;
  }
168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
  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;
}

SSDataBlock* createResDataBlock(SDataBlockDescNode* pNode) {
  int32_t numOfCols = LIST_LENGTH(pNode->pSlots);
H
Haojun Liao 已提交
190

191
  SSDataBlock* pBlock = createDataBlock();
H
Haojun Liao 已提交
192

193 194
  pBlock->info.blockId = pNode->dataBlockId;
  pBlock->info.type = STREAM_INVALID;
5
54liuyao 已提交
195
  pBlock->info.calWin = (STimeWindow){.skey = INT64_MIN, .ekey = INT64_MAX};
H
Haojun Liao 已提交
196

197
  for (int32_t i = 0; i < numOfCols; ++i) {
dengyihao's avatar
dengyihao 已提交
198
    SSlotDescNode* pDescNode = (SSlotDescNode*)nodesListGetNode(pNode->pSlots, i);
199 200 201
    /*if (!pDescNode->output) {  // todo disable it temporarily*/
    /*continue;*/
    /*}*/
202

dengyihao's avatar
dengyihao 已提交
203 204
    SColumnInfoData idata =
        createColumnInfoData(pDescNode->dataType.type, pDescNode->dataType.bytes, pDescNode->slotId);
205 206 207
    idata.info.scale = pDescNode->dataType.scale;
    idata.info.precision = pDescNode->dataType.precision;

208
    blockDataAppendColInfo(pBlock, &idata);
H
Haojun Liao 已提交
209 210
  }

211 212 213
  return pBlock;
}

wmmhello's avatar
wmmhello 已提交
214 215
EDealRes doTranslateTagExpr(SNode** pNode, void* pContext) {
  SMetaReader* mr = (SMetaReader*)pContext;
dengyihao's avatar
dengyihao 已提交
216
  if (nodeType(*pNode) == QUERY_NODE_COLUMN) {
wmmhello's avatar
wmmhello 已提交
217 218
    SColumnNode* pSColumnNode = *(SColumnNode**)pNode;

dengyihao's avatar
dengyihao 已提交
219
    SValueNode* res = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE);
wmmhello's avatar
wmmhello 已提交
220 221 222 223 224 225 226 227 228 229 230 231
    if (NULL == res) {
      return DEAL_RES_ERROR;
    }

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

    STagVal tagVal = {0};
    tagVal.cid = pSColumnNode->colId;
    const char* p = metaGetTableTagVal(&mr->me, pSColumnNode->node.resType.type, &tagVal);
    if (p == NULL) {
      res->node.resType.type = TSDB_DATA_TYPE_NULL;
dengyihao's avatar
dengyihao 已提交
232 233
    } else if (pSColumnNode->node.resType.type == TSDB_DATA_TYPE_JSON) {
      int32_t len = ((const STag*)p)->len;
wmmhello's avatar
wmmhello 已提交
234 235 236 237 238 239 240 241 242 243 244
      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 已提交
245 246 247 248
  } 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 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
      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;
}

268
int32_t isTableOk(STableKeyInfo* info, SNode* pTagCond, void* metaHandle, bool* pQualified) {
dengyihao's avatar
dengyihao 已提交
269
  SMetaReader mr = {0};
wmmhello's avatar
wmmhello 已提交
270 271 272
  metaReaderInit(&mr, metaHandle, 0);
  metaGetTableEntryByUid(&mr, info->uid);

dengyihao's avatar
dengyihao 已提交
273
  SNode* pTagCondTmp = nodesCloneNode(pTagCond);
wmmhello's avatar
wmmhello 已提交
274 275 276 277 278 279 280

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

  SNode*  pNew = NULL;
  int32_t code = scalarCalculateConstants(pTagCondTmp, &pNew);
  if (TSDB_CODE_SUCCESS != code) {
wmmhello's avatar
wmmhello 已提交
281
    terrno = code;
wmmhello's avatar
wmmhello 已提交
282
    nodesDestroyNode(pTagCondTmp);
283 284 285
    *pQualified = false;

    return code;
wmmhello's avatar
wmmhello 已提交
286 287 288
  }

  ASSERT(nodeType(pNew) == QUERY_NODE_VALUE);
dengyihao's avatar
dengyihao 已提交
289
  SValueNode* pValue = (SValueNode*)pNew;
wmmhello's avatar
wmmhello 已提交
290 291

  ASSERT(pValue->node.resType.type == TSDB_DATA_TYPE_BOOL);
292 293
  *pQualified = pValue->datum.b;

wmmhello's avatar
wmmhello 已提交
294
  nodesDestroyNode(pNew);
295
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
296 297
}

298
int32_t getTableList(void* metaHandle, void* pVnode, SScanPhysiNode* pScanNode, SNode* pTagCond, SNode* pTagIndexCond, STableListInfo* pListInfo) {
299
  int32_t code = TSDB_CODE_SUCCESS;
300

301
  pListInfo->pTableList = taosArrayInit(8, sizeof(STableKeyInfo));
302 303 304
  if (pListInfo->pTableList == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
305 306 307

  uint64_t tableUid = pScanNode->uid;

D
dapan1121 已提交
308
  pListInfo->suid = pScanNode->suid;
dengyihao's avatar
dengyihao 已提交
309

310
  if (pScanNode->tableType == TSDB_SUPER_TABLE) {
wmmhello's avatar
wmmhello 已提交
311
    if (pTagIndexCond) {
312 313 314
      SIndexMetaArg metaArg = {
          .metaEx = metaHandle, .idx = tsdbGetIdx(metaHandle), .ivtIdx = tsdbGetIvtIdx(metaHandle), .suid = tableUid};

dengyihao's avatar
dengyihao 已提交
315 316 317 318
      SArray*       res = taosArrayInit(8, sizeof(uint64_t));
      SIdxFltStatus status = SFLT_NOT_INDEX;
      code = doFilterTag(pTagIndexCond, &metaArg, res, &status);
      if (code != 0 || status == SFLT_NOT_INDEX) {
wmmhello's avatar
wmmhello 已提交
319 320
        qError("failed to get tableIds from index, reason:%s, suid:%" PRIu64, tstrerror(code), tableUid);
//        code = TSDB_CODE_INDEX_REBUILDING;
321
        code = vnodeGetAllTableList(pVnode, tableUid, pListInfo->pTableList);
322
      } else {
S
Shengliang Guan 已提交
323
        qDebug("success to get tableIds, size:%d, suid:%" PRIu64, (int)taosArrayGetSize(res), tableUid);
324 325 326
      }

      for (int i = 0; i < taosArrayGetSize(res); i++) {
S
slzhou 已提交
327
        STableKeyInfo info = {.lastKey = TSKEY_INITIAL_VAL, .uid = *(uint64_t*)taosArrayGet(res, i), .groupId = 0};
328 329 330 331
        taosArrayPush(pListInfo->pTableList, &info);
      }
      taosArrayDestroy(res);
    } else {
332
      code = vnodeGetAllTableList(pVnode, tableUid, pListInfo->pTableList);
333
    }
wmmhello's avatar
wmmhello 已提交
334

wmmhello's avatar
wmmhello 已提交
335
    if (code != TSDB_CODE_SUCCESS) {
S
Shengliang Guan 已提交
336
      qError("failed to get tableIds, reason:%s, suid:%" PRIu64, tstrerror(code), tableUid);
wmmhello's avatar
wmmhello 已提交
337 338 339
      terrno = code;
      return code;
    }
L
Liu Jicong 已提交
340
  } else {  // Create one table group.
S
slzhou 已提交
341
    STableKeyInfo info = {.lastKey = 0, .uid = tableUid, .groupId = 0};
342
    taosArrayPush(pListInfo->pTableList, &info);
H
Haojun Liao 已提交
343
  }
344

wmmhello's avatar
wmmhello 已提交
345 346 347 348
  if (pTagCond) {
    int32_t i = 0;
    while (i < taosArrayGetSize(pListInfo->pTableList)) {
      STableKeyInfo* info = taosArrayGet(pListInfo->pTableList, i);
349 350 351 352 353 354 355 356

      bool qualified = true;
      code = isTableOk(info, pTagCond, metaHandle, &qualified);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      if (!qualified) {
wmmhello's avatar
wmmhello 已提交
357 358 359 360 361 362 363
        taosArrayRemove(pListInfo->pTableList, i);
        continue;
      }
      i++;
    }
  }

wmmhello's avatar
wmmhello 已提交
364
  pListInfo->pGroupList = taosArrayInit(4, POINTER_BYTES);
365
  if (pListInfo->pGroupList == NULL) {
366 367
    return TSDB_CODE_OUT_OF_MEMORY;
  }
wmmhello's avatar
wmmhello 已提交
368

dengyihao's avatar
dengyihao 已提交
369
  // put into list as default group, remove it if grouping sorting is required later
wmmhello's avatar
wmmhello 已提交
370
  taosArrayPush(pListInfo->pGroupList, &pListInfo->pTableList);
371 372
  return code;
}
H
Haojun Liao 已提交
373

374
SArray* extractPartitionColInfo(SNodeList* pNodeList) {
dengyihao's avatar
dengyihao 已提交
375
  if (!pNodeList) {
376 377
    return NULL;
  }
H
Haojun Liao 已提交
378

379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
  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 已提交
400

401
  return pList;
H
Haojun Liao 已提交
402 403
}

404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
SArray* extractColMatchInfo(SNodeList* pNodeList, SDataBlockDescNode* pOutputNodeList, int32_t* numOfOutputCols,
                            int32_t type) {
  size_t  numOfCols = LIST_LENGTH(pNodeList);
  SArray* pList = taosArrayInit(numOfCols, sizeof(SColMatchInfo));
  if (pList == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return NULL;
  }

  for (int32_t i = 0; i < numOfCols; ++i) {
    STargetNode* pNode = (STargetNode*)nodesListGetNode(pNodeList, i);
    SColumnNode* pColNode = (SColumnNode*)pNode->pExpr;

    SColMatchInfo c = {0};
    c.output = true;
dengyihao's avatar
dengyihao 已提交
419
    c.colId = pColNode->colId;
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
    c.srcSlotId = pColNode->slotId;
    c.matchType = type;
    c.targetSlotId = pNode->slotId;
    taosArrayPush(pList, &c);
  }

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

438 439 440 441 442 443 444
    SColMatchInfo* info = NULL;
    for (int32_t j = 0; j < taosArrayGetSize(pList); ++j) {
      info = taosArrayGet(pList, j);
      if (info->targetSlotId == pNode->slotId) {
        break;
      }
    }
445

446 447 448 449 450
    if (pNode->output) {
      (*numOfOutputCols) += 1;
    } else {
      info->output = false;
    }
451
  }
452 453

  return pList;
454 455
}

456 457 458 459 460 461 462 463 464 465 466 467
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;
  strncpy(s.name, name, tListLen(s.name));

  return s;
}
468

469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 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 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
static SColumn* createColumn(int32_t blockId, int32_t slotId, int32_t colId, SDataType* pType) {
  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;

  return pCol;
}

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

    pExp->pExpr = taosMemoryCalloc(1, sizeof(tExprNode));
    pExp->pExpr->_function.num = 1;
    pExp->pExpr->_function.functionId = -1;

    int32_t type = nodeType(pTargetNode->pExpr);
    // it is a project query, or group by column
    if (type == QUERY_NODE_COLUMN) {
      pExp->pExpr->nodeType = QUERY_NODE_COLUMN;
      SColumnNode* pColNode = (SColumnNode*)pTargetNode->pExpr;

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

      SDataType* pType = &pColNode->node.resType;
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pColNode->colName);
      pExp->base.pParam[0].pCol = createColumn(pColNode->dataBlockId, pColNode->slotId, pColNode->colId, pType);
      pExp->base.pParam[0].type = FUNC_PARAM_TYPE_COLUMN;
    } else if (type == QUERY_NODE_VALUE) {
      pExp->pExpr->nodeType = QUERY_NODE_VALUE;
      SValueNode* pValNode = (SValueNode*)pTargetNode->pExpr;

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

      SDataType* pType = &pValNode->node.resType;
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pValNode->node.aliasName);
      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;
      SFunctionNode* pFuncNode = (SFunctionNode*)pTargetNode->pExpr;

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

      pExp->pExpr->_function.functionId = pFuncNode->funcId;
      pExp->pExpr->_function.pFunctNode = pFuncNode;

      strncpy(pExp->pExpr->_function.functionName, pFuncNode->functionName,
              tListLen(pExp->pExpr->_function.functionName));
#if 1
      // todo refactor: add the parameter for tbname function
      if (strcmp(pExp->pExpr->_function.functionName, "tbname") == 0) {
        pFuncNode->pParameterList = nodesMakeList();
        ASSERT(LIST_LENGTH(pFuncNode->pParameterList) == 0);
        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);
        } 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;
      SOperatorNode* pNode = (SOperatorNode*)pTargetNode->pExpr;

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

      SDataType* pType = &pNode->node.resType;
      pExp->base.resSchema = createResSchema(pType->type, pType->bytes, pTargetNode->slotId, pType->scale,
                                             pType->precision, pNode->node.aliasName);
      pExp->pExpr->_optrRoot.pRootNode = pTargetNode->pExpr;
    } else {
      ASSERT(0);
    }
  }

  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) {
    return TSDB_CODE_QRY_OUT_OF_MEMORY;
  }

  for (int32_t i = 0; i < numOfOutput; ++i) {
H
Haojun Liao 已提交
612 613 614
    const char* pName = pCtx[i].pExpr->pExpr->_function.functionName;
    if ((strcmp(pName, "_select_value") == 0) ||
        (strcmp(pName, "_group_key") == 0)) {
615 616 617 618 619
      pValCtx[num++] = &pCtx[i];
    } else if (fmIsSelectFunc(pCtx[i].functionId)) {
      p = &pCtx[i];
    }
  }
H
Haojun Liao 已提交
620

621
#ifdef BUF_PAGE_DEBUG
wmmhello's avatar
wmmhello 已提交
622
  qDebug("page_setSelect num:%d", num);
623
#endif
624 625 626
  if (p != NULL) {
    p->subsidiaries.pCtx = pValCtx;
    p->subsidiaries.num = num;
627
  } else {
628
    taosMemoryFreeClear(pValCtx);
629
  }
630 631

  return TSDB_CODE_SUCCESS;
632 633
}

634
SqlFunctionCtx* createSqlFunctionCtx(SExprInfo* pExprInfo, int32_t numOfOutput, int32_t** rowEntryInfoOffset) {
635 636 637 638
  SqlFunctionCtx* pFuncCtx = (SqlFunctionCtx*)taosMemoryCalloc(numOfOutput, sizeof(SqlFunctionCtx));
  if (pFuncCtx == NULL) {
    return NULL;
  }
639

640 641
  *rowEntryInfoOffset = taosMemoryCalloc(numOfOutput, sizeof(int32_t));
  if (*rowEntryInfoOffset == 0) {
642 643 644 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 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
    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->curBufPage = -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;
          strncpy(pCtx->udfName, udfName, strlen(udfName));
          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->increase = false;

    pCtx->param = pFunct->pParam;
  }

  for (int32_t i = 1; i < numOfOutput; ++i) {
dengyihao's avatar
dengyihao 已提交
700 701
    (*rowEntryInfoOffset)[i] = (int32_t)((*rowEntryInfoOffset)[i - 1] + sizeof(SResultRowEntryInfo) +
                                         pFuncCtx[i - 1].resDataInfo.interBufSize);
702 703 704 705
  }

  setSelectValueColumnInfo(pFuncCtx, numOfOutput);
  return pFuncCtx;
706
}
707 708

// NOTE: sources columns are more than the destination SSDatablock columns.
709 710
// doFilter in table scan needs every column even its output is false
void relocateColumnData(SSDataBlock* pBlock, const SArray* pColMatchInfo, SArray* pCols, bool outputEveryColumn) {
711 712 713 714 715 716
  size_t numOfSrcCols = taosArrayGetSize(pCols);

  int32_t i = 0, j = 0;
  while (i < numOfSrcCols && j < taosArrayGetSize(pColMatchInfo)) {
    SColumnInfoData* p = taosArrayGet(pCols, i);
    SColMatchInfo*   pmInfo = taosArrayGet(pColMatchInfo, j);
717
    if (!outputEveryColumn && pmInfo->reserved) {
718 719 720 721 722 723
      j++;
      continue;
    }

    if (p->info.colId == pmInfo->colId) {
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, pmInfo->targetSlotId);
724
      colDataAssign(pDst, p, pBlock->info.rows, &pBlock->info);
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
      i++;
      j++;
    } else if (p->info.colId < pmInfo->colId) {
      i++;
    } else {
      ASSERT(0);
    }
  }
}

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 已提交
749 750 751 752 753 754

  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;
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
  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);
  pCond->colList = taosMemoryCalloc(pCond->numOfCols, sizeof(SColumnInfo));
  if (pCond->colList == NULL) {
    terrno = TSDB_CODE_QRY_OUT_OF_MEMORY;
    return terrno;
  }

  // pCond->twindow = pTableScanNode->scanRange;
  // TODO: get it from stable scan node
H
Haojun Liao 已提交
770 771 772
  pCond->twindows = pTableScanNode->scanRange;
  pCond->suid     = pTableScanNode->scan.suid;
  pCond->type     = BLOCK_LOAD_OFFSET_ORDER;
H
Haojun Liao 已提交
773 774
  pCond->startVersion = -1;
  pCond->endVersion   = -1;
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
  //  pCond->type = pTableScanNode->scanFlag;

  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;
    j += 1;
  }

  pCond->numOfCols = j;
  return TSDB_CODE_SUCCESS;
}

795
void cleanupQueryTableDataCond(SQueryTableDataCond* pCond) { taosMemoryFree(pCond->colList); }
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

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 已提交
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851

static void getInitialStartTimeWindow(SInterval* pInterval, TSKEY ts, STimeWindow* w, bool ascQuery) {
  if (ascQuery) {
    getAlignQueryTimeWindow(pInterval, pInterval->precision, ts, w);
  } else {
    // the start position of the first time window in the endpoint that spreads beyond the queried last timestamp
    getAlignQueryTimeWindow(pInterval, pInterval->precision, ts, w);

    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) {
  STimeWindow  w =  {0};

  if (pInterval->intervalUnit == 'n' || pInterval->intervalUnit == 'y') {
    w.skey = taosTimeTruncate(ts, pInterval, pInterval->precision);
    w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1;
  } else {
    int64_t st = w.skey;
5
54liuyao 已提交
852 853 854
    if (pInterval->offset > 0) {
      st = taosTimeAdd(st, pInterval->offset, pInterval->offsetUnit, pInterval->precision);
    }
H
Haojun Liao 已提交
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871

    if (st > ts) {
      st -= ((st - ts + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
    }

    int64_t et = st + pInterval->interval - 1;
    if (et < ts) {
      st += ((ts - et + pInterval->sliding - 1) / pInterval->sliding) * pInterval->sliding;
    }

    w.skey = st;
    w.ekey = taosTimeAdd(w.skey, pInterval->interval, pInterval->intervalUnit, pInterval->precision) - 1;
  }

  return w;
}

872
STimeWindow getFirstQualifiedTimeWindow(int64_t ts, STimeWindow* pWindow, SInterval* pInterval, int32_t order) {
H
Haojun Liao 已提交
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
  int32_t factor = (order == TSDB_ORDER_ASC)? -1:1;

  STimeWindow win = *pWindow;
  STimeWindow save = win;
  while(win.skey <= ts && win.ekey >= ts) {
    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
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;
  }

  w = getResultRowByPos(pBuf, &pResultRowInfo->cur)->win;

  // 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;
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928
}

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


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

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;
  pLimitInfo->slimit= slimit;
  pLimitInfo->remainOffset = limit.offset;
  pLimitInfo->remainGroupOffset = slimit.offset;
H
Haojun Liao 已提交
929
}