You need to sign in or sign up before continuing.
planOptimizer.c 87.3 KB
Newer Older
X
Xiaoyu Wang 已提交
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
#include "filter.h"
X
Xiaoyu Wang 已提交
17 18
#include "functionMgt.h"
#include "planInt.h"
19
#include "tglobal.h"
X
Xiaoyu Wang 已提交
20
#include "ttime.h"
X
Xiaoyu Wang 已提交
21

X
Xiaoyu Wang 已提交
22
#define OPTIMIZE_FLAG_MASK(n) (1 << n)
23

24
#define OPTIMIZE_FLAG_SCAN_PATH       OPTIMIZE_FLAG_MASK(0)
25
#define OPTIMIZE_FLAG_PUSH_DOWN_CONDE OPTIMIZE_FLAG_MASK(1)
26

X
Xiaoyu Wang 已提交
27
#define OPTIMIZE_FLAG_SET_MASK(val, mask)  (val) |= (mask)
28 29 30
#define OPTIMIZE_FLAG_TEST_MASK(val, mask) (((val) & (mask)) != 0)

typedef struct SOptimizeContext {
X
Xiaoyu Wang 已提交
31
  SPlanContext* pPlanCxt;
X
Xiaoyu Wang 已提交
32
  bool          optimized;
33 34
} SOptimizeContext;

X
Xiaoyu Wang 已提交
35
typedef int32_t (*FOptimize)(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan);
36 37

typedef struct SOptimizeRule {
X
Xiaoyu Wang 已提交
38
  char*     pName;
39 40 41
  FOptimize optimizeFunc;
} SOptimizeRule;

X
Xiaoyu Wang 已提交
42 43
typedef enum EScanOrder { SCAN_ORDER_ASC = 1, SCAN_ORDER_DESC, SCAN_ORDER_BOTH } EScanOrder;

44 45
typedef struct SOsdInfo {
  SScanLogicNode* pScan;
X
Xiaoyu Wang 已提交
46 47
  SNodeList*      pSdrFuncs;
  SNodeList*      pDsoFuncs;
X
Xiaoyu Wang 已提交
48
  EScanOrder      scanOrder;
49 50
} SOsdInfo;

51 52 53
typedef struct SCpdIsMultiTableCondCxt {
  SNodeList* pLeftCols;
  SNodeList* pRightCols;
X
Xiaoyu Wang 已提交
54 55
  bool       havaLeftCol;
  bool       haveRightCol;
56 57 58 59 60 61 62 63 64 65
} SCpdIsMultiTableCondCxt;

typedef enum ECondAction {
  COND_ACTION_STAY = 1,
  COND_ACTION_PUSH_JOIN,
  COND_ACTION_PUSH_LEFT_CHILD,
  COND_ACTION_PUSH_RIGHT_CHILD
  // after supporting outer join, there are other possibilities
} ECondAction;

X
Xiaoyu Wang 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
typedef bool (*FMayBeOptimized)(SLogicNode* pNode);

static SLogicNode* optFindPossibleNode(SLogicNode* pNode, FMayBeOptimized func) {
  if (func(pNode)) {
    return pNode;
  }
  SNode* pChild;
  FOREACH(pChild, pNode->pChildren) {
    SLogicNode* pScanNode = optFindPossibleNode((SLogicNode*)pChild, func);
    if (NULL != pScanNode) {
      return pScanNode;
    }
  }
  return NULL;
}

82 83 84 85 86
static void optResetParent(SLogicNode* pNode) {
  SNode* pChild = NULL;
  FOREACH(pChild, pNode->pChildren) { ((SLogicNode*)pChild)->pParent = pNode; }
}

X
Xiaoyu Wang 已提交
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
static EDealRes optRebuildTbanme(SNode** pNode, void* pContext) {
  if (QUERY_NODE_COLUMN == nodeType(*pNode) && COLUMN_TYPE_TBNAME == ((SColumnNode*)*pNode)->colType) {
    SFunctionNode* pFunc = (SFunctionNode*)nodesMakeNode(QUERY_NODE_FUNCTION);
    if (NULL == pFunc) {
      *(int32_t*)pContext = TSDB_CODE_OUT_OF_MEMORY;
      return DEAL_RES_ERROR;
    }
    strcpy(pFunc->functionName, "tbname");
    pFunc->funcType = FUNCTION_TYPE_TBNAME;
    pFunc->node.resType = ((SColumnNode*)*pNode)->node.resType;
    nodesDestroyNode(*pNode);
    *pNode = (SNode*)pFunc;
    return DEAL_RES_IGNORE_CHILD;
  }
  return DEAL_RES_CONTINUE;
}

X
Xiaoyu Wang 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
static void optSetParentOrder(SLogicNode* pNode, EOrder order) {
  if (NULL == pNode) {
    return;
  }
  switch (nodeType(pNode)) {
    case QUERY_NODE_LOGIC_PLAN_WINDOW:
      ((SWindowLogicNode*)pNode)->inputTsOrder = order;
      // window has a sorting function, and the operator behind it uses its output order
      return;
    case QUERY_NODE_LOGIC_PLAN_JOIN:
      ((SJoinLogicNode*)pNode)->inputTsOrder = order;
      break;
    case QUERY_NODE_LOGIC_PLAN_FILL:
      ((SFillLogicNode*)pNode)->inputTsOrder = order;
      break;
    default:
      break;
  }
  optSetParentOrder(pNode->pParent, order);
}

125
EDealRes scanPathOptHaveNormalColImpl(SNode* pNode, void* pContext) {
126
  if (QUERY_NODE_COLUMN == nodeType(pNode)) {
127 128
    *((bool*)pContext) =
        (COLUMN_TYPE_TAG != ((SColumnNode*)pNode)->colType && COLUMN_TYPE_TBNAME != ((SColumnNode*)pNode)->colType);
129 130 131 132 133
    return *((bool*)pContext) ? DEAL_RES_END : DEAL_RES_IGNORE_CHILD;
  }
  return DEAL_RES_CONTINUE;
}

134
static bool scanPathOptHaveNormalCol(SNodeList* pList) {
135
  bool res = false;
136
  nodesWalkExprsPostOrder(pList, scanPathOptHaveNormalColImpl, &res);
137 138 139
  return res;
}

140
static bool scanPathOptMayBeOptimized(SLogicNode* pNode) {
141
  if (OPTIMIZE_FLAG_TEST_MASK(pNode->optimizedFlag, OPTIMIZE_FLAG_SCAN_PATH)) {
142 143 144 145 146
    return false;
  }
  if (QUERY_NODE_LOGIC_PLAN_SCAN != nodeType(pNode)) {
    return false;
  }
X
Xiaoyu Wang 已提交
147
  if (NULL == pNode->pParent || (QUERY_NODE_LOGIC_PLAN_WINDOW != nodeType(pNode->pParent) &&
148 149
                                 QUERY_NODE_LOGIC_PLAN_AGG != nodeType(pNode->pParent) &&
                                 QUERY_NODE_LOGIC_PLAN_PARTITION != nodeType(pNode->pParent))) {
150 151
    return false;
  }
152 153
  if ((QUERY_NODE_LOGIC_PLAN_WINDOW == nodeType(pNode->pParent) &&
       WINDOW_TYPE_INTERVAL == ((SWindowLogicNode*)pNode->pParent)->winType) ||
X
Xiaoyu Wang 已提交
154
      (QUERY_NODE_LOGIC_PLAN_PARTITION == nodeType(pNode->pParent) && pNode->pParent->pParent &&
155 156
       QUERY_NODE_LOGIC_PLAN_WINDOW == nodeType(pNode->pParent->pParent) &&
       WINDOW_TYPE_INTERVAL == ((SWindowLogicNode*)pNode->pParent)->winType)) {
5
54liuyao 已提交
157
    return true;
158
  }
159 160 161 162
  if (QUERY_NODE_LOGIC_PLAN_AGG == nodeType(pNode->pParent)) {
    return !scanPathOptHaveNormalCol(((SAggLogicNode*)pNode->pParent)->pGroupKeys);
  }
  return false;
163 164
}

165
static SNodeList* scanPathOptGetAllFuncs(SLogicNode* pNode) {
166 167 168 169 170 171 172 173 174 175 176
  switch (nodeType(pNode)) {
    case QUERY_NODE_LOGIC_PLAN_WINDOW:
      return ((SWindowLogicNode*)pNode)->pFuncs;
    case QUERY_NODE_LOGIC_PLAN_AGG:
      return ((SAggLogicNode*)pNode)->pAggFuncs;
    default:
      break;
  }
  return NULL;
}

177
static bool scanPathOptNeedOptimizeDataRequire(const SFunctionNode* pFunc) {
178 179 180 181 182 183 184 185 186 187 188 189
  if (!fmIsSpecialDataRequiredFunc(pFunc->funcId)) {
    return false;
  }
  SNode* pPara = NULL;
  FOREACH(pPara, pFunc->pParameterList) {
    if (QUERY_NODE_COLUMN != nodeType(pPara) && QUERY_NODE_VALUE != nodeType(pPara)) {
      return false;
    }
  }
  return true;
}

190
static bool scanPathOptNeedDynOptimize(const SFunctionNode* pFunc) {
191 192 193 194 195 196 197 198 199 200 201 202
  if (!fmIsDynamicScanOptimizedFunc(pFunc->funcId)) {
    return false;
  }
  SNode* pPara = NULL;
  FOREACH(pPara, pFunc->pParameterList) {
    if (QUERY_NODE_COLUMN != nodeType(pPara) && QUERY_NODE_VALUE != nodeType(pPara)) {
      return false;
    }
  }
  return true;
}

203 204
static int32_t scanPathOptGetRelatedFuncs(SScanLogicNode* pScan, SNodeList** pSdrFuncs, SNodeList** pDsoFuncs) {
  SNodeList* pAllFuncs = scanPathOptGetAllFuncs(pScan->node.pParent);
X
Xiaoyu Wang 已提交
205 206
  SNodeList* pTmpSdrFuncs = NULL;
  SNodeList* pTmpDsoFuncs = NULL;
X
Xiaoyu Wang 已提交
207
  SNode*     pNode = NULL;
X
Xiaoyu Wang 已提交
208
  bool       otherFunc = false;
X
Xiaoyu Wang 已提交
209 210 211 212 213 214 215
  FOREACH(pNode, pAllFuncs) {
    SFunctionNode* pFunc = (SFunctionNode*)pNode;
    int32_t        code = TSDB_CODE_SUCCESS;
    if (scanPathOptNeedOptimizeDataRequire(pFunc)) {
      code = nodesListMakeStrictAppend(&pTmpSdrFuncs, nodesCloneNode(pNode));
    } else if (scanPathOptNeedDynOptimize(pFunc)) {
      code = nodesListMakeStrictAppend(&pTmpDsoFuncs, nodesCloneNode(pNode));
X
Xiaoyu Wang 已提交
216 217
    } else {
      otherFunc = true;
X
Xiaoyu Wang 已提交
218
      break;
219 220
    }
    if (TSDB_CODE_SUCCESS != code) {
X
Xiaoyu Wang 已提交
221 222
      nodesDestroyList(pTmpSdrFuncs);
      nodesDestroyList(pTmpDsoFuncs);
223 224
      return code;
    }
X
Xiaoyu Wang 已提交
225
  }
X
Xiaoyu Wang 已提交
226 227 228 229 230 231 232
  if (otherFunc) {
    nodesDestroyList(pTmpSdrFuncs);
    nodesDestroyList(pTmpDsoFuncs);
  } else {
    *pSdrFuncs = pTmpSdrFuncs;
    *pDsoFuncs = pTmpDsoFuncs;
  }
233 234 235
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
236 237 238 239 240 241 242 243 244 245
static int32_t scanPathOptGetScanOrder(SScanLogicNode* pScan, EScanOrder* pScanOrder) {
  SNodeList* pAllFuncs = scanPathOptGetAllFuncs(pScan->node.pParent);
  SNode*     pNode = NULL;
  bool       hasFirst = false;
  bool       hasLast = false;
  bool       otherFunc = false;
  FOREACH(pNode, pAllFuncs) {
    SFunctionNode* pFunc = (SFunctionNode*)pNode;
    if (FUNCTION_TYPE_FIRST == pFunc->funcType) {
      hasFirst = true;
246
    } else if (FUNCTION_TYPE_LAST == pFunc->funcType || FUNCTION_TYPE_LAST_ROW == pFunc->funcType) {
X
Xiaoyu Wang 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
      hasLast = true;
    } else if (FUNCTION_TYPE_SELECT_VALUE != pFunc->funcType) {
      otherFunc = true;
    }
  }
  if (hasFirst && hasLast && !otherFunc) {
    *pScanOrder = SCAN_ORDER_BOTH;
  } else if (hasLast) {
    *pScanOrder = SCAN_ORDER_DESC;
  } else {
    *pScanOrder = SCAN_ORDER_ASC;
  }
  return TSDB_CODE_SUCCESS;
}

static int32_t scanPathOptSetOsdInfo(SOsdInfo* pInfo) {
  int32_t code = scanPathOptGetRelatedFuncs(pInfo->pScan, &pInfo->pSdrFuncs, &pInfo->pDsoFuncs);
  if (TSDB_CODE_SUCCESS == code) {
    code = scanPathOptGetScanOrder(pInfo->pScan, &pInfo->scanOrder);
  }
  return code;
}

270 271
static int32_t scanPathOptMatch(SOptimizeContext* pCxt, SLogicNode* pLogicNode, SOsdInfo* pInfo) {
  pInfo->pScan = (SScanLogicNode*)optFindPossibleNode(pLogicNode, scanPathOptMayBeOptimized);
272 273 274
  if (NULL == pInfo->pScan) {
    return TSDB_CODE_SUCCESS;
  }
X
Xiaoyu Wang 已提交
275
  return scanPathOptSetOsdInfo(pInfo);
276 277
}

278
static EFuncDataRequired scanPathOptPromoteDataRequired(EFuncDataRequired l, EFuncDataRequired r) {
279
  switch (l) {
280
    case FUNC_DATA_REQUIRED_DATA_LOAD:
281
      return l;
H
Haojun Liao 已提交
282
    case FUNC_DATA_REQUIRED_SMA_LOAD:
283 284 285
      return FUNC_DATA_REQUIRED_DATA_LOAD == r ? r : l;
    case FUNC_DATA_REQUIRED_NOT_LOAD:
      return FUNC_DATA_REQUIRED_FILTEROUT == r ? l : r;
286 287 288 289 290 291
    default:
      break;
  }
  return r;
}

292
static int32_t scanPathOptGetDataRequired(SNodeList* pFuncs) {
293
  if (NULL == pFuncs) {
294
    return FUNC_DATA_REQUIRED_DATA_LOAD;
295
  }
296
  EFuncDataRequired dataRequired = FUNC_DATA_REQUIRED_FILTEROUT;
X
Xiaoyu Wang 已提交
297
  SNode*            pFunc = NULL;
298
  FOREACH(pFunc, pFuncs) {
299
    dataRequired = scanPathOptPromoteDataRequired(dataRequired, fmFuncDataRequired((SFunctionNode*)pFunc, NULL));
300 301 302 303
  }
  return dataRequired;
}

304
static void scanPathOptSetScanWin(SScanLogicNode* pScan) {
305
  SLogicNode* pParent = pScan->node.pParent;
X
Xiaoyu Wang 已提交
306 307
  if (QUERY_NODE_LOGIC_PLAN_PARTITION == nodeType(pParent) && pParent->pParent &&
      QUERY_NODE_LOGIC_PLAN_WINDOW == nodeType(pParent->pParent)) {
308 309 310 311 312 313 314 315 316 317
    pParent = pParent->pParent;
  }
  if (QUERY_NODE_LOGIC_PLAN_WINDOW == nodeType(pParent)) {
    pScan->interval = ((SWindowLogicNode*)pParent)->interval;
    pScan->offset = ((SWindowLogicNode*)pParent)->offset;
    pScan->sliding = ((SWindowLogicNode*)pParent)->sliding;
    pScan->intervalUnit = ((SWindowLogicNode*)pParent)->intervalUnit;
    pScan->slidingUnit = ((SWindowLogicNode*)pParent)->slidingUnit;
    pScan->triggerType = ((SWindowLogicNode*)pParent)->triggerType;
    pScan->watermark = ((SWindowLogicNode*)pParent)->watermark;
318
    pScan->igExpired = ((SWindowLogicNode*)pParent)->igExpired;
X
Xiaoyu Wang 已提交
319 320 321
  }
}

X
Xiaoyu Wang 已提交
322
static void scanPathOptSetScanOrder(EScanOrder scanOrder, SScanLogicNode* pScan) {
X
Xiaoyu Wang 已提交
323
  if (pScan->sortPrimaryKey || pScan->scanSeq[0] > 1 || pScan->scanSeq[1] > 1) {
X
Xiaoyu Wang 已提交
324 325 326 327 328 329
    return;
  }
  switch (scanOrder) {
    case SCAN_ORDER_ASC:
      pScan->scanSeq[0] = 1;
      pScan->scanSeq[1] = 0;
X
Xiaoyu Wang 已提交
330
      optSetParentOrder(pScan->node.pParent, ORDER_ASC);
X
Xiaoyu Wang 已提交
331 332 333 334
      break;
    case SCAN_ORDER_DESC:
      pScan->scanSeq[0] = 0;
      pScan->scanSeq[1] = 1;
X
Xiaoyu Wang 已提交
335
      optSetParentOrder(pScan->node.pParent, ORDER_DESC);
X
Xiaoyu Wang 已提交
336 337 338 339 340 341 342 343 344 345
      break;
    case SCAN_ORDER_BOTH:
      pScan->scanSeq[0] = 1;
      pScan->scanSeq[1] = 1;
      break;
    default:
      break;
  }
}

346
static int32_t scanPathOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
X
Xiaoyu Wang 已提交
347
  SOsdInfo info = {.scanOrder = SCAN_ORDER_ASC};
348
  int32_t  code = scanPathOptMatch(pCxt, pLogicSubplan->pNode, &info);
5
54liuyao 已提交
349
  if (TSDB_CODE_SUCCESS == code && info.pScan) {
X
Xiaoyu Wang 已提交
350 351
    scanPathOptSetScanWin(info.pScan);
    scanPathOptSetScanOrder(info.scanOrder, info.pScan);
5
54liuyao 已提交
352
  }
353
  if (TSDB_CODE_SUCCESS == code && (NULL != info.pDsoFuncs || NULL != info.pSdrFuncs)) {
354
    info.pScan->dataRequired = scanPathOptGetDataRequired(info.pSdrFuncs);
355
    info.pScan->pDynamicScanFuncs = info.pDsoFuncs;
X
Xiaoyu Wang 已提交
356 357
  }
  if (TSDB_CODE_SUCCESS == code && info.pScan) {
358
    OPTIMIZE_FLAG_SET_MASK(info.pScan->node.optimizedFlag, OPTIMIZE_FLAG_SCAN_PATH);
359 360 361 362 363 364
    pCxt->optimized = true;
  }
  nodesDestroyList(info.pSdrFuncs);
  return code;
}

365
static int32_t pushDownCondOptMergeCond(SNode** pDst, SNode** pSrc) {
366
  SLogicConditionNode* pLogicCond = (SLogicConditionNode*)nodesMakeNode(QUERY_NODE_LOGIC_CONDITION);
367 368 369
  if (NULL == pLogicCond) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
D
dapan1121 已提交
370 371
  pLogicCond->node.resType.type = TSDB_DATA_TYPE_BOOL;
  pLogicCond->node.resType.bytes = tDataTypes[TSDB_DATA_TYPE_BOOL].bytes;
372 373 374 375 376 377 378 379 380
  pLogicCond->condType = LOGIC_COND_TYPE_AND;
  int32_t code = nodesListMakeAppend(&pLogicCond->pParameterList, *pSrc);
  if (TSDB_CODE_SUCCESS == code) {
    *pSrc = NULL;
    code = nodesListMakeAppend(&pLogicCond->pParameterList, *pDst);
  }
  if (TSDB_CODE_SUCCESS == code) {
    *pDst = (SNode*)pLogicCond;
  } else {
381
    nodesDestroyNode((SNode*)pLogicCond);
382 383 384 385
  }
  return code;
}

386
static int32_t pushDownCondOptAppendCond(SNode** pCond, SNode** pAdditionalCond) {
387
  if (NULL == *pCond) {
wafwerar's avatar
wafwerar 已提交
388
    TSWAP(*pCond, *pAdditionalCond);
389 390 391 392
    return TSDB_CODE_SUCCESS;
  }

  int32_t code = TSDB_CODE_SUCCESS;
393 394
  if (QUERY_NODE_LOGIC_CONDITION == nodeType(*pCond) &&
      LOGIC_COND_TYPE_AND == ((SLogicConditionNode*)*pCond)->condType) {
395 396 397 398 399
    code = nodesListAppend(((SLogicConditionNode*)*pCond)->pParameterList, *pAdditionalCond);
    if (TSDB_CODE_SUCCESS == code) {
      *pAdditionalCond = NULL;
    }
  } else {
400
    code = pushDownCondOptMergeCond(pCond, pAdditionalCond);
401 402 403 404
  }
  return code;
}

405 406
static int32_t pushDownCondOptCalcTimeRange(SOptimizeContext* pCxt, SScanLogicNode* pScan, SNode** pPrimaryKeyCond,
                                            SNode** pOtherCond) {
407 408
  int32_t code = TSDB_CODE_SUCCESS;
  if (pCxt->pPlanCxt->topicQuery || pCxt->pPlanCxt->streamQuery) {
409
    code = pushDownCondOptAppendCond(pOtherCond, pPrimaryKeyCond);
410 411 412 413 414 415 416
  } else {
    bool isStrict = false;
    code = filterGetTimeRange(*pPrimaryKeyCond, &pScan->scanRange, &isStrict);
    if (TSDB_CODE_SUCCESS == code) {
      if (isStrict) {
        nodesDestroyNode(*pPrimaryKeyCond);
      } else {
417
        code = pushDownCondOptAppendCond(pOtherCond, pPrimaryKeyCond);
418 419
      }
      *pPrimaryKeyCond = NULL;
420 421 422 423 424
    }
  }
  return code;
}

X
Xiaoyu Wang 已提交
425 426 427 428 429 430
static int32_t pushDownCondOptRebuildTbanme(SNode** pTagCond) {
  int32_t code = TSDB_CODE_SUCCESS;
  nodesRewriteExpr(pTagCond, optRebuildTbanme, &code);
  return code;
}

431 432 433
static int32_t pushDownCondOptDealScan(SOptimizeContext* pCxt, SScanLogicNode* pScan) {
  if (NULL == pScan->node.pConditions ||
      OPTIMIZE_FLAG_TEST_MASK(pScan->node.optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE) ||
X
Xiaoyu Wang 已提交
434
      TSDB_SYSTEM_TABLE == pScan->tableType) {
435 436 437
    return TSDB_CODE_SUCCESS;
  }

X
Xiaoyu Wang 已提交
438 439
  SNode*  pPrimaryKeyCond = NULL;
  SNode*  pOtherCond = NULL;
440 441
  int32_t code = filterPartitionCond(&pScan->node.pConditions, &pPrimaryKeyCond, &pScan->pTagIndexCond,
                                     &pScan->pTagCond, &pOtherCond);
X
Xiaoyu Wang 已提交
442 443 444
  if (TSDB_CODE_SUCCESS == code && NULL != pScan->pTagCond) {
    code = pushDownCondOptRebuildTbanme(&pScan->pTagCond);
  }
445
  if (TSDB_CODE_SUCCESS == code && NULL != pPrimaryKeyCond) {
446
    code = pushDownCondOptCalcTimeRange(pCxt, pScan, &pPrimaryKeyCond, &pOtherCond);
447 448 449 450 451
  }
  if (TSDB_CODE_SUCCESS == code) {
    pScan->node.pConditions = pOtherCond;
  }

X
Xiaoyu Wang 已提交
452
  if (TSDB_CODE_SUCCESS == code) {
453
    OPTIMIZE_FLAG_SET_MASK(pScan->node.optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE);
X
Xiaoyu Wang 已提交
454 455
    pCxt->optimized = true;
  } else {
456 457 458 459 460 461 462
    nodesDestroyNode(pPrimaryKeyCond);
    nodesDestroyNode(pOtherCond);
  }

  return code;
}

463
static bool pushDownCondOptBelongThisTable(SNode* pCondCol, SNodeList* pTableCols) {
464 465 466 467 468 469 470
  SNode* pTableCol = NULL;
  FOREACH(pTableCol, pTableCols) {
    if (nodesEqualNode(pCondCol, pTableCol)) {
      return true;
    }
  }
  return false;
471 472
}

473
static EDealRes pushDownCondOptIsCrossTableCond(SNode* pNode, void* pContext) {
474 475
  SCpdIsMultiTableCondCxt* pCxt = pContext;
  if (QUERY_NODE_COLUMN == nodeType(pNode)) {
476
    if (pushDownCondOptBelongThisTable(pNode, pCxt->pLeftCols)) {
477
      pCxt->havaLeftCol = true;
478
    } else if (pushDownCondOptBelongThisTable(pNode, pCxt->pRightCols)) {
479 480 481 482 483
      pCxt->haveRightCol = true;
    }
    return pCxt->havaLeftCol && pCxt->haveRightCol ? DEAL_RES_END : DEAL_RES_CONTINUE;
  }
  return DEAL_RES_CONTINUE;
484 485
}

486 487
static ECondAction pushDownCondOptGetCondAction(EJoinType joinType, SNodeList* pLeftCols, SNodeList* pRightCols,
                                                SNode* pNode) {
X
Xiaoyu Wang 已提交
488 489
  SCpdIsMultiTableCondCxt cxt = {
      .pLeftCols = pLeftCols, .pRightCols = pRightCols, .havaLeftCol = false, .haveRightCol = false};
490
  nodesWalkExpr(pNode, pushDownCondOptIsCrossTableCond, &cxt);
X
Xiaoyu Wang 已提交
491 492 493 494 495
  return (JOIN_TYPE_INNER != joinType
              ? COND_ACTION_STAY
              : (cxt.havaLeftCol && cxt.haveRightCol
                     ? COND_ACTION_PUSH_JOIN
                     : (cxt.havaLeftCol ? COND_ACTION_PUSH_LEFT_CHILD : COND_ACTION_PUSH_RIGHT_CHILD)));
496 497
}

498 499
static int32_t pushDownCondOptPartLogicCond(SJoinLogicNode* pJoin, SNode** pOnCond, SNode** pLeftChildCond,
                                            SNode** pRightChildCond) {
500 501 502 503 504 505 506
  SLogicConditionNode* pLogicCond = (SLogicConditionNode*)pJoin->node.pConditions;
  if (LOGIC_COND_TYPE_AND != pLogicCond->condType) {
    return TSDB_CODE_SUCCESS;
  }

  SNodeList* pLeftCols = ((SLogicNode*)nodesListGetNode(pJoin->node.pChildren, 0))->pTargets;
  SNodeList* pRightCols = ((SLogicNode*)nodesListGetNode(pJoin->node.pChildren, 1))->pTargets;
X
Xiaoyu Wang 已提交
507
  int32_t    code = TSDB_CODE_SUCCESS;
508 509 510 511 512

  SNodeList* pOnConds = NULL;
  SNodeList* pLeftChildConds = NULL;
  SNodeList* pRightChildConds = NULL;
  SNodeList* pRemainConds = NULL;
X
Xiaoyu Wang 已提交
513
  SNode*     pCond = NULL;
514
  FOREACH(pCond, pLogicCond->pParameterList) {
515
    ECondAction condAction = pushDownCondOptGetCondAction(pJoin->joinType, pLeftCols, pRightCols, pCond);
516 517 518 519 520 521 522 523
    if (COND_ACTION_PUSH_JOIN == condAction) {
      code = nodesListMakeAppend(&pOnConds, nodesCloneNode(pCond));
    } else if (COND_ACTION_PUSH_LEFT_CHILD == condAction) {
      code = nodesListMakeAppend(&pLeftChildConds, nodesCloneNode(pCond));
    } else if (COND_ACTION_PUSH_RIGHT_CHILD == condAction) {
      code = nodesListMakeAppend(&pRightChildConds, nodesCloneNode(pCond));
    } else {
      code = nodesListMakeAppend(&pRemainConds, nodesCloneNode(pCond));
524
    }
525 526
    if (TSDB_CODE_SUCCESS != code) {
      break;
527 528
    }
  }
529 530 531 532 533 534

  SNode* pTempOnCond = NULL;
  SNode* pTempLeftChildCond = NULL;
  SNode* pTempRightChildCond = NULL;
  SNode* pTempRemainCond = NULL;
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
535
    code = nodesMergeConds(&pTempOnCond, &pOnConds);
536 537
  }
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
538
    code = nodesMergeConds(&pTempLeftChildCond, &pLeftChildConds);
539 540
  }
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
541
    code = nodesMergeConds(&pTempRightChildCond, &pRightChildConds);
542 543
  }
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
544
    code = nodesMergeConds(&pTempRemainCond, &pRemainConds);
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
  }

  if (TSDB_CODE_SUCCESS == code) {
    *pOnCond = pTempOnCond;
    *pLeftChildCond = pTempLeftChildCond;
    *pRightChildCond = pTempRightChildCond;
    nodesDestroyNode(pJoin->node.pConditions);
    pJoin->node.pConditions = pTempRemainCond;
  } else {
    nodesDestroyList(pOnConds);
    nodesDestroyList(pLeftChildConds);
    nodesDestroyList(pRightChildConds);
    nodesDestroyList(pRemainConds);
    nodesDestroyNode(pTempOnCond);
    nodesDestroyNode(pTempLeftChildCond);
    nodesDestroyNode(pTempRightChildCond);
    nodesDestroyNode(pTempRemainCond);
  }

  return code;
}

567 568
static int32_t pushDownCondOptPartOpCond(SJoinLogicNode* pJoin, SNode** pOnCond, SNode** pLeftChildCond,
                                         SNode** pRightChildCond) {
X
Xiaoyu Wang 已提交
569 570
  SNodeList*  pLeftCols = ((SLogicNode*)nodesListGetNode(pJoin->node.pChildren, 0))->pTargets;
  SNodeList*  pRightCols = ((SLogicNode*)nodesListGetNode(pJoin->node.pChildren, 1))->pTargets;
571 572
  ECondAction condAction =
      pushDownCondOptGetCondAction(pJoin->joinType, pLeftCols, pRightCols, pJoin->node.pConditions);
573 574 575 576 577 578 579 580 581 582
  if (COND_ACTION_STAY == condAction) {
    return TSDB_CODE_SUCCESS;
  } else if (COND_ACTION_PUSH_JOIN == condAction) {
    *pOnCond = pJoin->node.pConditions;
  } else if (COND_ACTION_PUSH_LEFT_CHILD == condAction) {
    *pLeftChildCond = pJoin->node.pConditions;
  } else if (COND_ACTION_PUSH_RIGHT_CHILD == condAction) {
    *pRightChildCond = pJoin->node.pConditions;
  }
  pJoin->node.pConditions = NULL;
583 584 585
  return TSDB_CODE_SUCCESS;
}

586 587
static int32_t pushDownCondOptPartCond(SJoinLogicNode* pJoin, SNode** pOnCond, SNode** pLeftChildCond,
                                       SNode** pRightChildCond) {
588
  if (QUERY_NODE_LOGIC_CONDITION == nodeType(pJoin->node.pConditions)) {
589
    return pushDownCondOptPartLogicCond(pJoin, pOnCond, pLeftChildCond, pRightChildCond);
590
  } else {
591
    return pushDownCondOptPartOpCond(pJoin, pOnCond, pLeftChildCond, pRightChildCond);
592 593 594
  }
}

595 596
static int32_t pushDownCondOptPushCondToOnCond(SOptimizeContext* pCxt, SJoinLogicNode* pJoin, SNode** pCond) {
  return pushDownCondOptAppendCond(&pJoin->pOnConditions, pCond);
597 598
}

599
static int32_t pushDownCondOptPushCondToChild(SOptimizeContext* pCxt, SLogicNode* pChild, SNode** pCond) {
600
  return pushDownCondOptAppendCond(&pChild->pConditions, pCond);
601 602
}

603
static bool pushDownCondOptIsPriKey(SNode* pNode, SNodeList* pTableCols) {
X
Xiaoyu Wang 已提交
604 605 606 607
  if (QUERY_NODE_COLUMN != nodeType(pNode)) {
    return false;
  }
  SColumnNode* pCol = (SColumnNode*)pNode;
608
  if (PRIMARYKEY_TIMESTAMP_COL_ID != pCol->colId || TSDB_SYSTEM_TABLE == pCol->tableType) {
X
Xiaoyu Wang 已提交
609 610
    return false;
  }
611
  return pushDownCondOptBelongThisTable(pNode, pTableCols);
X
Xiaoyu Wang 已提交
612 613
}

614
static bool pushDownCondOptIsPriKeyEqualCond(SJoinLogicNode* pJoin, SNode* pCond) {
X
Xiaoyu Wang 已提交
615 616 617
  if (QUERY_NODE_OPERATOR != nodeType(pCond)) {
    return false;
  }
618

619
  SOperatorNode* pOper = (SOperatorNode*)pCond;
620 621 622 623 624 625
  if (OP_TYPE_EQUAL != pOper->opType) {
    return false;
  }

  SNodeList* pLeftCols = ((SLogicNode*)nodesListGetNode(pJoin->node.pChildren, 0))->pTargets;
  SNodeList* pRightCols = ((SLogicNode*)nodesListGetNode(pJoin->node.pChildren, 1))->pTargets;
626 627 628 629
  if (pushDownCondOptIsPriKey(pOper->pLeft, pLeftCols)) {
    return pushDownCondOptIsPriKey(pOper->pRight, pRightCols);
  } else if (pushDownCondOptIsPriKey(pOper->pLeft, pRightCols)) {
    return pushDownCondOptIsPriKey(pOper->pRight, pLeftCols);
X
Xiaoyu Wang 已提交
630 631 632 633
  }
  return false;
}

634
static bool pushDownCondOptContainPriKeyEqualCond(SJoinLogicNode* pJoin, SNode* pCond) {
635 636 637 638
  if (QUERY_NODE_LOGIC_CONDITION == nodeType(pCond)) {
    SLogicConditionNode* pLogicCond = (SLogicConditionNode*)pCond;
    if (LOGIC_COND_TYPE_AND != pLogicCond->condType) {
      return false;
X
Xiaoyu Wang 已提交
639
    }
640 641 642
    bool   hasPrimaryKeyEqualCond = false;
    SNode* pCond = NULL;
    FOREACH(pCond, pLogicCond->pParameterList) {
643
      if (pushDownCondOptContainPriKeyEqualCond(pJoin, pCond)) {
644 645 646 647 648 649
        hasPrimaryKeyEqualCond = true;
        break;
      }
    }
    return hasPrimaryKeyEqualCond;
  } else {
650
    return pushDownCondOptIsPriKeyEqualCond(pJoin, pCond);
651 652 653
  }
}

654
static int32_t pushDownCondOptCheckJoinOnCond(SOptimizeContext* pCxt, SJoinLogicNode* pJoin) {
X
Xiaoyu Wang 已提交
655
  if (NULL == pJoin->pOnConditions) {
X
Xiaoyu Wang 已提交
656
    return generateUsageErrMsg(pCxt->pPlanCxt->pMsg, pCxt->pPlanCxt->msgLen, TSDB_CODE_PLAN_NOT_SUPPORT_CROSS_JOIN);
X
Xiaoyu Wang 已提交
657
  }
658
  if (!pushDownCondOptContainPriKeyEqualCond(pJoin, pJoin->pOnConditions)) {
659
    return generateUsageErrMsg(pCxt->pPlanCxt->pMsg, pCxt->pPlanCxt->msgLen, TSDB_CODE_PLAN_EXPECTED_TS_EQUAL);
X
Xiaoyu Wang 已提交
660
  }
661
  return TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
662 663
}

664 665 666
static int32_t pushDownCondOptPartJoinOnCondLogicCond(SJoinLogicNode* pJoin, SNode** ppMergeCond, SNode** ppOnCond) {
  SLogicConditionNode* pLogicCond = (SLogicConditionNode*)(pJoin->pOnConditions);

667
  int32_t    code = TSDB_CODE_SUCCESS;
668
  SNodeList* pOnConds = NULL;
669
  SNode*     pCond = NULL;
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 700 701 702 703 704 705 706 707 708 709 710 711
  FOREACH(pCond, pLogicCond->pParameterList) {
    if (pushDownCondOptIsPriKeyEqualCond(pJoin, pCond)) {
      *ppMergeCond = nodesCloneNode(pCond);
    } else {
      code = nodesListMakeAppend(&pOnConds, nodesCloneNode(pCond));
    }
  }

  SNode* pTempOnCond = NULL;
  if (TSDB_CODE_SUCCESS == code) {
    code = nodesMergeConds(&pTempOnCond, &pOnConds);
  }

  if (TSDB_CODE_SUCCESS == code && NULL != *ppMergeCond) {
    *ppOnCond = pTempOnCond;
    nodesDestroyNode(pJoin->pOnConditions);
    pJoin->pOnConditions = NULL;
    return TSDB_CODE_SUCCESS;
  } else {
    nodesDestroyList(pOnConds);
    nodesDestroyNode(pTempOnCond);
    return TSDB_CODE_PLAN_INTERNAL_ERROR;
  }
}

static int32_t pushDownCondOptPartJoinOnCond(SJoinLogicNode* pJoin, SNode** ppMergeCond, SNode** ppOnCond) {
  if (QUERY_NODE_LOGIC_CONDITION == nodeType(pJoin->pOnConditions) &&
      LOGIC_COND_TYPE_AND == ((SLogicConditionNode*)(pJoin->pOnConditions))->condType) {
    return pushDownCondOptPartJoinOnCondLogicCond(pJoin, ppMergeCond, ppOnCond);
  }

  if (pushDownCondOptIsPriKeyEqualCond(pJoin, pJoin->pOnConditions)) {
    *ppMergeCond = nodesCloneNode(pJoin->pOnConditions);
    *ppOnCond = NULL;
    nodesDestroyNode(pJoin->pOnConditions);
    pJoin->pOnConditions = NULL;
    return TSDB_CODE_SUCCESS;
  } else {
    return TSDB_CODE_PLAN_INTERNAL_ERROR;
  }
}

712 713
static int32_t pushDownCondOptJoinExtractMergeCond(SOptimizeContext* pCxt, SJoinLogicNode* pJoin) {
  int32_t code = pushDownCondOptCheckJoinOnCond(pCxt, pJoin);
714 715
  SNode*  pJoinMergeCond = NULL;
  SNode*  pJoinOnCond = NULL;
716 717 718 719 720 721 722 723 724 725 726 727 728
  if (TSDB_CODE_SUCCESS == code) {
    code = pushDownCondOptPartJoinOnCond(pJoin, &pJoinMergeCond, &pJoinOnCond);
  }
  if (TSDB_CODE_SUCCESS == code) {
    pJoin->pMergeCondition = pJoinMergeCond;
    pJoin->pOnConditions = pJoinOnCond;
  } else {
    nodesDestroyNode(pJoinMergeCond);
    nodesDestroyNode(pJoinOnCond);
  }
  return code;
}

729 730
static int32_t pushDownCondOptDealJoin(SOptimizeContext* pCxt, SJoinLogicNode* pJoin) {
  if (OPTIMIZE_FLAG_TEST_MASK(pJoin->node.optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE)) {
731 732 733
    return TSDB_CODE_SUCCESS;
  }

X
Xiaoyu Wang 已提交
734
  if (NULL == pJoin->node.pConditions) {
735
    int32_t code = pushDownCondOptJoinExtractMergeCond(pCxt, pJoin);
S
slzhou 已提交
736 737 738 739
    if (TSDB_CODE_SUCCESS == code) {
      OPTIMIZE_FLAG_SET_MASK(pJoin->node.optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE);
      pCxt->optimized = true;
    }
740
    return code;
X
Xiaoyu Wang 已提交
741 742
  }

X
Xiaoyu Wang 已提交
743 744 745
  SNode*  pOnCond = NULL;
  SNode*  pLeftChildCond = NULL;
  SNode*  pRightChildCond = NULL;
746
  int32_t code = pushDownCondOptPartCond(pJoin, &pOnCond, &pLeftChildCond, &pRightChildCond);
747
  if (TSDB_CODE_SUCCESS == code && NULL != pOnCond) {
748
    code = pushDownCondOptPushCondToOnCond(pCxt, pJoin, &pOnCond);
749 750
  }
  if (TSDB_CODE_SUCCESS == code && NULL != pLeftChildCond) {
751 752
    code =
        pushDownCondOptPushCondToChild(pCxt, (SLogicNode*)nodesListGetNode(pJoin->node.pChildren, 0), &pLeftChildCond);
753 754
  }
  if (TSDB_CODE_SUCCESS == code && NULL != pRightChildCond) {
755 756
    code =
        pushDownCondOptPushCondToChild(pCxt, (SLogicNode*)nodesListGetNode(pJoin->node.pChildren, 1), &pRightChildCond);
757 758
  }

759
  if (TSDB_CODE_SUCCESS == code) {
760
    code = pushDownCondOptJoinExtractMergeCond(pCxt, pJoin);
761 762
  }

X
Xiaoyu Wang 已提交
763
  if (TSDB_CODE_SUCCESS == code) {
764
    OPTIMIZE_FLAG_SET_MASK(pJoin->node.optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE);
X
Xiaoyu Wang 已提交
765 766
    pCxt->optimized = true;
  } else {
767 768 769 770 771 772 773 774
    nodesDestroyNode(pOnCond);
    nodesDestroyNode(pLeftChildCond);
    nodesDestroyNode(pRightChildCond);
  }

  return code;
}

775 776
typedef struct SPartAggCondContext {
  SAggLogicNode* pAgg;
777
  bool           hasAggFunc;
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
} SPartAggCondContext;

static EDealRes partAggCondHasAggFuncImpl(SNode* pNode, void* pContext) {
  SPartAggCondContext* pCxt = pContext;
  if (QUERY_NODE_COLUMN == nodeType(pNode)) {
    SNode* pAggFunc = NULL;
    FOREACH(pAggFunc, pCxt->pAgg->pAggFuncs) {
      if (strcmp(((SColumnNode*)pNode)->colName, ((SFunctionNode*)pAggFunc)->node.aliasName) == 0) {
        pCxt->hasAggFunc = true;
        return DEAL_RES_END;
      }
    }
  }
  return DEAL_RES_CONTINUE;
}

static int32_t partitionAggCondHasAggFunc(SAggLogicNode* pAgg, SNode* pCond) {
  SPartAggCondContext cxt = {.pAgg = pAgg, .hasAggFunc = false};
  nodesWalkExpr(pCond, partAggCondHasAggFuncImpl, &cxt);
  return cxt.hasAggFunc;
}

static int32_t partitionAggCondConj(SAggLogicNode* pAgg, SNode** ppAggFuncCond, SNode** ppGroupKeyCond) {
  SLogicConditionNode* pLogicCond = (SLogicConditionNode*)pAgg->node.pConditions;
802
  int32_t              code = TSDB_CODE_SUCCESS;
803 804 805

  SNodeList* pAggFuncConds = NULL;
  SNodeList* pGroupKeyConds = NULL;
806
  SNode*     pCond = NULL;
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
  FOREACH(pCond, pLogicCond->pParameterList) {
    if (partitionAggCondHasAggFunc(pAgg, pCond)) {
      code = nodesListMakeAppend(&pAggFuncConds, nodesCloneNode(pCond));
    } else {
      code = nodesListMakeAppend(&pGroupKeyConds, nodesCloneNode(pCond));
    }
    if (TSDB_CODE_SUCCESS != code) {
      break;
    }
  }

  SNode* pTempAggFuncCond = NULL;
  SNode* pTempGroupKeyCond = NULL;
  if (TSDB_CODE_SUCCESS == code) {
    code = nodesMergeConds(&pTempAggFuncCond, &pAggFuncConds);
  }
  if (TSDB_CODE_SUCCESS == code) {
    code = nodesMergeConds(&pTempGroupKeyCond, &pGroupKeyConds);
  }

  if (TSDB_CODE_SUCCESS == code) {
    *ppAggFuncCond = pTempAggFuncCond;
    *ppGroupKeyCond = pTempGroupKeyCond;
  } else {
    nodesDestroyList(pAggFuncConds);
    nodesDestroyList(pGroupKeyConds);
    nodesDestroyNode(pTempAggFuncCond);
    nodesDestroyNode(pTempGroupKeyCond);
  }
X
Xiaoyu Wang 已提交
836
  nodesDestroyNode(pAgg->node.pConditions);
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
  pAgg->node.pConditions = NULL;
  return code;
}

static int32_t partitionAggCond(SAggLogicNode* pAgg, SNode** ppAggFunCond, SNode** ppGroupKeyCond) {
  SNode* pAggNodeCond = pAgg->node.pConditions;
  if (QUERY_NODE_LOGIC_CONDITION == nodeType(pAggNodeCond) &&
      LOGIC_COND_TYPE_AND == ((SLogicConditionNode*)(pAggNodeCond))->condType) {
    return partitionAggCondConj(pAgg, ppAggFunCond, ppGroupKeyCond);
  }
  if (partitionAggCondHasAggFunc(pAgg, pAggNodeCond)) {
    *ppAggFunCond = pAggNodeCond;
  } else {
    *ppGroupKeyCond = pAggNodeCond;
  }
  pAgg->node.pConditions = NULL;
853 854 855
  return TSDB_CODE_SUCCESS;
}

856
static int32_t pushCondToAggCond(SOptimizeContext* pCxt, SAggLogicNode* pAgg, SNode** pAggFuncCond) {
X
Xiaoyu Wang 已提交
857
  return pushDownCondOptAppendCond(&pAgg->node.pConditions, pAggFuncCond);
858 859
}

860 861 862
typedef struct SRewriteAggGroupKeyCondContext {
  SAggLogicNode* pAgg;
  int32_t        errCode;
863 864 865 866
} SRewriteAggGroupKeyCondContext;

static EDealRes rewriteAggGroupKeyCondForPushDownImpl(SNode** pNode, void* pContext) {
  SRewriteAggGroupKeyCondContext* pCxt = pContext;
867
  SAggLogicNode*                  pAgg = pCxt->pAgg;
868 869 870 871 872 873 874 875
  if (QUERY_NODE_COLUMN == nodeType(*pNode)) {
    SNode* pGroupKey = NULL;
    FOREACH(pGroupKey, pAgg->pGroupKeys) {
      SNode* pGroup = NULL;
      FOREACH(pGroup, ((SGroupingSetNode*)pGroupKey)->pParameterList) {
        if (0 == strcmp(((SExprNode*)pGroup)->aliasName, ((SColumnNode*)(*pNode))->colName)) {
          SNode* pExpr = nodesCloneNode(pGroup);
          if (pExpr == NULL) {
876
            pCxt->errCode = TSDB_CODE_OUT_OF_MEMORY;
877 878 879 880
            return DEAL_RES_ERROR;
          }
          nodesDestroyNode(*pNode);
          *pNode = pExpr;
881
          return DEAL_RES_IGNORE_CHILD;
882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
        }
      }
    }
  }
  return DEAL_RES_CONTINUE;
}

static int32_t rewriteAggGroupKeyCondForPushDown(SOptimizeContext* pCxt, SAggLogicNode* pAgg, SNode* pGroupKeyCond) {
  SRewriteAggGroupKeyCondContext cxt = {.pAgg = pAgg, .errCode = TSDB_CODE_SUCCESS};
  nodesRewriteExpr(&pGroupKeyCond, rewriteAggGroupKeyCondForPushDownImpl, &cxt);
  return cxt.errCode;
}

static int32_t pushDownCondOptDealAgg(SOptimizeContext* pCxt, SAggLogicNode* pAgg) {
  if (NULL == pAgg->node.pConditions ||
      OPTIMIZE_FLAG_TEST_MASK(pAgg->node.optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE)) {
    return TSDB_CODE_SUCCESS;
  }
900
  // TODO: remove it after full implementation of pushing down to child
901
  if (1 != LIST_LENGTH(pAgg->node.pChildren)) {
902 903
    return TSDB_CODE_SUCCESS;
  }
904 905 906

  SNode*  pAggFuncCond = NULL;
  SNode*  pGroupKeyCond = NULL;
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
  int32_t code = partitionAggCond(pAgg, &pAggFuncCond, &pGroupKeyCond);
  if (TSDB_CODE_SUCCESS == code && NULL != pAggFuncCond) {
    code = pushCondToAggCond(pCxt, pAgg, &pAggFuncCond);
  }
  if (TSDB_CODE_SUCCESS == code && NULL != pGroupKeyCond) {
    code = rewriteAggGroupKeyCondForPushDown(pCxt, pAgg, pGroupKeyCond);
  }
  if (TSDB_CODE_SUCCESS == code && NULL != pGroupKeyCond) {
    SLogicNode* pChild = (SLogicNode*)nodesListGetNode(pAgg->node.pChildren, 0);
    code = pushDownCondOptPushCondToChild(pCxt, pChild, &pGroupKeyCond);
  }
  if (TSDB_CODE_SUCCESS == code) {
    OPTIMIZE_FLAG_SET_MASK(pAgg->node.optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE);
    pCxt->optimized = true;
  } else {
    nodesDestroyNode(pGroupKeyCond);
    nodesDestroyNode(pAggFuncCond);
  }
  return code;
}

928 929
typedef struct SRewriteProjCondContext {
  SProjectLogicNode* pProj;
930 931
  int32_t            errCode;
} SRewriteProjCondContext;
932 933 934

static EDealRes rewriteProjectCondForPushDownImpl(SNode** ppNode, void* pContext) {
  SRewriteProjCondContext* pCxt = pContext;
935
  SProjectLogicNode*       pProj = pCxt->pProj;
936 937 938 939 940 941 942 943 944
  if (QUERY_NODE_COLUMN == nodeType(*ppNode)) {
    SNode* pTarget = NULL;
    FOREACH(pTarget, pProj->node.pTargets) {
      if (nodesEqualNode(pTarget, *ppNode)) {
        SNode* pProjection = NULL;
        FOREACH(pProjection, pProj->pProjections) {
          if (0 == strcmp(((SExprNode*)pProjection)->aliasName, ((SColumnNode*)(*ppNode))->colName)) {
            SNode* pExpr = nodesCloneNode(pProjection);
            if (pExpr == NULL) {
945
              pCxt->errCode = TSDB_CODE_OUT_OF_MEMORY;
946 947 948 949
              return DEAL_RES_ERROR;
            }
            nodesDestroyNode(*ppNode);
            *ppNode = pExpr;
950
            return DEAL_RES_IGNORE_CHILD;
951 952 953 954
          }  // end if expr alias name equal column name
        }    // end for each project
      }      // end if target node equals cond column node
    }        // end for each targets
955 956 957 958
  }
  return DEAL_RES_CONTINUE;
}

959 960
static int32_t rewriteProjectCondForPushDown(SOptimizeContext* pCxt, SProjectLogicNode* pProject,
                                             SNode** ppProjectCond) {
961
  SRewriteProjCondContext cxt = {.pProj = pProject, .errCode = TSDB_CODE_SUCCESS};
962
  SNode*                  pProjectCond = pProject->node.pConditions;
963 964 965 966 967 968 969 970 971 972 973 974
  nodesRewriteExpr(&pProjectCond, rewriteProjectCondForPushDownImpl, &cxt);
  *ppProjectCond = pProjectCond;
  pProject->node.pConditions = NULL;
  return cxt.errCode;
}

static int32_t pushDownCondOptDealProject(SOptimizeContext* pCxt, SProjectLogicNode* pProject) {
  if (NULL == pProject->node.pConditions ||
      OPTIMIZE_FLAG_TEST_MASK(pProject->node.optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE)) {
    return TSDB_CODE_SUCCESS;
  }
  // TODO: remove it after full implementation of pushing down to child
975
  if (1 != LIST_LENGTH(pProject->node.pChildren)) {
976 977 978 979 980 981 982 983
    return TSDB_CODE_SUCCESS;
  }

  if (NULL != pProject->node.pLimit || NULL != pProject->node.pSlimit) {
    return TSDB_CODE_SUCCESS;
  }

  int32_t code = TSDB_CODE_SUCCESS;
984
  SNode*  pProjCond = NULL;
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
  code = rewriteProjectCondForPushDown(pCxt, pProject, &pProjCond);
  if (TSDB_CODE_SUCCESS == code) {
    SLogicNode* pChild = (SLogicNode*)nodesListGetNode(pProject->node.pChildren, 0);
    code = pushDownCondOptPushCondToChild(pCxt, pChild, &pProjCond);
  }

  if (TSDB_CODE_SUCCESS == code) {
    OPTIMIZE_FLAG_SET_MASK(pProject->node.optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE);
    pCxt->optimized = true;
  } else {
    nodesDestroyNode(pProjCond);
  }
  return code;
}

1000
static int32_t pushDownCondOptTrivialPushDown(SOptimizeContext* pCxt, SLogicNode* pLogicNode) {
1001 1002 1003 1004 1005
  if (NULL == pLogicNode->pConditions ||
      OPTIMIZE_FLAG_TEST_MASK(pLogicNode->optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE)) {
    return TSDB_CODE_SUCCESS;
  }
  SLogicNode* pChild = (SLogicNode*)nodesListGetNode(pLogicNode->pChildren, 0);
1006
  int32_t     code = pushDownCondOptPushCondToChild(pCxt, pChild, &pLogicNode->pConditions);
1007 1008 1009 1010 1011 1012 1013
  if (TSDB_CODE_SUCCESS == code) {
    OPTIMIZE_FLAG_SET_MASK(pLogicNode->optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE);
    pCxt->optimized = true;
  }
  return code;
}

1014
static int32_t pushDownCondOptimizeImpl(SOptimizeContext* pCxt, SLogicNode* pLogicNode) {
1015 1016 1017
  int32_t code = TSDB_CODE_SUCCESS;
  switch (nodeType(pLogicNode)) {
    case QUERY_NODE_LOGIC_PLAN_SCAN:
1018
      code = pushDownCondOptDealScan(pCxt, (SScanLogicNode*)pLogicNode);
1019 1020
      break;
    case QUERY_NODE_LOGIC_PLAN_JOIN:
1021
      code = pushDownCondOptDealJoin(pCxt, (SJoinLogicNode*)pLogicNode);
1022 1023
      break;
    case QUERY_NODE_LOGIC_PLAN_AGG:
1024
      code = pushDownCondOptDealAgg(pCxt, (SAggLogicNode*)pLogicNode);
1025
      break;
1026 1027 1028
    case QUERY_NODE_LOGIC_PLAN_PROJECT:
      code = pushDownCondOptDealProject(pCxt, (SProjectLogicNode*)pLogicNode);
      break;
1029 1030
    case QUERY_NODE_LOGIC_PLAN_SORT:
    case QUERY_NODE_LOGIC_PLAN_PARTITION:
1031
      code = pushDownCondOptTrivialPushDown(pCxt, pLogicNode);
1032
      break;
1033 1034 1035 1036 1037 1038
    default:
      break;
  }
  if (TSDB_CODE_SUCCESS == code) {
    SNode* pChild = NULL;
    FOREACH(pChild, pLogicNode->pChildren) {
1039
      code = pushDownCondOptimizeImpl(pCxt, (SLogicNode*)pChild);
1040 1041 1042 1043 1044 1045 1046 1047
      if (TSDB_CODE_SUCCESS != code) {
        break;
      }
    }
  }
  return code;
}

1048 1049
static int32_t pushDownCondOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  return pushDownCondOptimizeImpl(pCxt, pLogicSubplan->pNode);
1050 1051
}

1052
static bool sortPriKeyOptIsPriKeyOrderBy(SNodeList* pSortKeys) {
X
Xiaoyu Wang 已提交
1053 1054 1055
  if (1 != LIST_LENGTH(pSortKeys)) {
    return false;
  }
X
Xiaoyu Wang 已提交
1056
  SNode* pNode = ((SOrderByExprNode*)nodesListGetNode(pSortKeys, 0))->pExpr;
X
Xiaoyu Wang 已提交
1057 1058 1059
  return (QUERY_NODE_COLUMN == nodeType(pNode) ? (PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)pNode)->colId) : false);
}

1060
static bool sortPriKeyOptMayBeOptimized(SLogicNode* pNode) {
X
Xiaoyu Wang 已提交
1061 1062 1063
  if (QUERY_NODE_LOGIC_PLAN_SORT != nodeType(pNode)) {
    return false;
  }
1064 1065
  SSortLogicNode* pSort = (SSortLogicNode*)pNode;
  if (pSort->groupSort || !sortPriKeyOptIsPriKeyOrderBy(pSort->pSortKeys) || 1 != LIST_LENGTH(pSort->node.pChildren)) {
X
Xiaoyu Wang 已提交
1066
    return false;
X
Xiaoyu Wang 已提交
1067 1068 1069 1070
  }
  return true;
}

X
Xiaoyu Wang 已提交
1071 1072
static int32_t sortPriKeyOptGetSequencingNodesImpl(SLogicNode* pNode, bool* pNotOptimize,
                                                   SNodeList** pSequencingNodes) {
X
Xiaoyu Wang 已提交
1073
  switch (nodeType(pNode)) {
1074 1075
    case QUERY_NODE_LOGIC_PLAN_SCAN: {
      SScanLogicNode* pScan = (SScanLogicNode*)pNode;
1076
      if (NULL != pScan->pGroupTags || TSDB_SYSTEM_TABLE == pScan->tableType) {
1077 1078 1079
        *pNotOptimize = true;
        return TSDB_CODE_SUCCESS;
      }
X
Xiaoyu Wang 已提交
1080
      return nodesListMakeAppend(pSequencingNodes, (SNode*)pNode);
1081 1082
    }
    case QUERY_NODE_LOGIC_PLAN_JOIN: {
X
Xiaoyu Wang 已提交
1083 1084
      int32_t code = sortPriKeyOptGetSequencingNodesImpl((SLogicNode*)nodesListGetNode(pNode->pChildren, 0),
                                                         pNotOptimize, pSequencingNodes);
X
Xiaoyu Wang 已提交
1085
      if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
1086 1087
        code = sortPriKeyOptGetSequencingNodesImpl((SLogicNode*)nodesListGetNode(pNode->pChildren, 1), pNotOptimize,
                                                   pSequencingNodes);
X
Xiaoyu Wang 已提交
1088 1089
      }
      return code;
1090
    }
X
Xiaoyu Wang 已提交
1091 1092
    case QUERY_NODE_LOGIC_PLAN_WINDOW:
      return nodesListMakeAppend(pSequencingNodes, (SNode*)pNode);
X
Xiaoyu Wang 已提交
1093
    case QUERY_NODE_LOGIC_PLAN_AGG:
1094
    case QUERY_NODE_LOGIC_PLAN_PARTITION:
X
Xiaoyu Wang 已提交
1095
      *pNotOptimize = true;
1096
      return TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
1097 1098 1099 1100 1101 1102
    default:
      break;
  }

  if (1 != LIST_LENGTH(pNode->pChildren)) {
    *pNotOptimize = true;
1103
    return TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
1104 1105
  }

X
Xiaoyu Wang 已提交
1106 1107
  return sortPriKeyOptGetSequencingNodesImpl((SLogicNode*)nodesListGetNode(pNode->pChildren, 0), pNotOptimize,
                                             pSequencingNodes);
X
Xiaoyu Wang 已提交
1108 1109
}

X
Xiaoyu Wang 已提交
1110
static int32_t sortPriKeyOptGetSequencingNodes(SLogicNode* pNode, SNodeList** pSequencingNodes) {
X
Xiaoyu Wang 已提交
1111
  bool    notOptimize = false;
X
Xiaoyu Wang 已提交
1112
  int32_t code = sortPriKeyOptGetSequencingNodesImpl(pNode, &notOptimize, pSequencingNodes);
X
Xiaoyu Wang 已提交
1113
  if (TSDB_CODE_SUCCESS != code || notOptimize) {
X
Xiaoyu Wang 已提交
1114
    NODES_CLEAR_LIST(*pSequencingNodes);
X
Xiaoyu Wang 已提交
1115 1116 1117 1118
  }
  return code;
}

1119
static EOrder sortPriKeyOptGetPriKeyOrder(SSortLogicNode* pSort) {
X
Xiaoyu Wang 已提交
1120 1121 1122
  return ((SOrderByExprNode*)nodesListGetNode(pSort->pSortKeys, 0))->order;
}

1123
static int32_t sortPriKeyOptApply(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan, SSortLogicNode* pSort,
X
Xiaoyu Wang 已提交
1124
                                  SNodeList* pSequencingNodes) {
1125
  EOrder order = sortPriKeyOptGetPriKeyOrder(pSort);
X
Xiaoyu Wang 已提交
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
  SNode* pSequencingNode = NULL;
  FOREACH(pSequencingNode, pSequencingNodes) {
    if (QUERY_NODE_LOGIC_PLAN_SCAN == nodeType(pSequencingNode)) {
      SScanLogicNode* pScan = (SScanLogicNode*)pSequencingNode;
      if ((ORDER_DESC == order && pScan->scanSeq[0] > 0) || (ORDER_ASC == order && pScan->scanSeq[1] > 0)) {
        TSWAP(pScan->scanSeq[0], pScan->scanSeq[1]);
      }
      if (TSDB_SUPER_TABLE == pScan->tableType) {
        pScan->scanType = SCAN_TYPE_TABLE_MERGE;
        pScan->node.resultDataOrder = DATA_ORDER_LEVEL_GLOBAL;
        pScan->node.requireDataOrder = DATA_ORDER_LEVEL_GLOBAL;
      }
      pScan->sortPrimaryKey = true;
    } else if (QUERY_NODE_LOGIC_PLAN_WINDOW == nodeType(pSequencingNode)) {
      ((SWindowLogicNode*)pSequencingNode)->outputTsOrder = order;
1141
    }
X
Xiaoyu Wang 已提交
1142
    optSetParentOrder(((SLogicNode*)pSequencingNode)->pParent, order);
X
Xiaoyu Wang 已提交
1143
  }
X
Xiaoyu Wang 已提交
1144

X
Xiaoyu Wang 已提交
1145 1146 1147 1148 1149
  SLogicNode* pChild = (SLogicNode*)nodesListGetNode(pSort->node.pChildren, 0);
  if (NULL == pSort->node.pParent) {
    TSWAP(pSort->node.pTargets, pChild->pTargets);
  }
  int32_t code = replaceLogicNode(pLogicSubplan, (SLogicNode*)pSort, pChild);
1150 1151 1152
  if (TSDB_CODE_SUCCESS == code) {
    NODES_CLEAR_LIST(pSort->node.pChildren);
    nodesDestroyNode((SNode*)pSort);
X
Xiaoyu Wang 已提交
1153
  }
1154
  pCxt->optimized = true;
1155
  return code;
X
Xiaoyu Wang 已提交
1156 1157
}

1158
static int32_t sortPrimaryKeyOptimizeImpl(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan, SSortLogicNode* pSort) {
X
Xiaoyu Wang 已提交
1159 1160 1161 1162 1163
  SNodeList* pSequencingNodes = NULL;
  int32_t    code =
      sortPriKeyOptGetSequencingNodes((SLogicNode*)nodesListGetNode(pSort->node.pChildren, 0), &pSequencingNodes);
  if (TSDB_CODE_SUCCESS == code && NULL != pSequencingNodes) {
    code = sortPriKeyOptApply(pCxt, pLogicSubplan, pSort, pSequencingNodes);
X
Xiaoyu Wang 已提交
1164
  }
X
Xiaoyu Wang 已提交
1165
  nodesClearList(pSequencingNodes);
X
Xiaoyu Wang 已提交
1166 1167 1168
  return code;
}

1169 1170
static int32_t sortPrimaryKeyOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  SSortLogicNode* pSort = (SSortLogicNode*)optFindPossibleNode(pLogicSubplan->pNode, sortPriKeyOptMayBeOptimized);
X
Xiaoyu Wang 已提交
1171 1172 1173
  if (NULL == pSort) {
    return TSDB_CODE_SUCCESS;
  }
1174
  return sortPrimaryKeyOptimizeImpl(pCxt, pLogicSubplan, pSort);
X
Xiaoyu Wang 已提交
1175 1176
}

1177
static bool smaIndexOptMayBeOptimized(SLogicNode* pNode) {
X
Xiaoyu Wang 已提交
1178 1179 1180
  if (QUERY_NODE_LOGIC_PLAN_SCAN != nodeType(pNode) || NULL == pNode->pParent ||
      QUERY_NODE_LOGIC_PLAN_WINDOW != nodeType(pNode->pParent) ||
      WINDOW_TYPE_INTERVAL != ((SWindowLogicNode*)pNode->pParent)->winType) {
X
Xiaoyu Wang 已提交
1181 1182 1183 1184
    return false;
  }

  SScanLogicNode* pScan = (SScanLogicNode*)pNode;
X
Xiaoyu Wang 已提交
1185
  if (NULL == pScan->pSmaIndexes || NULL != pScan->node.pConditions) {
X
Xiaoyu Wang 已提交
1186 1187 1188
    return false;
  }

X
Xiaoyu Wang 已提交
1189
  return true;
X
Xiaoyu Wang 已提交
1190 1191
}

1192 1193
static int32_t smaIndexOptCreateSmaScan(SScanLogicNode* pScan, STableIndexInfo* pIndex, SNodeList* pCols,
                                        SLogicNode** pOutput) {
1194
  SScanLogicNode* pSmaScan = (SScanLogicNode*)nodesMakeNode(QUERY_NODE_LOGIC_PLAN_SCAN);
X
Xiaoyu Wang 已提交
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
  if (NULL == pSmaScan) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  pSmaScan->pScanCols = pCols;
  pSmaScan->tableType = TSDB_SUPER_TABLE;
  pSmaScan->tableId = pIndex->dstTbUid;
  pSmaScan->stableId = pIndex->dstTbUid;
  pSmaScan->scanType = SCAN_TYPE_TABLE;
  pSmaScan->scanSeq[0] = pScan->scanSeq[0];
  pSmaScan->scanSeq[1] = pScan->scanSeq[1];
  pSmaScan->scanRange = pScan->scanRange;
  pSmaScan->dataRequired = FUNC_DATA_REQUIRED_DATA_LOAD;

  pSmaScan->pVgroupList = taosMemoryCalloc(1, sizeof(SVgroupsInfo) + sizeof(SVgroupInfo));
X
Xiaoyu Wang 已提交
1209 1210
  pSmaScan->node.pTargets = nodesCloneList(pCols);
  if (NULL == pSmaScan->pVgroupList || NULL == pSmaScan->node.pTargets) {
1211
    nodesDestroyNode((SNode*)pSmaScan);
X
Xiaoyu Wang 已提交
1212 1213 1214 1215 1216 1217
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  pSmaScan->pVgroupList->numOfVgroups = 1;
  pSmaScan->pVgroupList->vgroups[0].vgId = pIndex->dstVgId;
  memcpy(&(pSmaScan->pVgroupList->vgroups[0].epSet), &pIndex->epSet, sizeof(SEpSet));

X
Xiaoyu Wang 已提交
1218
  *pOutput = (SLogicNode*)pSmaScan;
X
Xiaoyu Wang 已提交
1219 1220 1221
  return TSDB_CODE_SUCCESS;
}

1222
static bool smaIndexOptEqualInterval(SScanLogicNode* pScan, SWindowLogicNode* pWindow, STableIndexInfo* pIndex) {
X
Xiaoyu Wang 已提交
1223 1224 1225 1226 1227
  if (pWindow->interval != pIndex->interval || pWindow->intervalUnit != pIndex->intervalUnit ||
      pWindow->offset != pIndex->offset || pWindow->sliding != pIndex->sliding ||
      pWindow->slidingUnit != pIndex->slidingUnit) {
    return false;
  }
X
Xiaoyu Wang 已提交
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
  if (IS_TSWINDOW_SPECIFIED(pScan->scanRange)) {
    SInterval interval = {.interval = pIndex->interval,
                          .intervalUnit = pIndex->intervalUnit,
                          .offset = pIndex->offset,
                          .offsetUnit = TIME_UNIT_MILLISECOND,
                          .sliding = pIndex->sliding,
                          .slidingUnit = pIndex->slidingUnit,
                          .precision = pScan->node.precision};
    return (pScan->scanRange.skey == taosTimeTruncate(pScan->scanRange.skey, &interval, pScan->node.precision)) &&
           (pScan->scanRange.ekey + 1 == taosTimeTruncate(pScan->scanRange.ekey + 1, &interval, pScan->node.precision));
  }
X
Xiaoyu Wang 已提交
1239 1240 1241
  return true;
}

1242
static SNode* smaIndexOptCreateSmaCol(SNode* pFunc, uint64_t tableId, int32_t colId) {
1243
  SColumnNode* pCol = (SColumnNode*)nodesMakeNode(QUERY_NODE_COLUMN);
X
Xiaoyu Wang 已提交
1244 1245 1246 1247 1248 1249 1250
  if (NULL == pCol) {
    return NULL;
  }
  pCol->tableId = tableId;
  pCol->tableType = TSDB_SUPER_TABLE;
  pCol->colId = colId;
  pCol->colType = COLUMN_TYPE_COLUMN;
X
Xiaoyu Wang 已提交
1251
  strcpy(pCol->colName, ((SExprNode*)pFunc)->aliasName);
X
Xiaoyu Wang 已提交
1252 1253 1254 1255 1256
  pCol->node.resType = ((SExprNode*)pFunc)->resType;
  strcpy(pCol->node.aliasName, ((SExprNode*)pFunc)->aliasName);
  return (SNode*)pCol;
}

1257
static int32_t smaIndexOptFindSmaFunc(SNode* pQueryFunc, SNodeList* pSmaFuncs) {
X
Xiaoyu Wang 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
  int32_t index = 0;
  SNode*  pSmaFunc = NULL;
  FOREACH(pSmaFunc, pSmaFuncs) {
    if (nodesEqualNode(pQueryFunc, pSmaFunc)) {
      return index;
    }
    ++index;
  }
  return -1;
}

1269 1270
static int32_t smaIndexOptCreateSmaCols(SNodeList* pFuncs, uint64_t tableId, SNodeList* pSmaFuncs, SNodeList** pOutput,
                                        int32_t* pWStrartIndex) {
X
Xiaoyu Wang 已提交
1271 1272 1273 1274
  SNodeList* pCols = NULL;
  SNode*     pFunc = NULL;
  int32_t    code = TSDB_CODE_SUCCESS;
  int32_t    index = 0;
X
Xiaoyu Wang 已提交
1275
  int32_t    smaFuncIndex = -1;
X
Xiaoyu Wang 已提交
1276
  *pWStrartIndex = -1;
X
Xiaoyu Wang 已提交
1277
  FOREACH(pFunc, pFuncs) {
1278
    if (FUNCTION_TYPE_WSTART == ((SFunctionNode*)pFunc)->funcType) {
X
Xiaoyu Wang 已提交
1279 1280
      *pWStrartIndex = index;
    }
1281
    smaFuncIndex = smaIndexOptFindSmaFunc(pFunc, pSmaFuncs);
X
Xiaoyu Wang 已提交
1282 1283 1284
    if (smaFuncIndex < 0) {
      break;
    } else {
1285
      code = nodesListMakeStrictAppend(&pCols, smaIndexOptCreateSmaCol(pFunc, tableId, smaFuncIndex + 1));
X
Xiaoyu Wang 已提交
1286 1287 1288 1289 1290 1291 1292
      if (TSDB_CODE_SUCCESS != code) {
        break;
      }
    }
    ++index;
  }

X
Xiaoyu Wang 已提交
1293
  if (TSDB_CODE_SUCCESS == code && smaFuncIndex >= 0) {
X
Xiaoyu Wang 已提交
1294 1295 1296 1297 1298 1299 1300 1301
    *pOutput = pCols;
  } else {
    nodesDestroyList(pCols);
  }

  return code;
}

1302 1303
static int32_t smaIndexOptCouldApplyIndex(SScanLogicNode* pScan, STableIndexInfo* pIndex, SNodeList** pCols,
                                          int32_t* pWStrartIndex) {
X
Xiaoyu Wang 已提交
1304
  SWindowLogicNode* pWindow = (SWindowLogicNode*)pScan->node.pParent;
1305
  if (!smaIndexOptEqualInterval(pScan, pWindow, pIndex)) {
X
Xiaoyu Wang 已提交
1306 1307 1308 1309 1310
    return TSDB_CODE_SUCCESS;
  }
  SNodeList* pSmaFuncs = NULL;
  int32_t    code = nodesStringToList(pIndex->expr, &pSmaFuncs);
  if (TSDB_CODE_SUCCESS == code) {
1311
    code = smaIndexOptCreateSmaCols(pWindow->pFuncs, pIndex->dstTbUid, pSmaFuncs, pCols, pWStrartIndex);
X
Xiaoyu Wang 已提交
1312 1313 1314 1315 1316
  }
  nodesDestroyList(pSmaFuncs);
  return code;
}

1317 1318
static int32_t smaIndexOptApplyIndex(SLogicSubplan* pLogicSubplan, SScanLogicNode* pScan, STableIndexInfo* pIndex,
                                     SNodeList* pSmaCols, int32_t wstrartIndex) {
X
Xiaoyu Wang 已提交
1319
  SLogicNode* pSmaScan = NULL;
1320
  int32_t     code = smaIndexOptCreateSmaScan(pScan, pIndex, pSmaCols, &pSmaScan);
X
Xiaoyu Wang 已提交
1321 1322 1323 1324 1325 1326
  if (TSDB_CODE_SUCCESS == code) {
    code = replaceLogicNode(pLogicSubplan, pScan->node.pParent, pSmaScan);
  }
  return code;
}

1327
static void smaIndexOptDestroySmaIndex(void* p) { taosMemoryFree(((STableIndexInfo*)p)->expr); }
X
Xiaoyu Wang 已提交
1328

1329
static int32_t smaIndexOptimizeImpl(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan, SScanLogicNode* pScan) {
X
Xiaoyu Wang 已提交
1330
  int32_t code = TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
1331 1332 1333 1334 1335
  int32_t nindexes = taosArrayGetSize(pScan->pSmaIndexes);
  for (int32_t i = 0; i < nindexes; ++i) {
    STableIndexInfo* pIndex = taosArrayGet(pScan->pSmaIndexes, i);
    SNodeList*       pSmaCols = NULL;
    int32_t          wstrartIndex = -1;
1336
    code = smaIndexOptCouldApplyIndex(pScan, pIndex, &pSmaCols, &wstrartIndex);
X
Xiaoyu Wang 已提交
1337
    if (TSDB_CODE_SUCCESS == code && NULL != pSmaCols) {
1338 1339
      code = smaIndexOptApplyIndex(pLogicSubplan, pScan, pIndex, pSmaCols, wstrartIndex);
      taosArrayDestroyEx(pScan->pSmaIndexes, smaIndexOptDestroySmaIndex);
X
Xiaoyu Wang 已提交
1340
      pScan->pSmaIndexes = NULL;
1341
      pCxt->optimized = true;
X
Xiaoyu Wang 已提交
1342
      break;
X
Xiaoyu Wang 已提交
1343 1344
    }
  }
X
Xiaoyu Wang 已提交
1345
  return code;
X
Xiaoyu Wang 已提交
1346
}
X
Xiaoyu Wang 已提交
1347

1348 1349
static int32_t smaIndexOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  SScanLogicNode* pScan = (SScanLogicNode*)optFindPossibleNode(pLogicSubplan->pNode, smaIndexOptMayBeOptimized);
X
Xiaoyu Wang 已提交
1350 1351 1352
  if (NULL == pScan) {
    return TSDB_CODE_SUCCESS;
  }
1353
  return smaIndexOptimizeImpl(pCxt, pLogicSubplan, pScan);
X
Xiaoyu Wang 已提交
1354 1355
}

X
Xiaoyu Wang 已提交
1356 1357
static EDealRes partTagsOptHasColImpl(SNode* pNode, void* pContext) {
  if (QUERY_NODE_COLUMN == nodeType(pNode)) {
X
Xiaoyu Wang 已提交
1358
    if (COLUMN_TYPE_TAG != ((SColumnNode*)pNode)->colType && COLUMN_TYPE_TBNAME != ((SColumnNode*)pNode)->colType) {
X
Xiaoyu Wang 已提交
1359 1360 1361 1362 1363 1364 1365
      *(bool*)pContext = true;
      return DEAL_RES_END;
    }
  }
  return DEAL_RES_CONTINUE;
}

S
slzhou@taodata.com 已提交
1366
static bool planOptNodeListHasCol(SNodeList* pKeys) {
X
Xiaoyu Wang 已提交
1367
  bool hasCol = false;
S
slzhou@taodata.com 已提交
1368
  nodesWalkExprs(pKeys, partTagsOptHasColImpl, &hasCol);
X
Xiaoyu Wang 已提交
1369 1370 1371
  return hasCol;
}

1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
static EDealRes partTagsOptHasTbname(SNode* pNode, void* pContext) {
  if (QUERY_NODE_COLUMN == nodeType(pNode)) {
    if (COLUMN_TYPE_TBNAME == ((SColumnNode*)pNode)->colType) {
      *(bool*)pContext = true;
      return DEAL_RES_END;
    }
  }
  return DEAL_RES_CONTINUE;
}

static bool planOptNodeListHasTbname(SNodeList* pKeys) {
  bool hasCol = false;
  nodesWalkExprs(pKeys, partTagsOptHasTbname, &hasCol);
  return hasCol;
}

X
Xiaoyu Wang 已提交
1388
static bool partTagsIsOptimizableNode(SLogicNode* pNode) {
X
Xiaoyu Wang 已提交
1389
  return ((QUERY_NODE_LOGIC_PLAN_PARTITION == nodeType(pNode) ||
X
Xiaoyu Wang 已提交
1390
           (QUERY_NODE_LOGIC_PLAN_AGG == nodeType(pNode) && NULL != ((SAggLogicNode*)pNode)->pGroupKeys &&
X
Xiaoyu Wang 已提交
1391
            NULL != ((SAggLogicNode*)pNode)->pAggFuncs)) &&
X
Xiaoyu Wang 已提交
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403
          1 == LIST_LENGTH(pNode->pChildren) &&
          QUERY_NODE_LOGIC_PLAN_SCAN == nodeType(nodesListGetNode(pNode->pChildren, 0)));
}

static SNodeList* partTagsGetPartKeys(SLogicNode* pNode) {
  if (QUERY_NODE_LOGIC_PLAN_PARTITION == nodeType(pNode)) {
    return ((SPartitionLogicNode*)pNode)->pPartitionKeys;
  } else {
    return ((SAggLogicNode*)pNode)->pGroupKeys;
  }
}

1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
static SNodeList* partTagsGetFuncs(SLogicNode* pNode) {
  if (QUERY_NODE_LOGIC_PLAN_PARTITION == nodeType(pNode)) {
    return NULL;
  } else {
    return ((SAggLogicNode*)pNode)->pAggFuncs;
  }
}

static bool partTagsOptAreSupportedFuncs(SNodeList* pFuncs) {
  SNode* pFunc = NULL;
  FOREACH(pFunc, pFuncs) {
    if (fmIsIndefiniteRowsFunc(((SFunctionNode*)pFunc)->funcId) && !fmIsSelectFunc(((SFunctionNode*)pFunc)->funcId)) {
      return false;
    }
  }
  return true;
}

X
Xiaoyu Wang 已提交
1422
static bool partTagsOptMayBeOptimized(SLogicNode* pNode) {
X
Xiaoyu Wang 已提交
1423
  if (!partTagsIsOptimizableNode(pNode)) {
X
Xiaoyu Wang 已提交
1424 1425 1426
    return false;
  }

S
slzhou@taodata.com 已提交
1427
  return !planOptNodeListHasCol(partTagsGetPartKeys(pNode)) && partTagsOptAreSupportedFuncs(partTagsGetFuncs(pNode));
X
Xiaoyu Wang 已提交
1428 1429
}

X
Xiaoyu Wang 已提交
1430 1431
static int32_t partTagsOptRebuildTbanme(SNodeList* pPartKeys) {
  int32_t code = TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
1432
  nodesRewriteExprs(pPartKeys, optRebuildTbanme, &code);
X
Xiaoyu Wang 已提交
1433 1434 1435
  return code;
}

1436 1437 1438 1439 1440
// todo refact: just to mask compilation warnings
static void partTagsSetAlias(char* pAlias, int32_t len, const char* pTableAlias, const char* pColName) {
  snprintf(pAlias, len, "%s.%s", pTableAlias, pColName);
}

1441
static SNode* partTagsCreateWrapperFunc(const char* pFuncName, SNode* pNode) {
1442 1443 1444 1445 1446
  SFunctionNode* pFunc = (SFunctionNode*)nodesMakeNode(QUERY_NODE_FUNCTION);
  if (NULL == pFunc) {
    return NULL;
  }

X
Xiaoyu Wang 已提交
1447
  snprintf(pFunc->functionName, sizeof(pFunc->functionName), "%s", pFuncName);
X
Xiaoyu Wang 已提交
1448
  if (QUERY_NODE_COLUMN == nodeType(pNode) && COLUMN_TYPE_TBNAME != ((SColumnNode*)pNode)->colType) {
1449
    SColumnNode* pCol = (SColumnNode*)pNode;
1450
    partTagsSetAlias(pFunc->node.aliasName, sizeof(pFunc->node.aliasName), pCol->tableAlias, pCol->colName);
1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
  } else {
    strcpy(pFunc->node.aliasName, ((SExprNode*)pNode)->aliasName);
  }
  int32_t code = nodesListMakeStrictAppend(&pFunc->pParameterList, nodesCloneNode(pNode));
  if (TSDB_CODE_SUCCESS == code) {
    code = fmGetFuncInfo(pFunc, NULL, 0);
  }

  if (TSDB_CODE_SUCCESS != code) {
    nodesDestroyNode((SNode*)pFunc);
    return NULL;
  }

  return (SNode*)pFunc;
}

1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
static bool partTagsHasIndefRowsSelectFunc(SNodeList* pFuncs) {
  SNode* pFunc = NULL;
  FOREACH(pFunc, pFuncs) {
    if (fmIsIndefiniteRowsFunc(((SFunctionNode*)pFunc)->funcId)) {
      return true;
    }
  }
  return false;
}

1477
static int32_t partTagsRewriteGroupTagsToFuncs(SNodeList* pGroupTags, int32_t start, SNodeList* pAggFuncs) {
1478 1479
  bool    hasIndefRowsSelectFunc = partTagsHasIndefRowsSelectFunc(pAggFuncs);
  int32_t code = TSDB_CODE_SUCCESS;
1480
  int32_t index = 0;
1481
  SNode*  pNode = NULL;
1482
  FOREACH(pNode, pGroupTags) {
1483 1484 1485
    if (index++ < start) {
      continue;
    }
1486 1487 1488 1489 1490
    if (hasIndefRowsSelectFunc) {
      code = nodesListStrictAppend(pAggFuncs, partTagsCreateWrapperFunc("_select_value", pNode));
    } else {
      code = nodesListStrictAppend(pAggFuncs, partTagsCreateWrapperFunc("_group_key", pNode));
    }
1491
    if (TSDB_CODE_SUCCESS != code) {
1492
      break;
1493 1494
    }
  }
1495
  return code;
1496 1497
}

X
Xiaoyu Wang 已提交
1498
static int32_t partTagsOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
X
Xiaoyu Wang 已提交
1499 1500
  SLogicNode* pNode = optFindPossibleNode(pLogicSubplan->pNode, partTagsOptMayBeOptimized);
  if (NULL == pNode) {
X
Xiaoyu Wang 已提交
1501 1502 1503
    return TSDB_CODE_SUCCESS;
  }

X
Xiaoyu Wang 已提交
1504 1505 1506
  int32_t         code = TSDB_CODE_SUCCESS;
  SScanLogicNode* pScan = (SScanLogicNode*)nodesListGetNode(pNode->pChildren, 0);
  if (QUERY_NODE_LOGIC_PLAN_PARTITION == nodeType(pNode)) {
1507
    TSWAP(((SPartitionLogicNode*)pNode)->pPartitionKeys, pScan->pGroupTags);
1508 1509
    TSWAP(((SPartitionLogicNode*)pNode)->pTags, pScan->pTags);
    TSWAP(((SPartitionLogicNode*)pNode)->pSubtable, pScan->pSubtable);
X
Xiaoyu Wang 已提交
1510
    int32_t code = replaceLogicNode(pLogicSubplan, pNode, (SLogicNode*)pScan);
X
Xiaoyu Wang 已提交
1511 1512 1513
    if (TSDB_CODE_SUCCESS == code) {
      code = adjustLogicNodeDataRequirement((SLogicNode*)pScan, pNode->resultDataOrder);
    }
X
Xiaoyu Wang 已提交
1514 1515 1516 1517 1518
    if (TSDB_CODE_SUCCESS == code) {
      NODES_CLEAR_LIST(pNode->pChildren);
      nodesDestroyNode((SNode*)pNode);
    }
  } else {
1519
    SAggLogicNode* pAgg = (SAggLogicNode*)pNode;
1520
    int32_t        start = -1;
1521 1522
    SNode*         pGroupKey = NULL;
    FOREACH(pGroupKey, pAgg->pGroupKeys) {
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535
      SNode* pGroupExpr = nodesListGetNode(((SGroupingSetNode*)pGroupKey)->pParameterList, 0);
      if (NULL != pScan->pGroupTags) {
        SNode* pGroupTag = NULL;
        FOREACH(pGroupTag, pScan->pGroupTags) {
          if (nodesEqualNode(pGroupTag, pGroupExpr)) {
            continue;
          }
        }
      }
      if (start < 0) {
        start = LIST_LENGTH(pScan->pGroupTags);
      }
      code = nodesListMakeStrictAppend(&pScan->pGroupTags, nodesCloneNode(pGroupExpr));
X
Xiaoyu Wang 已提交
1536 1537 1538 1539
      if (TSDB_CODE_SUCCESS != code) {
        break;
      }
    }
1540
    NODES_DESTORY_LIST(pAgg->pGroupKeys);
1541 1542 1543
    if (TSDB_CODE_SUCCESS == code && start >= 0) {
      code = partTagsRewriteGroupTagsToFuncs(pScan->pGroupTags, start, pAgg->pAggFuncs);
    }
X
Xiaoyu Wang 已提交
1544 1545
  }
  if (TSDB_CODE_SUCCESS == code) {
1546
    code = partTagsOptRebuildTbanme(pScan->pGroupTags);
X
Xiaoyu Wang 已提交
1547
  }
1548
  pCxt->optimized = true;
X
Xiaoyu Wang 已提交
1549 1550 1551
  return code;
}

S
slzhou 已提交
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569
static bool eliminateProjOptCheckProjColumnNames(SProjectLogicNode* pProjectNode) {
  SHashObj* pProjColNameHash = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
  SNode*    pProjection;
  FOREACH(pProjection, pProjectNode->pProjections) {
    char*    projColumnName = ((SColumnNode*)pProjection)->colName;
    int32_t* pExist = taosHashGet(pProjColNameHash, projColumnName, strlen(projColumnName));
    if (NULL != pExist) {
      taosHashCleanup(pProjColNameHash);
      return false;
    } else {
      int32_t exist = 1;
      taosHashPut(pProjColNameHash, projColumnName, strlen(projColumnName), &exist, sizeof(exist));
    }
  }
  taosHashCleanup(pProjColNameHash);
  return true;
}

1570
static bool eliminateProjOptMayBeOptimized(SLogicNode* pNode) {
X
Xiaoyu Wang 已提交
1571
  // TODO: enable this optimization after new mechanising that map projection and targets of project node
1572 1573 1574
  if (NULL != pNode->pParent) {
    return false;
  }
X
Xiaoyu Wang 已提交
1575

1576 1577 1578 1579
  // Super table scan requires project operator to merge packets to improve performance.
  if (QUERY_NODE_LOGIC_PLAN_PROJECT != nodeType(pNode) || 1 != LIST_LENGTH(pNode->pChildren) ||
      (QUERY_NODE_LOGIC_PLAN_SCAN == nodeType(nodesListGetNode(pNode->pChildren, 0)) &&
       TSDB_SUPER_TABLE == ((SScanLogicNode*)nodesListGetNode(pNode->pChildren, 0))->tableType)) {
1580 1581 1582 1583
    return false;
  }

  SProjectLogicNode* pProjectNode = (SProjectLogicNode*)pNode;
1584 1585
  if (NULL != pProjectNode->node.pLimit || NULL != pProjectNode->node.pSlimit ||
      NULL != pProjectNode->node.pConditions) {
1586 1587 1588
    return false;
  }

X
Xiaoyu Wang 已提交
1589
  SNode* pProjection;
1590 1591 1592 1593 1594 1595
  FOREACH(pProjection, pProjectNode->pProjections) {
    SExprNode* pExprNode = (SExprNode*)pProjection;
    if (QUERY_NODE_COLUMN != nodeType(pExprNode)) {
      return false;
    }
  }
1596

S
slzhou 已提交
1597
  return eliminateProjOptCheckProjColumnNames(pProjectNode);
1598 1599
}

1600 1601 1602 1603 1604 1605 1606 1607 1608 1609
typedef struct CheckNewChildTargetsCxt {
  SNodeList* pNewChildTargets;
  bool       canUse;
} CheckNewChildTargetsCxt;

static EDealRes eliminateProjOptCanUseNewChildTargetsImpl(SNode* pNode, void* pContext) {
  if (QUERY_NODE_COLUMN == nodeType(pNode)) {
    CheckNewChildTargetsCxt* pCxt = pContext;
    SNode*                   pTarget = NULL;
    FOREACH(pTarget, pCxt->pNewChildTargets) {
1610 1611 1612
      if (nodesEqualNode(pTarget, pNode)) {
        pCxt->canUse = true;
        return DEAL_RES_CONTINUE;
1613 1614
      }
    }
1615 1616
    pCxt->canUse = false;
    return DEAL_RES_END;
1617 1618 1619 1620
  }
  return DEAL_RES_CONTINUE;
}

1621 1622 1623 1624 1625
static bool eliminateProjOptCanChildConditionUseChildTargets(SLogicNode* pChild, SNodeList* pNewChildTargets) {
  if (NULL != pChild->pConditions) {
    CheckNewChildTargetsCxt cxt = {.pNewChildTargets = pNewChildTargets, .canUse = false};
    nodesWalkExpr(pChild->pConditions, eliminateProjOptCanUseNewChildTargetsImpl, &cxt);
    if (!cxt.canUse) return false;
1626
  }
1627
  if (QUERY_NODE_LOGIC_PLAN_JOIN == nodeType(pChild) && NULL != ((SJoinLogicNode*)pChild)->pOnConditions) {
1628
    SJoinLogicNode*         pJoinLogicNode = (SJoinLogicNode*)pChild;
1629 1630 1631 1632 1633
    CheckNewChildTargetsCxt cxt = {.pNewChildTargets = pNewChildTargets, .canUse = false};
    nodesWalkExpr(pJoinLogicNode->pOnConditions, eliminateProjOptCanUseNewChildTargetsImpl, &cxt);
    if (!cxt.canUse) return false;
  }
  return true;
1634 1635
}

D
dapan1121 已提交
1636 1637 1638 1639 1640 1641
static void alignProjectionWithTarget(SLogicNode* pNode) {
  if (QUERY_NODE_LOGIC_PLAN_PROJECT != pNode->type) {
    return;
  }

  SProjectLogicNode* pProjectNode = (SProjectLogicNode*)pNode;
1642
  SNode*             pProjection = NULL;
D
dapan1121 已提交
1643 1644
  FOREACH(pProjection, pProjectNode->pProjections) {
    SNode* pTarget = NULL;
1645
    bool   keep = false;
D
dapan1121 已提交
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
    FOREACH(pTarget, pNode->pTargets) {
      if (0 == strcmp(((SColumnNode*)pProjection)->node.aliasName, ((SColumnNode*)pTarget)->colName)) {
        keep = true;
        break;
      }
    }
    if (!keep) {
      nodesListErase(pProjectNode->pProjections, cell);
    }
  }
}

X
Xiaoyu Wang 已提交
1658 1659
static int32_t eliminateProjOptimizeImpl(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan,
                                         SProjectLogicNode* pProjectNode) {
1660
  SLogicNode* pChild = (SLogicNode*)nodesListGetNode(pProjectNode->node.pChildren, 0);
X
Xiaoyu Wang 已提交
1661
  SNodeList*  pNewChildTargets = nodesMakeList();
1662 1663 1664 1665 1666

  SNode* pProjection = NULL;
  FOREACH(pProjection, pProjectNode->pProjections) {
    SNode* pChildTarget = NULL;
    FOREACH(pChildTarget, pChild->pTargets) {
1667
      if (0 == strcmp(((SColumnNode*)pProjection)->colName, ((SColumnNode*)pChildTarget)->colName)) {
1668
        nodesListAppend(pNewChildTargets, nodesCloneNode(pChildTarget));
1669
        break;
1670 1671 1672
      }
    }
  }
1673
  if (eliminateProjOptCanChildConditionUseChildTargets(pChild, pNewChildTargets)) {
1674 1675 1676 1677 1678 1679
    nodesDestroyList(pChild->pTargets);
    pChild->pTargets = pNewChildTargets;
  } else {
    nodesDestroyList(pNewChildTargets);
    return TSDB_CODE_SUCCESS;
  }
X
Xiaoyu Wang 已提交
1680

1681 1682 1683 1684
  int32_t code = replaceLogicNode(pLogicSubplan, (SLogicNode*)pProjectNode, pChild);
  if (TSDB_CODE_SUCCESS == code) {
    NODES_CLEAR_LIST(pProjectNode->node.pChildren);
    nodesDestroyNode((SNode*)pProjectNode);
1685
    // if pChild is a project logic node, remove its projection which is not reference by its target.
D
dapan1121 已提交
1686
    alignProjectionWithTarget(pChild);
1687
  }
1688
  pCxt->optimized = true;
1689 1690 1691 1692 1693
  return code;
}

static int32_t eliminateProjOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  SProjectLogicNode* pProjectNode =
X
Xiaoyu Wang 已提交
1694
      (SProjectLogicNode*)optFindPossibleNode(pLogicSubplan->pNode, eliminateProjOptMayBeOptimized);
1695 1696 1697 1698 1699 1700 1701 1702

  if (NULL == pProjectNode) {
    return TSDB_CODE_SUCCESS;
  }

  return eliminateProjOptimizeImpl(pCxt, pLogicSubplan, pProjectNode);
}

1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726
static bool rewriteTailOptMayBeOptimized(SLogicNode* pNode) {
  return QUERY_NODE_LOGIC_PLAN_INDEF_ROWS_FUNC == nodeType(pNode) && ((SIndefRowsFuncLogicNode*)pNode)->isTailFunc;
}

static SNode* rewriteTailOptCreateOrderByExpr(SNode* pSortKey) {
  SOrderByExprNode* pOrder = (SOrderByExprNode*)nodesMakeNode(QUERY_NODE_ORDER_BY_EXPR);
  if (NULL == pOrder) {
    return NULL;
  }
  pOrder->order = ORDER_DESC;
  pOrder->pExpr = nodesCloneNode(pSortKey);
  if (NULL == pOrder->pExpr) {
    nodesDestroyNode((SNode*)pOrder);
    return NULL;
  }
  return (SNode*)pOrder;
}

static int32_t rewriteTailOptCreateLimit(SNode* pLimit, SNode* pOffset, SNode** pOutput) {
  SLimitNode* pLimitNode = (SLimitNode*)nodesMakeNode(QUERY_NODE_LIMIT);
  if (NULL == pLimitNode) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  pLimitNode->limit = NULL == pLimit ? -1 : ((SValueNode*)pLimit)->datum.i;
X
Xiaoyu Wang 已提交
1727
  pLimitNode->offset = NULL == pOffset ? 0 : ((SValueNode*)pOffset)->datum.i;
1728 1729 1730 1731 1732
  *pOutput = (SNode*)pLimitNode;
  return TSDB_CODE_SUCCESS;
}

static bool rewriteTailOptNeedGroupSort(SIndefRowsFuncLogicNode* pIndef) {
1733 1734 1735 1736 1737
  if (1 != LIST_LENGTH(pIndef->node.pChildren)) {
    return false;
  }
  SNode* pChild = nodesListGetNode(pIndef->node.pChildren, 0);
  return QUERY_NODE_LOGIC_PLAN_PARTITION == nodeType(pChild) ||
1738
         (QUERY_NODE_LOGIC_PLAN_SCAN == nodeType(pChild) && NULL != ((SScanLogicNode*)pChild)->pGroupTags);
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
}

static int32_t rewriteTailOptCreateSort(SIndefRowsFuncLogicNode* pIndef, SLogicNode** pOutput) {
  SSortLogicNode* pSort = (SSortLogicNode*)nodesMakeNode(QUERY_NODE_LOGIC_PLAN_SORT);
  if (NULL == pSort) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  pSort->groupSort = rewriteTailOptNeedGroupSort(pIndef);
  TSWAP(pSort->node.pChildren, pIndef->node.pChildren);
1749
  optResetParent((SLogicNode*)pSort);
1750 1751
  pSort->node.precision = pIndef->node.precision;

1752 1753 1754 1755 1756 1757 1758 1759 1760
  SFunctionNode* pTail = NULL;
  SNode*         pFunc = NULL;
  FOREACH(pFunc, pIndef->pFuncs) {
    if (FUNCTION_TYPE_TAIL == ((SFunctionNode*)pFunc)->funcType) {
      pTail = (SFunctionNode*)pFunc;
      break;
    }
  }

1761
  // tail(expr, [limit, offset,] _rowts)
1762
  int32_t rowtsIndex = LIST_LENGTH(pTail->pParameterList) - 1;
1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781

  int32_t code = nodesListMakeStrictAppend(
      &pSort->pSortKeys, rewriteTailOptCreateOrderByExpr(nodesListGetNode(pTail->pParameterList, rowtsIndex)));
  if (TSDB_CODE_SUCCESS == code) {
    pSort->node.pTargets = nodesCloneList(((SLogicNode*)nodesListGetNode(pSort->node.pChildren, 0))->pTargets);
    if (NULL == pSort->node.pTargets) {
      code = TSDB_CODE_OUT_OF_MEMORY;
    }
  }

  if (TSDB_CODE_SUCCESS == code) {
    *pOutput = (SLogicNode*)pSort;
  } else {
    nodesDestroyNode((SNode*)pSort);
  }

  return code;
}

1782 1783
static SNode* rewriteTailOptCreateProjectExpr(SFunctionNode* pFunc) {
  SNode* pExpr = nodesCloneNode(nodesListGetNode(pFunc->pParameterList, 0));
1784 1785 1786
  if (NULL == pExpr) {
    return NULL;
  }
1787
  strcpy(((SExprNode*)pExpr)->aliasName, pFunc->node.aliasName);
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
  return pExpr;
}

static int32_t rewriteTailOptCreateProject(SIndefRowsFuncLogicNode* pIndef, SLogicNode** pOutput) {
  SProjectLogicNode* pProject = (SProjectLogicNode*)nodesMakeNode(QUERY_NODE_LOGIC_PLAN_PROJECT);
  if (NULL == pProject) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  TSWAP(pProject->node.pTargets, pIndef->node.pTargets);
  pProject->node.precision = pIndef->node.precision;

1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
  int32_t        code = TSDB_CODE_SUCCESS;
  SFunctionNode* pTail = NULL;
  SNode*         pFunc = NULL;
  FOREACH(pFunc, pIndef->pFuncs) {
    code = nodesListMakeStrictAppend(&pProject->pProjections, rewriteTailOptCreateProjectExpr((SFunctionNode*)pFunc));
    if (TSDB_CODE_SUCCESS != code) {
      break;
    }
    if (FUNCTION_TYPE_TAIL == ((SFunctionNode*)pFunc)->funcType) {
      pTail = (SFunctionNode*)pFunc;
    }
  }
X
Xiaoyu Wang 已提交
1812

1813 1814 1815
  // tail(expr, [limit, offset,] _rowts)
  int32_t limitIndex = LIST_LENGTH(pTail->pParameterList) > 2 ? 1 : -1;
  int32_t offsetIndex = LIST_LENGTH(pTail->pParameterList) > 3 ? 2 : -1;
X
Xiaoyu Wang 已提交
1816 1817 1818 1819 1820
  if (TSDB_CODE_SUCCESS == code) {
    code = rewriteTailOptCreateLimit(limitIndex < 0 ? NULL : nodesListGetNode(pTail->pParameterList, limitIndex),
                                     offsetIndex < 0 ? NULL : nodesListGetNode(pTail->pParameterList, offsetIndex),
                                     &pProject->node.pLimit);
  }
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
  if (TSDB_CODE_SUCCESS == code) {
    *pOutput = (SLogicNode*)pProject;
  } else {
    nodesDestroyNode((SNode*)pProject);
  }
  return code;
}

static int32_t rewriteTailOptimizeImpl(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan,
                                       SIndefRowsFuncLogicNode* pIndef) {
  SLogicNode* pSort = NULL;
  SLogicNode* pProject = NULL;
  int32_t     code = rewriteTailOptCreateSort(pIndef, &pSort);
  if (TSDB_CODE_SUCCESS == code) {
    code = rewriteTailOptCreateProject(pIndef, &pProject);
  }
  if (TSDB_CODE_SUCCESS == code) {
    code = nodesListMakeAppend(&pProject->pChildren, (SNode*)pSort);
    pSort->pParent = pProject;
    pSort = NULL;
  }
  if (TSDB_CODE_SUCCESS == code) {
    code = replaceLogicNode(pLogicSubplan, (SLogicNode*)pIndef, pProject);
  }
  if (TSDB_CODE_SUCCESS == code) {
    nodesDestroyNode((SNode*)pIndef);
  } else {
    nodesDestroyNode((SNode*)pSort);
    nodesDestroyNode((SNode*)pProject);
  }
1851
  pCxt->optimized = true;
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865
  return code;
}

static int32_t rewriteTailOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  SIndefRowsFuncLogicNode* pIndef =
      (SIndefRowsFuncLogicNode*)optFindPossibleNode(pLogicSubplan->pNode, rewriteTailOptMayBeOptimized);

  if (NULL == pIndef) {
    return TSDB_CODE_SUCCESS;
  }

  return rewriteTailOptimizeImpl(pCxt, pLogicSubplan, pIndef);
}

S
slzhou 已提交
1866 1867 1868
static bool eliminateSetOpMayBeOptimized(SLogicNode* pNode) {
  SLogicNode* pParent = pNode->pParent;
  if (NULL == pParent ||
X
Xiaoyu Wang 已提交
1869
      QUERY_NODE_LOGIC_PLAN_AGG != nodeType(pParent) && QUERY_NODE_LOGIC_PLAN_PROJECT != nodeType(pParent) ||
S
slzhou 已提交
1870 1871 1872
      LIST_LENGTH(pParent->pChildren) < 2) {
    return false;
  }
X
Xiaoyu Wang 已提交
1873
  if (nodeType(pNode) != nodeType(pNode->pParent) || LIST_LENGTH(pNode->pChildren) < 2) {
S
slzhou 已提交
1874 1875 1876 1877 1878
    return false;
  }
  return true;
}

X
Xiaoyu Wang 已提交
1879 1880
static int32_t eliminateSetOpOptimizeImpl(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan,
                                          SLogicNode* pSetOpNode) {
S
slzhou 已提交
1881 1882 1883 1884
  SNode* pSibling;
  FOREACH(pSibling, pSetOpNode->pParent->pChildren) {
    if (nodesEqualNode(pSibling, (SNode*)pSetOpNode)) {
      SNode* pChild;
X
Xiaoyu Wang 已提交
1885
      FOREACH(pChild, pSetOpNode->pChildren) { ((SLogicNode*)pChild)->pParent = pSetOpNode->pParent; }
S
slzhou 已提交
1886 1887
      INSERT_LIST(pSetOpNode->pParent->pChildren, pSetOpNode->pChildren);

S
slzhou 已提交
1888 1889
      pSetOpNode->pChildren = NULL;
      ERASE_NODE(pSetOpNode->pParent->pChildren);
1890
      pCxt->optimized = true;
S
slzhou 已提交
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
      return TSDB_CODE_SUCCESS;
    }
  }

  return TSDB_CODE_PLAN_INTERNAL_ERROR;
}

static int32_t eliminateSetOpOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  SLogicNode* pSetOpNode = optFindPossibleNode(pLogicSubplan->pNode, eliminateSetOpMayBeOptimized);
  if (NULL == pSetOpNode) {
    return TSDB_CODE_SUCCESS;
  }

  return eliminateSetOpOptimizeImpl(pCxt, pLogicSubplan, pSetOpNode);
}

1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
static bool rewriteUniqueOptMayBeOptimized(SLogicNode* pNode) {
  return QUERY_NODE_LOGIC_PLAN_INDEF_ROWS_FUNC == nodeType(pNode) && ((SIndefRowsFuncLogicNode*)pNode)->isUniqueFunc;
}

static SNode* rewriteUniqueOptCreateGroupingSet(SNode* pExpr) {
  SGroupingSetNode* pGroupingSet = (SGroupingSetNode*)nodesMakeNode(QUERY_NODE_GROUPING_SET);
  if (NULL == pGroupingSet) {
    return NULL;
  }
  pGroupingSet->groupingSetType = GP_TYPE_NORMAL;
  SExprNode* pGroupExpr = (SExprNode*)nodesCloneNode(pExpr);
  if (TSDB_CODE_SUCCESS != nodesListMakeStrictAppend(&pGroupingSet->pParameterList, (SNode*)pGroupExpr)) {
    nodesDestroyNode((SNode*)pGroupingSet);
    return NULL;
  }
  return (SNode*)pGroupingSet;
}

static SNode* rewriteUniqueOptCreateFirstFunc(SFunctionNode* pSelectValue, SNode* pCol) {
  SFunctionNode* pFunc = (SFunctionNode*)nodesMakeNode(QUERY_NODE_FUNCTION);
  if (NULL == pFunc) {
    return NULL;
  }

  strcpy(pFunc->functionName, "first");
  if (NULL != pSelectValue) {
1933
    strcpy(pFunc->node.aliasName, pSelectValue->node.aliasName);
1934
  } else {
X
Xiaoyu Wang 已提交
1935 1936
    int64_t pointer = (int64_t)pFunc;
    snprintf(pFunc->node.aliasName, sizeof(pFunc->node.aliasName), "%s.%" PRId64 "", pFunc->functionName, pointer);
1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
  }
  int32_t code = nodesListMakeStrictAppend(&pFunc->pParameterList, nodesCloneNode(pCol));
  if (TSDB_CODE_SUCCESS == code) {
    code = fmGetFuncInfo(pFunc, NULL, 0);
  }

  if (TSDB_CODE_SUCCESS != code) {
    nodesDestroyNode((SNode*)pFunc);
    return NULL;
  }

  return (SNode*)pFunc;
}

static int32_t rewriteUniqueOptCreateAgg(SIndefRowsFuncLogicNode* pIndef, SLogicNode** pOutput) {
  SAggLogicNode* pAgg = (SAggLogicNode*)nodesMakeNode(QUERY_NODE_LOGIC_PLAN_AGG);
  if (NULL == pAgg) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  TSWAP(pAgg->node.pChildren, pIndef->node.pChildren);
1958
  optResetParent((SLogicNode*)pAgg);
1959
  pAgg->node.precision = pIndef->node.precision;
1960 1961
  pAgg->node.requireDataOrder = DATA_ORDER_LEVEL_IN_BLOCK;  // first function requirement
  pAgg->node.resultDataOrder = DATA_ORDER_LEVEL_NONE;
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033

  int32_t code = TSDB_CODE_SUCCESS;
  bool    hasSelectPrimaryKey = false;
  SNode*  pPrimaryKey = NULL;
  SNode*  pNode = NULL;
  FOREACH(pNode, pIndef->pFuncs) {
    SFunctionNode* pFunc = (SFunctionNode*)pNode;
    SNode*         pExpr = nodesListGetNode(pFunc->pParameterList, 0);
    if (FUNCTION_TYPE_UNIQUE == pFunc->funcType) {
      pPrimaryKey = nodesListGetNode(pFunc->pParameterList, 1);
      code = nodesListMakeStrictAppend(&pAgg->pGroupKeys, rewriteUniqueOptCreateGroupingSet(pExpr));
    } else if (PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)pExpr)->colId) {  // _select_value(ts) => first(ts)
      hasSelectPrimaryKey = true;
      code = nodesListMakeStrictAppend(&pAgg->pAggFuncs, rewriteUniqueOptCreateFirstFunc(pFunc, pExpr));
    } else {  // _select_value(other_col)
      code = nodesListMakeStrictAppend(&pAgg->pAggFuncs, nodesCloneNode(pNode));
    }
    if (TSDB_CODE_SUCCESS != code) {
      break;
    }
  }

  if (TSDB_CODE_SUCCESS == code) {
    code = createColumnByRewriteExprs(pAgg->pGroupKeys, &pAgg->node.pTargets);
  }
  if (TSDB_CODE_SUCCESS == code && NULL != pAgg->pAggFuncs) {
    code = createColumnByRewriteExprs(pAgg->pAggFuncs, &pAgg->node.pTargets);
  }

  if (TSDB_CODE_SUCCESS == code && !hasSelectPrimaryKey && NULL != pAgg->pAggFuncs) {
    code = nodesListMakeStrictAppend(&pAgg->pAggFuncs, rewriteUniqueOptCreateFirstFunc(NULL, pPrimaryKey));
  }

  if (TSDB_CODE_SUCCESS == code) {
    *pOutput = (SLogicNode*)pAgg;
  } else {
    nodesDestroyNode((SNode*)pAgg);
  }
  return code;
}

static SNode* rewriteUniqueOptCreateProjectCol(SFunctionNode* pFunc) {
  SColumnNode* pCol = (SColumnNode*)nodesMakeNode(QUERY_NODE_COLUMN);
  if (NULL == pCol) {
    return NULL;
  }

  pCol->node.resType = pFunc->node.resType;
  if (FUNCTION_TYPE_UNIQUE == pFunc->funcType) {
    SExprNode* pExpr = (SExprNode*)nodesListGetNode(pFunc->pParameterList, 0);
    if (QUERY_NODE_COLUMN == nodeType(pExpr)) {
      strcpy(pCol->tableAlias, ((SColumnNode*)pExpr)->tableAlias);
      strcpy(pCol->colName, ((SColumnNode*)pExpr)->colName);
    } else {
      strcpy(pCol->colName, pExpr->aliasName);
    }
  } else {
    strcpy(pCol->colName, pFunc->node.aliasName);
  }
  strcpy(pCol->node.aliasName, pFunc->node.aliasName);

  return (SNode*)pCol;
}

static int32_t rewriteUniqueOptCreateProject(SIndefRowsFuncLogicNode* pIndef, SLogicNode** pOutput) {
  SProjectLogicNode* pProject = (SProjectLogicNode*)nodesMakeNode(QUERY_NODE_LOGIC_PLAN_PROJECT);
  if (NULL == pProject) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  TSWAP(pProject->node.pTargets, pIndef->node.pTargets);
  pProject->node.precision = pIndef->node.precision;
2034 2035
  pProject->node.requireDataOrder = DATA_ORDER_LEVEL_NONE;
  pProject->node.resultDataOrder = DATA_ORDER_LEVEL_NONE;
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070

  int32_t code = TSDB_CODE_SUCCESS;
  SNode*  pNode = NULL;
  FOREACH(pNode, pIndef->pFuncs) {
    code = nodesListMakeStrictAppend(&pProject->pProjections, rewriteUniqueOptCreateProjectCol((SFunctionNode*)pNode));
    if (TSDB_CODE_SUCCESS != code) {
      break;
    }
  }

  if (TSDB_CODE_SUCCESS == code) {
    *pOutput = (SLogicNode*)pProject;
  } else {
    nodesDestroyNode((SNode*)pProject);
  }
  return code;
}

static int32_t rewriteUniqueOptimizeImpl(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan,
                                         SIndefRowsFuncLogicNode* pIndef) {
  SLogicNode* pAgg = NULL;
  SLogicNode* pProject = NULL;
  int32_t     code = rewriteUniqueOptCreateAgg(pIndef, &pAgg);
  if (TSDB_CODE_SUCCESS == code) {
    code = rewriteUniqueOptCreateProject(pIndef, &pProject);
  }
  if (TSDB_CODE_SUCCESS == code) {
    code = nodesListMakeAppend(&pProject->pChildren, (SNode*)pAgg);
  }
  if (TSDB_CODE_SUCCESS == code) {
    pAgg->pParent = pProject;
    pAgg = NULL;
    code = replaceLogicNode(pLogicSubplan, (SLogicNode*)pIndef, pProject);
  }
  if (TSDB_CODE_SUCCESS == code) {
2071 2072
    code = adjustLogicNodeDataRequirement(
        pProject, NULL == pProject->pParent ? DATA_ORDER_LEVEL_NONE : pProject->pParent->requireDataOrder);
2073
    pProject = NULL;
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
  }
  if (TSDB_CODE_SUCCESS == code) {
    nodesDestroyNode((SNode*)pIndef);
  } else {
    nodesDestroyNode((SNode*)pAgg);
    nodesDestroyNode((SNode*)pProject);
  }
  pCxt->optimized = true;
  return code;
}

static int32_t rewriteUniqueOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  SIndefRowsFuncLogicNode* pIndef =
      (SIndefRowsFuncLogicNode*)optFindPossibleNode(pLogicSubplan->pNode, rewriteUniqueOptMayBeOptimized);

  if (NULL == pIndef) {
    return TSDB_CODE_SUCCESS;
  }

  return rewriteUniqueOptimizeImpl(pCxt, pLogicSubplan, pIndef);
}

X
Xiaoyu Wang 已提交
2096 2097 2098 2099 2100 2101
typedef struct SLastRowScanOptLastParaCkCxt {
  bool hasTag;
  bool hasCol;
} SLastRowScanOptLastParaCkCxt;

static EDealRes lastRowScanOptLastParaCheckImpl(SNode* pNode, void* pContext) {
X
Xiaoyu Wang 已提交
2102
  if (QUERY_NODE_COLUMN == nodeType(pNode)) {
X
Xiaoyu Wang 已提交
2103
    SLastRowScanOptLastParaCkCxt* pCxt = pContext;
X
Xiaoyu Wang 已提交
2104
    if (COLUMN_TYPE_TAG == ((SColumnNode*)pNode)->colType || COLUMN_TYPE_TBNAME == ((SColumnNode*)pNode)->colType) {
X
Xiaoyu Wang 已提交
2105 2106 2107
      pCxt->hasTag = true;
    } else {
      pCxt->hasCol = true;
X
Xiaoyu Wang 已提交
2108
    }
X
Xiaoyu Wang 已提交
2109
    return DEAL_RES_END;
X
Xiaoyu Wang 已提交
2110 2111 2112 2113
  }
  return DEAL_RES_CONTINUE;
}

X
Xiaoyu Wang 已提交
2114 2115 2116 2117
static bool lastRowScanOptLastParaCheck(SNode* pExpr) {
  SLastRowScanOptLastParaCkCxt cxt = {.hasTag = false, .hasCol = false};
  nodesWalkExpr(pExpr, lastRowScanOptLastParaCheckImpl, &cxt);
  return !cxt.hasTag && cxt.hasCol;
X
Xiaoyu Wang 已提交
2118 2119
}

X
Xiaoyu Wang 已提交
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
static bool hasSuitableCache(int8_t cacheLastMode, bool hasLastRow, bool hasLast) {
  switch (cacheLastMode) {
    case TSDB_CACHE_MODEL_NONE:
      return false;
    case TSDB_CACHE_MODEL_LAST_ROW:
      return hasLastRow;
    case TSDB_CACHE_MODEL_LAST_VALUE:
      return hasLast;
    case TSDB_CACHE_MODEL_BOTH:
      return true;
    default:
      break;
  }
  return false;
}

2136
static bool lastRowScanOptMayBeOptimized(SLogicNode* pNode) {
X
Xiaoyu Wang 已提交
2137 2138 2139 2140 2141 2142 2143
  if (QUERY_NODE_LOGIC_PLAN_AGG != nodeType(pNode) || 1 != LIST_LENGTH(pNode->pChildren) ||
      QUERY_NODE_LOGIC_PLAN_SCAN != nodeType(nodesListGetNode(pNode->pChildren, 0))) {
    return false;
  }

  SAggLogicNode*  pAgg = (SAggLogicNode*)pNode;
  SScanLogicNode* pScan = (SScanLogicNode*)nodesListGetNode(pNode->pChildren, 0);
X
Xiaoyu Wang 已提交
2144 2145
  // Only one of LAST and LASTROW can appear
  if (pAgg->hasLastRow == pAgg->hasLast || NULL != pAgg->pGroupKeys || NULL != pScan->node.pConditions ||
X
Xiaoyu Wang 已提交
2146 2147
      !hasSuitableCache(pScan->cacheLastMode, pAgg->hasLastRow, pAgg->hasLast) ||
      IS_TSWINDOW_SPECIFIED(pScan->scanRange)) {
2148 2149 2150
    return false;
  }

X
Xiaoyu Wang 已提交
2151 2152
  bool   hasLastFunc = false;
  bool   hasSelectFunc = false;
2153 2154
  SNode* pFunc = NULL;
  FOREACH(pFunc, ((SAggLogicNode*)pNode)->pAggFuncs) {
X
Xiaoyu Wang 已提交
2155 2156
    SFunctionNode* pAggFunc = (SFunctionNode*)pFunc;
    if (FUNCTION_TYPE_LAST == pAggFunc->funcType) {
X
Xiaoyu Wang 已提交
2157
      if (hasSelectFunc || !lastRowScanOptLastParaCheck(nodesListGetNode(pAggFunc->pParameterList, 0))) {
X
Xiaoyu Wang 已提交
2158 2159 2160 2161 2162 2163 2164 2165 2166
        return false;
      }
      hasLastFunc = true;
    } else if (FUNCTION_TYPE_SELECT_VALUE == pAggFunc->funcType || FUNCTION_TYPE_GROUP_KEY == pAggFunc->funcType) {
      if (hasLastFunc) {
        return false;
      }
      hasSelectFunc = true;
    } else if (FUNCTION_TYPE_LAST_ROW != pAggFunc->funcType) {
2167 2168 2169 2170 2171 2172 2173
      return false;
    }
  }

  return true;
}

X
Xiaoyu Wang 已提交
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
typedef struct SLastRowScanOptSetColDataTypeCxt {
  bool       doAgg;
  SNodeList* pLastCols;
} SLastRowScanOptSetColDataTypeCxt;

static EDealRes lastRowScanOptSetColDataType(SNode* pNode, void* pContext) {
  if (QUERY_NODE_COLUMN == nodeType(pNode)) {
    SLastRowScanOptSetColDataTypeCxt* pCxt = pContext;
    if (pCxt->doAgg) {
      nodesListMakeAppend(&pCxt->pLastCols, pNode);
      getLastCacheDataType(&(((SColumnNode*)pNode)->node.resType));
    } else {
      SNode* pCol = NULL;
      FOREACH(pCol, pCxt->pLastCols) {
        if (nodesEqualNode(pCol, pNode)) {
          getLastCacheDataType(&(((SColumnNode*)pNode)->node.resType));
          break;
        }
      }
    }
    return DEAL_RES_IGNORE_CHILD;
  }
  return DEAL_RES_CONTINUE;
}

X
Xiaoyu Wang 已提交
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218
static void lastRowScanOptSetLastTargets(SNodeList* pTargets, SNodeList* pLastCols) {
  SNode* pTarget = NULL;
  WHERE_EACH(pTarget, pTargets) {
    bool   found = false;
    SNode* pCol = NULL;
    FOREACH(pCol, pLastCols) {
      if (nodesEqualNode(pCol, pTarget)) {
        getLastCacheDataType(&(((SColumnNode*)pTarget)->node.resType));
        found = true;
        break;
      }
    }
    if (!found) {
      ERASE_NODE(pTargets);
      continue;
    }
    WHERE_NEXT;
  }
}

2219 2220 2221 2222 2223 2224 2225
static int32_t lastRowScanOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  SAggLogicNode* pAgg = (SAggLogicNode*)optFindPossibleNode(pLogicSubplan->pNode, lastRowScanOptMayBeOptimized);

  if (NULL == pAgg) {
    return TSDB_CODE_SUCCESS;
  }

X
Xiaoyu Wang 已提交
2226 2227
  SLastRowScanOptSetColDataTypeCxt cxt = {.doAgg = true, .pLastCols = NULL};
  SNode*                           pNode = NULL;
2228 2229
  FOREACH(pNode, pAgg->pAggFuncs) {
    SFunctionNode* pFunc = (SFunctionNode*)pNode;
X
Xiaoyu Wang 已提交
2230 2231 2232 2233
    int32_t        funcType = pFunc->funcType;
    if (FUNCTION_TYPE_LAST_ROW == funcType || FUNCTION_TYPE_LAST == funcType) {
      int32_t len = snprintf(pFunc->functionName, sizeof(pFunc->functionName),
                             FUNCTION_TYPE_LAST_ROW == funcType ? "_cache_last_row" : "_cache_last");
2234 2235 2236
      pFunc->functionName[len] = '\0';
      int32_t code = fmGetFuncInfo(pFunc, NULL, 0);
      if (TSDB_CODE_SUCCESS != code) {
X
Xiaoyu Wang 已提交
2237
        nodesClearList(cxt.pLastCols);
2238 2239
        return code;
      }
X
Xiaoyu Wang 已提交
2240 2241
      if (FUNCTION_TYPE_LAST == funcType) {
        nodesWalkExpr(nodesListGetNode(pFunc->pParameterList, 0), lastRowScanOptSetColDataType, &cxt);
X
Xiaoyu Wang 已提交
2242
        nodesListErase(pFunc->pParameterList, nodesListGetCell(pFunc->pParameterList, 1));
X
Xiaoyu Wang 已提交
2243
      }
2244
    }
2245 2246
  }

X
Xiaoyu Wang 已提交
2247 2248 2249
  SScanLogicNode* pScan = (SScanLogicNode*)nodesListGetNode(pAgg->node.pChildren, 0);
  pScan->scanType = SCAN_TYPE_LAST_ROW;
  pScan->igLastNull = pAgg->hasLast ? true : false;
X
Xiaoyu Wang 已提交
2250 2251
  if (NULL != cxt.pLastCols) {
    cxt.doAgg = false;
X
Xiaoyu Wang 已提交
2252
    lastRowScanOptSetLastTargets(pScan->pScanCols, cxt.pLastCols);
X
Xiaoyu Wang 已提交
2253
    nodesWalkExprs(pScan->pScanPseudoCols, lastRowScanOptSetColDataType, &cxt);
X
Xiaoyu Wang 已提交
2254
    lastRowScanOptSetLastTargets(pScan->node.pTargets, cxt.pLastCols);
X
Xiaoyu Wang 已提交
2255 2256
    nodesClearList(cxt.pLastCols);
  }
X
Xiaoyu Wang 已提交
2257 2258
  pAgg->hasLastRow = false;
  pAgg->hasLast = false;
2259 2260 2261 2262 2263

  pCxt->optimized = true;
  return TSDB_CODE_SUCCESS;
}

S
slzhou 已提交
2264 2265 2266 2267 2268
// merge projects
static bool mergeProjectsMayBeOptimized(SLogicNode* pNode) {
  if (QUERY_NODE_LOGIC_PLAN_PROJECT != nodeType(pNode) || 1 != LIST_LENGTH(pNode->pChildren)) {
    return false;
  }
X
Xiaoyu Wang 已提交
2269
  SLogicNode* pChild = (SLogicNode*)nodesListGetNode(pNode->pChildren, 0);
S
slzhou 已提交
2270
  if (QUERY_NODE_LOGIC_PLAN_PROJECT != nodeType(pChild) || 1 < LIST_LENGTH(pChild->pChildren) ||
2271
      NULL != pChild->pConditions || NULL != pChild->pLimit || NULL != pChild->pSlimit) {
S
slzhou 已提交
2272 2273 2274 2275 2276 2277
    return false;
  }
  return true;
}

typedef struct SMergeProjectionsContext {
2278
  SProjectLogicNode* pChildProj;
X
Xiaoyu Wang 已提交
2279
  int32_t            errCode;
S
slzhou 已提交
2280 2281 2282
} SMergeProjectionsContext;

static EDealRes mergeProjectionsExpr(SNode** pNode, void* pContext) {
2283
  SMergeProjectionsContext* pCxt = pContext;
X
Xiaoyu Wang 已提交
2284
  SProjectLogicNode*        pChildProj = pCxt->pChildProj;
2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
  if (QUERY_NODE_COLUMN == nodeType(*pNode)) {
    SNode* pTarget;
    FOREACH(pTarget, ((SLogicNode*)pChildProj)->pTargets) {
      if (nodesEqualNode(pTarget, *pNode)) {
        SNode* pProjection;
        FOREACH(pProjection, pChildProj->pProjections) {
          if (0 == strcmp(((SColumnNode*)pTarget)->colName, ((SExprNode*)pProjection)->aliasName)) {
            SNode* pExpr = nodesCloneNode(pProjection);
            if (pExpr == NULL) {
              pCxt->errCode = terrno;
              return DEAL_RES_ERROR;
            }
2297 2298
            snprintf(((SExprNode*)pExpr)->aliasName, sizeof(((SExprNode*)pExpr)->aliasName), "%s",
                     ((SExprNode*)*pNode)->aliasName);
2299 2300
            nodesDestroyNode(*pNode);
            *pNode = pExpr;
2301
            return DEAL_RES_IGNORE_CHILD;
2302 2303 2304 2305 2306
          }
        }
      }
    }
  }
S
slzhou 已提交
2307 2308 2309
  return DEAL_RES_CONTINUE;
}

2310
static int32_t mergeProjectsOptimizeImpl(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan, SLogicNode* pSelfNode) {
2311
  SLogicNode* pChild = (SLogicNode*)nodesListGetNode(pSelfNode->pChildren, 0);
2312

2313
  SMergeProjectionsContext cxt = {.pChildProj = (SProjectLogicNode*)pChild, .errCode = TSDB_CODE_SUCCESS};
2314
  nodesRewriteExprs(((SProjectLogicNode*)pSelfNode)->pProjections, mergeProjectionsExpr, &cxt);
2315
  int32_t code = cxt.errCode;
2316

2317 2318 2319 2320 2321
  if (TSDB_CODE_SUCCESS == code) {
    if (1 == LIST_LENGTH(pChild->pChildren)) {
      SLogicNode* pGrandChild = (SLogicNode*)nodesListGetNode(pChild->pChildren, 0);
      code = replaceLogicNode(pLogicSubplan, pChild, pGrandChild);
    } else {  // no grand child
2322
      NODES_CLEAR_LIST(pSelfNode->pChildren);
2323 2324 2325 2326 2327 2328 2329
    }
  }

  if (TSDB_CODE_SUCCESS == code) {
    NODES_CLEAR_LIST(pChild->pChildren);
  }
  nodesDestroyNode((SNode*)pChild);
2330
  pCxt->optimized = true;
2331
  return code;
S
slzhou 已提交
2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342
}

static int32_t mergeProjectsOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  SLogicNode* pProjectNode = optFindPossibleNode(pLogicSubplan->pNode, mergeProjectsMayBeOptimized);
  if (NULL == pProjectNode) {
    return TSDB_CODE_SUCCESS;
  }

  return mergeProjectsOptimizeImpl(pCxt, pLogicSubplan, pProjectNode);
}

2343
static bool tagScanOptShouldBeOptimized(SLogicNode* pNode) {
S
slzhou@taodata.com 已提交
2344 2345 2346
  if (QUERY_NODE_LOGIC_PLAN_SCAN != nodeType(pNode) || (SCAN_TYPE_TAG == ((SScanLogicNode*)pNode)->scanType)) {
    return false;
  }
2347
  SScanLogicNode* pScan = (SScanLogicNode*)pNode;
2348
  if (pScan->hasNormalCols) {
2349 2350
    return false;
  }
2351 2352
  if (NULL == pNode->pParent || QUERY_NODE_LOGIC_PLAN_AGG != nodeType(pNode->pParent) ||
      1 != LIST_LENGTH(pNode->pParent->pChildren)) {
S
slzhou@taodata.com 已提交
2353 2354 2355 2356
    return false;
  }

  SAggLogicNode* pAgg = (SAggLogicNode*)(pNode->pParent);
2357 2358
  if (NULL == pAgg->pGroupKeys || NULL != pAgg->pAggFuncs || planOptNodeListHasCol(pAgg->pGroupKeys) ||
      !planOptNodeListHasTbname(pAgg->pGroupKeys)) {
S
slzhou@taodata.com 已提交
2359 2360
    return false;
  }
2361

2362 2363 2364 2365 2366 2367 2368 2369 2370
  SNode* pGroupKey = NULL;
  FOREACH(pGroupKey, pAgg->pGroupKeys) {
    SNode* pGroup = NULL;
    FOREACH(pGroup, ((SGroupingSetNode*)pGroupKey)->pParameterList) {
      if (QUERY_NODE_COLUMN != nodeType(pGroup)) {
        return false;
      }
    }
  }
S
slzhou@taodata.com 已提交
2371 2372 2373 2374
  return true;
}

static int32_t tagScanOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
2375
  SScanLogicNode* pScanNode = (SScanLogicNode*)optFindPossibleNode(pLogicSubplan->pNode, tagScanOptShouldBeOptimized);
S
slzhou@taodata.com 已提交
2376 2377 2378 2379 2380
  if (NULL == pScanNode) {
    return TSDB_CODE_SUCCESS;
  }

  pScanNode->scanType = SCAN_TYPE_TAG;
2381 2382
  SNode* pTarget = NULL;
  FOREACH(pTarget, pScanNode->node.pTargets) {
2383 2384 2385 2386
    if (PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)(pTarget))->colId) {
      ERASE_NODE(pScanNode->node.pTargets);
      break;
    }
2387
  }
2388

2389 2390
  NODES_DESTORY_LIST(pScanNode->pScanCols);

2391
  SLogicNode* pAgg = pScanNode->node.pParent;
2392 2393 2394 2395 2396 2397
  if (NULL == pAgg->pParent) {
    SNodeList* pScanTargets = nodesMakeList();

    SNode* pAggTarget = NULL;
    FOREACH(pAggTarget, pAgg->pTargets) {
      SNode* pScanTarget = NULL;
X
Xiaoyu Wang 已提交
2398
      FOREACH(pScanTarget, pScanNode->node.pTargets) {
2399
        if (0 == strcmp(((SColumnNode*)pAggTarget)->colName, ((SColumnNode*)pScanTarget)->colName)) {
2400 2401 2402 2403 2404 2405 2406 2407 2408
          nodesListAppend(pScanTargets, nodesCloneNode(pScanTarget));
          break;
        }
      }
    }
    nodesDestroyList(pScanNode->node.pTargets);
    pScanNode->node.pTargets = pScanTargets;
  }

2409 2410 2411 2412 2413
  int32_t code = replaceLogicNode(pLogicSubplan, pAgg, (SLogicNode*)pScanNode);
  if (TSDB_CODE_SUCCESS == code) {
    NODES_CLEAR_LIST(pAgg->pChildren);
  }
  nodesDestroyNode((SNode*)pAgg);
S
slzhou@taodata.com 已提交
2414 2415 2416 2417
  pCxt->optimized = true;
  return TSDB_CODE_SUCCESS;
}

2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440
static bool pushDownLimitOptShouldBeOptimized(SLogicNode* pNode) {
  if (NULL == pNode->pLimit || 1 != LIST_LENGTH(pNode->pChildren) ||
      QUERY_NODE_LOGIC_PLAN_SCAN != nodeType(nodesListGetNode(pNode->pChildren, 0))) {
    return false;
  }
  return true;
}

static int32_t pushDownLimitOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  SLogicNode* pNode = optFindPossibleNode(pLogicSubplan->pNode, pushDownLimitOptShouldBeOptimized);
  if (NULL == pNode) {
    return TSDB_CODE_SUCCESS;
  }

  SLogicNode* pChild = (SLogicNode*)nodesListGetNode(pNode->pChildren, 0);
  nodesDestroyNode(pChild->pLimit);
  pChild->pLimit = pNode->pLimit;
  pNode->pLimit = NULL;
  pCxt->optimized = true;

  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
2441 2442
// clang-format off
static const SOptimizeRule optimizeRuleSet[] = {
2443
  {.pName = "ScanPath",                   .optimizeFunc = scanPathOptimize},
2444 2445
  {.pName = "PushDownCondition",          .optimizeFunc = pushDownCondOptimize},
  {.pName = "SortPrimaryKey",             .optimizeFunc = sortPrimaryKeyOptimize},
2446
  {.pName = "SmaIndex",                   .optimizeFunc = smaIndexOptimize},
S
slzhou 已提交
2447
  {.pName = "PartitionTags",              .optimizeFunc = partTagsOptimize},
S
slzhou 已提交
2448
  {.pName = "MergeProjects",              .optimizeFunc = mergeProjectsOptimize},
S
slzhou 已提交
2449
  {.pName = "EliminateProject",           .optimizeFunc = eliminateProjOptimize},
X
Xiaoyu Wang 已提交
2450
  {.pName = "EliminateSetOperator",       .optimizeFunc = eliminateSetOpOptimize},
2451
  {.pName = "RewriteTail",                .optimizeFunc = rewriteTailOptimize},
2452
  {.pName = "RewriteUnique",              .optimizeFunc = rewriteUniqueOptimize},
X
Xiaoyu Wang 已提交
2453
  {.pName = "LastRowScan",                .optimizeFunc = lastRowScanOptimize},
2454
  {.pName = "TagScan",                    .optimizeFunc = tagScanOptimize},
2455
  {.pName = "PushDownLimit",              .optimizeFunc = pushDownLimitOptimize}
X
Xiaoyu Wang 已提交
2456 2457
};
// clang-format on
2458 2459 2460

static const int32_t optimizeRuleNum = (sizeof(optimizeRuleSet) / sizeof(SOptimizeRule));

2461
static void dumpLogicSubplan(const char* pRuleName, SLogicSubplan* pSubplan) {
2462
  if (!tsQueryPlannerTrace) {
2463 2464
    return;
  }
2465 2466
  char* pStr = NULL;
  nodesNodeToString((SNode*)pSubplan, false, &pStr, NULL);
2467 2468 2469 2470 2471
  if (NULL == pRuleName) {
    qDebugL("before optimize: %s", pStr);
  } else {
    qDebugL("apply optimize %s rule: %s", pRuleName, pStr);
  }
2472 2473 2474
  taosMemoryFree(pStr);
}

X
Xiaoyu Wang 已提交
2475
static int32_t applyOptimizeRule(SPlanContext* pCxt, SLogicSubplan* pLogicSubplan) {
X
Xiaoyu Wang 已提交
2476
  SOptimizeContext cxt = {.pPlanCxt = pCxt, .optimized = false};
2477
  bool             optimized = false;
2478
  dumpLogicSubplan(NULL, pLogicSubplan);
2479
  do {
2480
    optimized = false;
2481
    for (int32_t i = 0; i < optimizeRuleNum; ++i) {
2482
      cxt.optimized = false;
X
Xiaoyu Wang 已提交
2483
      int32_t code = optimizeRuleSet[i].optimizeFunc(&cxt, pLogicSubplan);
2484 2485 2486
      if (TSDB_CODE_SUCCESS != code) {
        return code;
      }
2487 2488 2489 2490
      if (cxt.optimized) {
        optimized = true;
        dumpLogicSubplan(optimizeRuleSet[i].pName, pLogicSubplan);
      }
2491
    }
2492
  } while (optimized);
X
Xiaoyu Wang 已提交
2493 2494
  return TSDB_CODE_SUCCESS;
}
2495

X
Xiaoyu Wang 已提交
2496
int32_t optimizeLogicPlan(SPlanContext* pCxt, SLogicSubplan* pLogicSubplan) {
2497 2498 2499
  if (SUBPLAN_TYPE_MODIFY == pLogicSubplan->subplanType && NULL == pLogicSubplan->pNode->pChildren) {
    return TSDB_CODE_SUCCESS;
  }
X
Xiaoyu Wang 已提交
2500
  return applyOptimizeRule(pCxt, pLogicSubplan);
X
Xiaoyu Wang 已提交
2501
}