planOptimizer.c 105.2 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"
X
Xiaoyu Wang 已提交
19
#include "systable.h"
20
#include "tglobal.h"
X
Xiaoyu Wang 已提交
21
#include "ttime.h"
X
Xiaoyu Wang 已提交
22

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

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

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

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

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

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

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

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

52 53 54
typedef struct SCpdIsMultiTableCondCxt {
  SNodeList* pLeftCols;
  SNodeList* pRightCols;
X
Xiaoyu Wang 已提交
55 56
  bool       havaLeftCol;
  bool       haveRightCol;
57 58 59 60 61 62 63 64 65 66
} 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 已提交
67
typedef bool (*FMayBeOptimized)(SLogicNode* pNode);
X
Xiaoyu Wang 已提交
68
typedef bool (*FShouldBeOptimized)(SLogicNode* pNode, void* pInfo);
X
Xiaoyu Wang 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83

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

X
Xiaoyu Wang 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96
static bool optFindEligibleNode(SLogicNode* pNode, FShouldBeOptimized func, void* pInfo) {
  if (func(pNode, pInfo)) {
    return true;
  }
  SNode* pChild;
  FOREACH(pChild, pNode->pChildren) {
    if (optFindEligibleNode((SLogicNode*)pChild, func, pInfo)) {
      return true;
    }
  }
  return false;
}

97 98 99 100 101
static void optResetParent(SLogicNode* pNode) {
  SNode* pChild = NULL;
  FOREACH(pChild, pNode->pChildren) { ((SLogicNode*)pChild)->pParent = pNode; }
}

X
Xiaoyu Wang 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
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;
}

119
static void optSetParentOrder(SLogicNode* pNode, EOrder order, SLogicNode* pNodeForcePropagate) {
X
Xiaoyu Wang 已提交
120 121 122
  if (NULL == pNode) {
    return;
  }
123
  pNode->inputTsOrder = order;
X
Xiaoyu Wang 已提交
124
  switch (nodeType(pNode)) {
125
    // for those nodes that will change the order, stop propagating
126
    // case QUERY_NODE_LOGIC_PLAN_WINDOW:
X
Xiaoyu Wang 已提交
127
    case QUERY_NODE_LOGIC_PLAN_JOIN:
128 129 130 131 132 133 134 135 136 137 138 139
    case QUERY_NODE_LOGIC_PLAN_AGG:
    case QUERY_NODE_LOGIC_PLAN_SORT:
      if (pNode == pNodeForcePropagate) {
        pNode->outputTsOrder = order;
        break;
      } else
        return;
    case QUERY_NODE_LOGIC_PLAN_WINDOW:
      // Window output ts order default to be asc, and changed when doing sort by primary key optimization.
      // We stop propagate the original order to parents.
      // Use window output ts order instead.
      order = pNode->outputTsOrder;
X
Xiaoyu Wang 已提交
140 141
      break;
    default:
142
      pNode->outputTsOrder = order;
X
Xiaoyu Wang 已提交
143 144
      break;
  }
145
  optSetParentOrder(pNode->pParent, order, pNodeForcePropagate);
X
Xiaoyu Wang 已提交
146 147
}

148
EDealRes scanPathOptHaveNormalColImpl(SNode* pNode, void* pContext) {
149
  if (QUERY_NODE_COLUMN == nodeType(pNode)) {
150 151
    *((bool*)pContext) =
        (COLUMN_TYPE_TAG != ((SColumnNode*)pNode)->colType && COLUMN_TYPE_TBNAME != ((SColumnNode*)pNode)->colType);
152 153 154 155 156
    return *((bool*)pContext) ? DEAL_RES_END : DEAL_RES_IGNORE_CHILD;
  }
  return DEAL_RES_CONTINUE;
}

157
static bool scanPathOptHaveNormalCol(SNodeList* pList) {
158
  bool res = false;
159
  nodesWalkExprsPostOrder(pList, scanPathOptHaveNormalColImpl, &res);
160 161 162
  return res;
}

163
static bool scanPathOptMayBeOptimized(SLogicNode* pNode) {
164
  if (OPTIMIZE_FLAG_TEST_MASK(pNode->optimizedFlag, OPTIMIZE_FLAG_SCAN_PATH)) {
165 166 167 168 169
    return false;
  }
  if (QUERY_NODE_LOGIC_PLAN_SCAN != nodeType(pNode)) {
    return false;
  }
170 171 172 173 174 175 176 177
  return true;
}

static bool scanPathOptShouldGetFuncs(SLogicNode* pNode) {
  if ((QUERY_NODE_LOGIC_PLAN_WINDOW == nodeType(pNode) &&
       WINDOW_TYPE_INTERVAL == ((SWindowLogicNode*)pNode)->winType) ||
      (QUERY_NODE_LOGIC_PLAN_PARTITION == nodeType(pNode) && pNode->pParent &&
       QUERY_NODE_LOGIC_PLAN_WINDOW == nodeType(pNode->pParent) &&
178
       WINDOW_TYPE_INTERVAL == ((SWindowLogicNode*)pNode->pParent)->winType)) {
5
54liuyao 已提交
179
    return true;
180
  }
181 182
  if (QUERY_NODE_LOGIC_PLAN_AGG == nodeType(pNode)) {
    return !scanPathOptHaveNormalCol(((SAggLogicNode*)pNode)->pGroupKeys);
183 184
  }
  return false;
185 186
}

187
static SNodeList* scanPathOptGetAllFuncs(SLogicNode* pNode) {
188
  if (!scanPathOptShouldGetFuncs(pNode)) return NULL;
189 190 191 192 193 194 195 196 197 198 199
  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;
}

200
static bool scanPathOptNeedOptimizeDataRequire(const SFunctionNode* pFunc) {
201 202 203 204 205 206 207 208 209 210 211 212
  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;
}

213
static bool scanPathOptNeedDynOptimize(const SFunctionNode* pFunc) {
214 215 216 217 218 219 220 221 222 223 224 225
  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;
}

226 227
static int32_t scanPathOptGetRelatedFuncs(SScanLogicNode* pScan, SNodeList** pSdrFuncs, SNodeList** pDsoFuncs) {
  SNodeList* pAllFuncs = scanPathOptGetAllFuncs(pScan->node.pParent);
X
Xiaoyu Wang 已提交
228 229
  SNodeList* pTmpSdrFuncs = NULL;
  SNodeList* pTmpDsoFuncs = NULL;
X
Xiaoyu Wang 已提交
230
  SNode*     pNode = NULL;
X
Xiaoyu Wang 已提交
231
  bool       otherFunc = false;
X
Xiaoyu Wang 已提交
232 233 234 235 236 237 238
  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 已提交
239 240
    } else {
      otherFunc = true;
X
Xiaoyu Wang 已提交
241
      break;
242 243
    }
    if (TSDB_CODE_SUCCESS != code) {
X
Xiaoyu Wang 已提交
244 245
      nodesDestroyList(pTmpSdrFuncs);
      nodesDestroyList(pTmpDsoFuncs);
246 247
      return code;
    }
X
Xiaoyu Wang 已提交
248
  }
X
Xiaoyu Wang 已提交
249 250 251 252 253 254 255
  if (otherFunc) {
    nodesDestroyList(pTmpSdrFuncs);
    nodesDestroyList(pTmpDsoFuncs);
  } else {
    *pSdrFuncs = pTmpSdrFuncs;
    *pDsoFuncs = pTmpDsoFuncs;
  }
256 257 258
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
259 260 261 262 263 264 265 266 267 268
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;
269
    } else if (FUNCTION_TYPE_LAST == pFunc->funcType || FUNCTION_TYPE_LAST_ROW == pFunc->funcType) {
X
Xiaoyu Wang 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
      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;
}

293 294
static int32_t scanPathOptMatch(SOptimizeContext* pCxt, SLogicNode* pLogicNode, SOsdInfo* pInfo) {
  pInfo->pScan = (SScanLogicNode*)optFindPossibleNode(pLogicNode, scanPathOptMayBeOptimized);
295 296 297
  if (NULL == pInfo->pScan) {
    return TSDB_CODE_SUCCESS;
  }
X
Xiaoyu Wang 已提交
298
  return scanPathOptSetOsdInfo(pInfo);
299 300
}

301
static EFuncDataRequired scanPathOptPromoteDataRequired(EFuncDataRequired l, EFuncDataRequired r) {
302
  switch (l) {
303
    case FUNC_DATA_REQUIRED_DATA_LOAD:
304
      return l;
H
Haojun Liao 已提交
305
    case FUNC_DATA_REQUIRED_SMA_LOAD:
306 307 308
      return FUNC_DATA_REQUIRED_DATA_LOAD == r ? r : l;
    case FUNC_DATA_REQUIRED_NOT_LOAD:
      return FUNC_DATA_REQUIRED_FILTEROUT == r ? l : r;
309 310 311 312 313 314
    default:
      break;
  }
  return r;
}

315
static int32_t scanPathOptGetDataRequired(SNodeList* pFuncs) {
316
  if (NULL == pFuncs) {
317
    return FUNC_DATA_REQUIRED_DATA_LOAD;
318
  }
319
  EFuncDataRequired dataRequired = FUNC_DATA_REQUIRED_FILTEROUT;
X
Xiaoyu Wang 已提交
320
  SNode*            pFunc = NULL;
321
  FOREACH(pFunc, pFuncs) {
322
    dataRequired = scanPathOptPromoteDataRequired(dataRequired, fmFuncDataRequired((SFunctionNode*)pFunc, NULL));
323 324 325 326
  }
  return dataRequired;
}

327
static void scanPathOptSetScanWin(SScanLogicNode* pScan) {
328
  SLogicNode* pParent = pScan->node.pParent;
X
Xiaoyu Wang 已提交
329 330
  if (QUERY_NODE_LOGIC_PLAN_PARTITION == nodeType(pParent) && pParent->pParent &&
      QUERY_NODE_LOGIC_PLAN_WINDOW == nodeType(pParent->pParent)) {
331 332 333 334 335 336 337 338
    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;
X
Xiaoyu Wang 已提交
339 340 341
  }
}

X
Xiaoyu Wang 已提交
342
static void scanPathOptSetScanOrder(EScanOrder scanOrder, SScanLogicNode* pScan) {
X
Xiaoyu Wang 已提交
343
  if (pScan->sortPrimaryKey || pScan->scanSeq[0] > 1 || pScan->scanSeq[1] > 1) {
X
Xiaoyu Wang 已提交
344 345 346 347 348 349
    return;
  }
  switch (scanOrder) {
    case SCAN_ORDER_ASC:
      pScan->scanSeq[0] = 1;
      pScan->scanSeq[1] = 0;
350
      optSetParentOrder(pScan->node.pParent, ORDER_ASC, NULL);
X
Xiaoyu Wang 已提交
351 352 353 354
      break;
    case SCAN_ORDER_DESC:
      pScan->scanSeq[0] = 0;
      pScan->scanSeq[1] = 1;
355
      optSetParentOrder(pScan->node.pParent, ORDER_DESC, NULL);
X
Xiaoyu Wang 已提交
356 357 358 359 360 361 362 363 364 365
      break;
    case SCAN_ORDER_BOTH:
      pScan->scanSeq[0] = 1;
      pScan->scanSeq[1] = 1;
      break;
    default:
      break;
  }
}

366 367 368 369 370 371 372 373 374 375 376 377
static void scanPathOptSetGroupOrderScan(SScanLogicNode* pScan) {
  if (pScan->tableType != TSDB_SUPER_TABLE) return;

  if (pScan->node.pParent && nodeType(pScan->node.pParent) == QUERY_NODE_LOGIC_PLAN_AGG) {
    SAggLogicNode* pAgg = (SAggLogicNode*)pScan->node.pParent;
    bool withSlimit = pAgg->node.pSlimit != NULL || (pAgg->node.pParent && pAgg->node.pParent->pSlimit);
    if (withSlimit && isPartTableAgg(pAgg)) {
      pScan->groupOrderScan = pAgg->node.forceCreateNonBlockingOptr = true;
    }
  }
}

378
static int32_t scanPathOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
X
Xiaoyu Wang 已提交
379
  SOsdInfo info = {.scanOrder = SCAN_ORDER_ASC};
380
  int32_t  code = scanPathOptMatch(pCxt, pLogicSubplan->pNode, &info);
5
54liuyao 已提交
381
  if (TSDB_CODE_SUCCESS == code && info.pScan) {
X
Xiaoyu Wang 已提交
382
    scanPathOptSetScanWin(info.pScan);
383 384 385
    if (!pCxt->pPlanCxt->streamQuery) {
      scanPathOptSetScanOrder(info.scanOrder, info.pScan);
    }
386
    scanPathOptSetGroupOrderScan(info.pScan);
5
54liuyao 已提交
387
  }
388
  if (TSDB_CODE_SUCCESS == code && (NULL != info.pDsoFuncs || NULL != info.pSdrFuncs)) {
389
    info.pScan->dataRequired = scanPathOptGetDataRequired(info.pSdrFuncs);
390
    info.pScan->pDynamicScanFuncs = info.pDsoFuncs;
X
Xiaoyu Wang 已提交
391 392
  }
  if (TSDB_CODE_SUCCESS == code && info.pScan) {
393
    OPTIMIZE_FLAG_SET_MASK(info.pScan->node.optimizedFlag, OPTIMIZE_FLAG_SCAN_PATH);
394 395 396 397 398 399
    pCxt->optimized = true;
  }
  nodesDestroyList(info.pSdrFuncs);
  return code;
}

400
static int32_t pushDownCondOptMergeCond(SNode** pDst, SNode** pSrc) {
401
  SLogicConditionNode* pLogicCond = (SLogicConditionNode*)nodesMakeNode(QUERY_NODE_LOGIC_CONDITION);
402 403 404
  if (NULL == pLogicCond) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
D
dapan1121 已提交
405 406
  pLogicCond->node.resType.type = TSDB_DATA_TYPE_BOOL;
  pLogicCond->node.resType.bytes = tDataTypes[TSDB_DATA_TYPE_BOOL].bytes;
407 408 409 410 411 412 413 414 415
  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 {
416
    nodesDestroyNode((SNode*)pLogicCond);
417 418 419 420
  }
  return code;
}

421
static int32_t pushDownCondOptAppendCond(SNode** pCond, SNode** pAdditionalCond) {
422
  if (NULL == *pCond) {
wafwerar's avatar
wafwerar 已提交
423
    TSWAP(*pCond, *pAdditionalCond);
424 425 426 427
    return TSDB_CODE_SUCCESS;
  }

  int32_t code = TSDB_CODE_SUCCESS;
428 429
  if (QUERY_NODE_LOGIC_CONDITION == nodeType(*pCond) &&
      LOGIC_COND_TYPE_AND == ((SLogicConditionNode*)*pCond)->condType) {
430 431 432 433 434
    code = nodesListAppend(((SLogicConditionNode*)*pCond)->pParameterList, *pAdditionalCond);
    if (TSDB_CODE_SUCCESS == code) {
      *pAdditionalCond = NULL;
    }
  } else {
435
    code = pushDownCondOptMergeCond(pCond, pAdditionalCond);
436 437 438 439
  }
  return code;
}

440 441
static int32_t pushDownCondOptCalcTimeRange(SOptimizeContext* pCxt, SScanLogicNode* pScan, SNode** pPrimaryKeyCond,
                                            SNode** pOtherCond) {
442 443
  int32_t code = TSDB_CODE_SUCCESS;
  if (pCxt->pPlanCxt->topicQuery || pCxt->pPlanCxt->streamQuery) {
444
    code = pushDownCondOptAppendCond(pOtherCond, pPrimaryKeyCond);
445 446 447 448 449 450 451
  } else {
    bool isStrict = false;
    code = filterGetTimeRange(*pPrimaryKeyCond, &pScan->scanRange, &isStrict);
    if (TSDB_CODE_SUCCESS == code) {
      if (isStrict) {
        nodesDestroyNode(*pPrimaryKeyCond);
      } else {
452
        code = pushDownCondOptAppendCond(pOtherCond, pPrimaryKeyCond);
453 454
      }
      *pPrimaryKeyCond = NULL;
455 456 457 458 459
    }
  }
  return code;
}

X
Xiaoyu Wang 已提交
460 461 462 463 464 465
static int32_t pushDownCondOptRebuildTbanme(SNode** pTagCond) {
  int32_t code = TSDB_CODE_SUCCESS;
  nodesRewriteExpr(pTagCond, optRebuildTbanme, &code);
  return code;
}

466 467 468
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 已提交
469
      TSDB_SYSTEM_TABLE == pScan->tableType) {
470 471 472
    return TSDB_CODE_SUCCESS;
  }

X
Xiaoyu Wang 已提交
473 474
  SNode*  pPrimaryKeyCond = NULL;
  SNode*  pOtherCond = NULL;
475 476
  int32_t code = filterPartitionCond(&pScan->node.pConditions, &pPrimaryKeyCond, &pScan->pTagIndexCond,
                                     &pScan->pTagCond, &pOtherCond);
X
Xiaoyu Wang 已提交
477 478 479
  if (TSDB_CODE_SUCCESS == code && NULL != pScan->pTagCond) {
    code = pushDownCondOptRebuildTbanme(&pScan->pTagCond);
  }
480
  if (TSDB_CODE_SUCCESS == code && NULL != pPrimaryKeyCond) {
481
    code = pushDownCondOptCalcTimeRange(pCxt, pScan, &pPrimaryKeyCond, &pOtherCond);
482 483 484 485 486
  }
  if (TSDB_CODE_SUCCESS == code) {
    pScan->node.pConditions = pOtherCond;
  }

X
Xiaoyu Wang 已提交
487
  if (TSDB_CODE_SUCCESS == code) {
488
    OPTIMIZE_FLAG_SET_MASK(pScan->node.optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE);
X
Xiaoyu Wang 已提交
489 490
    pCxt->optimized = true;
  } else {
491 492 493 494 495 496 497
    nodesDestroyNode(pPrimaryKeyCond);
    nodesDestroyNode(pOtherCond);
  }

  return code;
}

498
static bool pushDownCondOptBelongThisTable(SNode* pCondCol, SNodeList* pTableCols) {
499 500 501 502 503 504 505
  SNode* pTableCol = NULL;
  FOREACH(pTableCol, pTableCols) {
    if (nodesEqualNode(pCondCol, pTableCol)) {
      return true;
    }
  }
  return false;
506 507
}

508
static EDealRes pushDownCondOptIsCrossTableCond(SNode* pNode, void* pContext) {
509 510
  SCpdIsMultiTableCondCxt* pCxt = pContext;
  if (QUERY_NODE_COLUMN == nodeType(pNode)) {
511
    if (pushDownCondOptBelongThisTable(pNode, pCxt->pLeftCols)) {
512
      pCxt->havaLeftCol = true;
513
    } else if (pushDownCondOptBelongThisTable(pNode, pCxt->pRightCols)) {
514 515 516 517 518
      pCxt->haveRightCol = true;
    }
    return pCxt->havaLeftCol && pCxt->haveRightCol ? DEAL_RES_END : DEAL_RES_CONTINUE;
  }
  return DEAL_RES_CONTINUE;
519 520
}

521 522
static ECondAction pushDownCondOptGetCondAction(EJoinType joinType, SNodeList* pLeftCols, SNodeList* pRightCols,
                                                SNode* pNode) {
X
Xiaoyu Wang 已提交
523 524
  SCpdIsMultiTableCondCxt cxt = {
      .pLeftCols = pLeftCols, .pRightCols = pRightCols, .havaLeftCol = false, .haveRightCol = false};
525
  nodesWalkExpr(pNode, pushDownCondOptIsCrossTableCond, &cxt);
X
Xiaoyu Wang 已提交
526 527 528 529 530
  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)));
531 532
}

533 534
static int32_t pushDownCondOptPartLogicCond(SJoinLogicNode* pJoin, SNode** pOnCond, SNode** pLeftChildCond,
                                            SNode** pRightChildCond) {
535 536 537 538 539 540 541
  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 已提交
542
  int32_t    code = TSDB_CODE_SUCCESS;
543 544 545 546 547

  SNodeList* pOnConds = NULL;
  SNodeList* pLeftChildConds = NULL;
  SNodeList* pRightChildConds = NULL;
  SNodeList* pRemainConds = NULL;
X
Xiaoyu Wang 已提交
548
  SNode*     pCond = NULL;
549
  FOREACH(pCond, pLogicCond->pParameterList) {
550
    ECondAction condAction = pushDownCondOptGetCondAction(pJoin->joinType, pLeftCols, pRightCols, pCond);
551 552 553 554 555 556 557 558
    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));
559
    }
560 561
    if (TSDB_CODE_SUCCESS != code) {
      break;
562 563
    }
  }
564 565 566 567 568 569

  SNode* pTempOnCond = NULL;
  SNode* pTempLeftChildCond = NULL;
  SNode* pTempRightChildCond = NULL;
  SNode* pTempRemainCond = NULL;
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
570
    code = nodesMergeConds(&pTempOnCond, &pOnConds);
571 572
  }
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
573
    code = nodesMergeConds(&pTempLeftChildCond, &pLeftChildConds);
574 575
  }
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
576
    code = nodesMergeConds(&pTempRightChildCond, &pRightChildConds);
577 578
  }
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
579
    code = nodesMergeConds(&pTempRemainCond, &pRemainConds);
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
  }

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

602 603
static int32_t pushDownCondOptPartOpCond(SJoinLogicNode* pJoin, SNode** pOnCond, SNode** pLeftChildCond,
                                         SNode** pRightChildCond) {
X
Xiaoyu Wang 已提交
604 605
  SNodeList*  pLeftCols = ((SLogicNode*)nodesListGetNode(pJoin->node.pChildren, 0))->pTargets;
  SNodeList*  pRightCols = ((SLogicNode*)nodesListGetNode(pJoin->node.pChildren, 1))->pTargets;
606 607
  ECondAction condAction =
      pushDownCondOptGetCondAction(pJoin->joinType, pLeftCols, pRightCols, pJoin->node.pConditions);
608 609 610 611 612 613 614 615 616 617
  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;
618 619 620
  return TSDB_CODE_SUCCESS;
}

621 622
static int32_t pushDownCondOptPartCond(SJoinLogicNode* pJoin, SNode** pOnCond, SNode** pLeftChildCond,
                                       SNode** pRightChildCond) {
623
  if (QUERY_NODE_LOGIC_CONDITION == nodeType(pJoin->node.pConditions)) {
624
    return pushDownCondOptPartLogicCond(pJoin, pOnCond, pLeftChildCond, pRightChildCond);
625
  } else {
626
    return pushDownCondOptPartOpCond(pJoin, pOnCond, pLeftChildCond, pRightChildCond);
627 628 629
  }
}

630 631
static int32_t pushDownCondOptPushCondToOnCond(SOptimizeContext* pCxt, SJoinLogicNode* pJoin, SNode** pCond) {
  return pushDownCondOptAppendCond(&pJoin->pOnConditions, pCond);
632 633
}

634
static int32_t pushDownCondOptPushCondToChild(SOptimizeContext* pCxt, SLogicNode* pChild, SNode** pCond) {
635
  return pushDownCondOptAppendCond(&pChild->pConditions, pCond);
636 637
}

638
static bool pushDownCondOptIsPriKey(SNode* pNode, SNodeList* pTableCols) {
X
Xiaoyu Wang 已提交
639 640 641 642
  if (QUERY_NODE_COLUMN != nodeType(pNode)) {
    return false;
  }
  SColumnNode* pCol = (SColumnNode*)pNode;
643
  if (PRIMARYKEY_TIMESTAMP_COL_ID != pCol->colId || TSDB_SYSTEM_TABLE == pCol->tableType) {
X
Xiaoyu Wang 已提交
644 645
    return false;
  }
646
  return pushDownCondOptBelongThisTable(pNode, pTableCols);
X
Xiaoyu Wang 已提交
647 648
}

649
static bool pushDownCondOptIsPriKeyEqualCond(SJoinLogicNode* pJoin, SNode* pCond) {
X
Xiaoyu Wang 已提交
650 651 652
  if (QUERY_NODE_OPERATOR != nodeType(pCond)) {
    return false;
  }
653

654
  SOperatorNode* pOper = (SOperatorNode*)pCond;
655 656 657 658 659 660
  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;
661 662 663 664
  if (pushDownCondOptIsPriKey(pOper->pLeft, pLeftCols)) {
    return pushDownCondOptIsPriKey(pOper->pRight, pRightCols);
  } else if (pushDownCondOptIsPriKey(pOper->pLeft, pRightCols)) {
    return pushDownCondOptIsPriKey(pOper->pRight, pLeftCols);
X
Xiaoyu Wang 已提交
665 666 667 668
  }
  return false;
}

669
static bool pushDownCondOptContainPriKeyEqualCond(SJoinLogicNode* pJoin, SNode* pCond) {
670 671 672 673
  if (QUERY_NODE_LOGIC_CONDITION == nodeType(pCond)) {
    SLogicConditionNode* pLogicCond = (SLogicConditionNode*)pCond;
    if (LOGIC_COND_TYPE_AND != pLogicCond->condType) {
      return false;
X
Xiaoyu Wang 已提交
674
    }
675 676 677
    bool   hasPrimaryKeyEqualCond = false;
    SNode* pCond = NULL;
    FOREACH(pCond, pLogicCond->pParameterList) {
678
      if (pushDownCondOptContainPriKeyEqualCond(pJoin, pCond)) {
679 680 681 682 683 684
        hasPrimaryKeyEqualCond = true;
        break;
      }
    }
    return hasPrimaryKeyEqualCond;
  } else {
685
    return pushDownCondOptIsPriKeyEqualCond(pJoin, pCond);
686 687 688
  }
}

689
static int32_t pushDownCondOptCheckJoinOnCond(SOptimizeContext* pCxt, SJoinLogicNode* pJoin) {
X
Xiaoyu Wang 已提交
690
  if (NULL == pJoin->pOnConditions) {
X
Xiaoyu Wang 已提交
691
    return generateUsageErrMsg(pCxt->pPlanCxt->pMsg, pCxt->pPlanCxt->msgLen, TSDB_CODE_PLAN_NOT_SUPPORT_CROSS_JOIN);
X
Xiaoyu Wang 已提交
692
  }
693
  if (!pushDownCondOptContainPriKeyEqualCond(pJoin, pJoin->pOnConditions)) {
694
    return generateUsageErrMsg(pCxt->pPlanCxt->pMsg, pCxt->pPlanCxt->msgLen, TSDB_CODE_PLAN_EXPECTED_TS_EQUAL);
X
Xiaoyu Wang 已提交
695
  }
696
  return TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
697 698
}

699 700 701
static int32_t pushDownCondOptPartJoinOnCondLogicCond(SJoinLogicNode* pJoin, SNode** ppMergeCond, SNode** ppOnCond) {
  SLogicConditionNode* pLogicCond = (SLogicConditionNode*)(pJoin->pOnConditions);

702
  int32_t    code = TSDB_CODE_SUCCESS;
703
  SNodeList* pOnConds = NULL;
704
  SNode*     pCond = NULL;
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
  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;
  }
}

747 748
static int32_t pushDownCondOptJoinExtractMergeCond(SOptimizeContext* pCxt, SJoinLogicNode* pJoin) {
  int32_t code = pushDownCondOptCheckJoinOnCond(pCxt, pJoin);
749 750
  SNode*  pJoinMergeCond = NULL;
  SNode*  pJoinOnCond = NULL;
751 752 753 754 755 756 757 758 759 760 761 762 763
  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;
}

764
static bool pushDownCondOptIsTableColumn(SNode* pNode, SNodeList* pTableCols) {
765 766 767 768 769 770 771
  if (QUERY_NODE_COLUMN != nodeType(pNode)) {
    return false;
  }
  SColumnNode* pCol = (SColumnNode*)pNode;
  return pushDownCondOptBelongThisTable(pNode, pTableCols);
}

S
slzhou 已提交
772
static bool pushDownCondOptIsColEqualOnCond(SJoinLogicNode* pJoin, SNode* pCond) {
773 774 775 776 777 778 779
  if (QUERY_NODE_OPERATOR != nodeType(pCond)) {
    return false;
  }
  SOperatorNode* pOper = (SOperatorNode*)pCond;
  if (OP_TYPE_EQUAL != pOper->opType) {
    return false;
  }
S
shenglian zhou 已提交
780 781 782 783 784
  if (QUERY_NODE_COLUMN != nodeType(pOper->pLeft) || QUERY_NODE_COLUMN != nodeType(pOper->pRight)) {
    return false;
  }
  SColumnNode* pLeft = (SColumnNode*)(pOper->pLeft);
  SColumnNode* pRight = (SColumnNode*)(pOper->pRight);
785 786 787
  // TODO: add cast to operator and remove this restriction of optimization
  if (pLeft->node.resType.type != pRight->node.resType.type ||
      pLeft->node.resType.bytes != pRight->node.resType.bytes) {
S
shenglian zhou 已提交
788 789
    return false;
  }
790 791
  SNodeList* pLeftCols = ((SLogicNode*)nodesListGetNode(pJoin->node.pChildren, 0))->pTargets;
  SNodeList* pRightCols = ((SLogicNode*)nodesListGetNode(pJoin->node.pChildren, 1))->pTargets;
792 793 794 795
  if (pushDownCondOptIsTableColumn(pOper->pLeft, pLeftCols)) {
    return pushDownCondOptIsTableColumn(pOper->pRight, pRightCols);
  } else if (pushDownCondOptIsTableColumn(pOper->pLeft, pRightCols)) {
    return pushDownCondOptIsTableColumn(pOper->pRight, pLeftCols);
796 797 798 799
  }
  return false;
}

S
slzhou 已提交
800
static int32_t pushDownCondOptJoinExtractColEqualOnLogicCond(SJoinLogicNode* pJoin) {
801 802 803
  SLogicConditionNode* pLogicCond = (SLogicConditionNode*)(pJoin->pOnConditions);

  int32_t    code = TSDB_CODE_SUCCESS;
S
slzhou 已提交
804
  SNodeList* pEqualOnConds = NULL;
805 806
  SNode*     pCond = NULL;
  FOREACH(pCond, pLogicCond->pParameterList) {
S
slzhou 已提交
807
    if (pushDownCondOptIsColEqualOnCond(pJoin, pCond)) {
S
slzhou 已提交
808
      code = nodesListMakeAppend(&pEqualOnConds, nodesCloneNode(pCond));
809 810 811 812 813
    }
  }

  SNode* pTempTagEqCond = NULL;
  if (TSDB_CODE_SUCCESS == code) {
S
slzhou 已提交
814
    code = nodesMergeConds(&pTempTagEqCond, &pEqualOnConds);
815 816 817
  }

  if (TSDB_CODE_SUCCESS == code) {
S
slzhou 已提交
818
    pJoin->pColEqualOnConditions = pTempTagEqCond;
819 820
    return TSDB_CODE_SUCCESS;
  } else {
S
slzhou 已提交
821
    nodesDestroyList(pEqualOnConds);
822 823 824 825 826
    return TSDB_CODE_PLAN_INTERNAL_ERROR;
  }
  return TSDB_CODE_SUCCESS;
}

S
slzhou 已提交
827
static int32_t pushDownCondOptJoinExtractColEqualOnCond(SOptimizeContext* pCxt, SJoinLogicNode* pJoin) {
828
  if (NULL == pJoin->pOnConditions) {
S
slzhou 已提交
829
    pJoin->pColEqualOnConditions = NULL;
830 831
    return TSDB_CODE_SUCCESS;
  }
832 833
  if (QUERY_NODE_LOGIC_CONDITION == nodeType(pJoin->pOnConditions) &&
      LOGIC_COND_TYPE_AND == ((SLogicConditionNode*)(pJoin->pOnConditions))->condType) {
S
slzhou 已提交
834
    return pushDownCondOptJoinExtractColEqualOnLogicCond(pJoin);
835 836
  }

S
slzhou 已提交
837
  if (pushDownCondOptIsColEqualOnCond(pJoin, pJoin->pOnConditions)) {
S
slzhou 已提交
838
    pJoin->pColEqualOnConditions = nodesCloneNode(pJoin->pOnConditions);
839 840 841 842 843
  }

  return TSDB_CODE_SUCCESS;
}

844 845
static int32_t pushDownCondOptDealJoin(SOptimizeContext* pCxt, SJoinLogicNode* pJoin) {
  if (OPTIMIZE_FLAG_TEST_MASK(pJoin->node.optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE)) {
846 847 848
    return TSDB_CODE_SUCCESS;
  }

X
Xiaoyu Wang 已提交
849
  if (NULL == pJoin->node.pConditions) {
850
    int32_t code = pushDownCondOptJoinExtractMergeCond(pCxt, pJoin);
S
slzhou 已提交
851 852 853 854
    if (TSDB_CODE_SUCCESS == code) {
      OPTIMIZE_FLAG_SET_MASK(pJoin->node.optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE);
      pCxt->optimized = true;
    }
855
    return code;
X
Xiaoyu Wang 已提交
856 857
  }

X
Xiaoyu Wang 已提交
858 859 860
  SNode*  pOnCond = NULL;
  SNode*  pLeftChildCond = NULL;
  SNode*  pRightChildCond = NULL;
861
  int32_t code = pushDownCondOptPartCond(pJoin, &pOnCond, &pLeftChildCond, &pRightChildCond);
862
  if (TSDB_CODE_SUCCESS == code && NULL != pOnCond) {
863
    code = pushDownCondOptPushCondToOnCond(pCxt, pJoin, &pOnCond);
864 865
  }
  if (TSDB_CODE_SUCCESS == code && NULL != pLeftChildCond) {
866 867
    code =
        pushDownCondOptPushCondToChild(pCxt, (SLogicNode*)nodesListGetNode(pJoin->node.pChildren, 0), &pLeftChildCond);
868 869
  }
  if (TSDB_CODE_SUCCESS == code && NULL != pRightChildCond) {
870 871
    code =
        pushDownCondOptPushCondToChild(pCxt, (SLogicNode*)nodesListGetNode(pJoin->node.pChildren, 1), &pRightChildCond);
872 873
  }

874
  if (TSDB_CODE_SUCCESS == code) {
875
    code = pushDownCondOptJoinExtractMergeCond(pCxt, pJoin);
876 877
  }

878
  if (TSDB_CODE_SUCCESS == code) {
S
slzhou 已提交
879
    code = pushDownCondOptJoinExtractColEqualOnCond(pCxt, pJoin);
880 881
  }

X
Xiaoyu Wang 已提交
882
  if (TSDB_CODE_SUCCESS == code) {
883
    OPTIMIZE_FLAG_SET_MASK(pJoin->node.optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE);
X
Xiaoyu Wang 已提交
884 885
    pCxt->optimized = true;
  } else {
886 887 888 889 890 891 892 893
    nodesDestroyNode(pOnCond);
    nodesDestroyNode(pLeftChildCond);
    nodesDestroyNode(pRightChildCond);
  }

  return code;
}

894 895
typedef struct SPartAggCondContext {
  SAggLogicNode* pAgg;
896
  bool           hasAggFunc;
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
} 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;
921
  int32_t              code = TSDB_CODE_SUCCESS;
922 923 924

  SNodeList* pAggFuncConds = NULL;
  SNodeList* pGroupKeyConds = NULL;
925
  SNode*     pCond = NULL;
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
  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 已提交
955
  nodesDestroyNode(pAgg->node.pConditions);
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
  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;
972 973 974
  return TSDB_CODE_SUCCESS;
}

975
static int32_t pushCondToAggCond(SOptimizeContext* pCxt, SAggLogicNode* pAgg, SNode** pAggFuncCond) {
X
Xiaoyu Wang 已提交
976
  return pushDownCondOptAppendCond(&pAgg->node.pConditions, pAggFuncCond);
977 978
}

979 980 981
typedef struct SRewriteAggGroupKeyCondContext {
  SAggLogicNode* pAgg;
  int32_t        errCode;
982 983 984 985
} SRewriteAggGroupKeyCondContext;

static EDealRes rewriteAggGroupKeyCondForPushDownImpl(SNode** pNode, void* pContext) {
  SRewriteAggGroupKeyCondContext* pCxt = pContext;
986
  SAggLogicNode*                  pAgg = pCxt->pAgg;
987 988 989 990 991 992 993 994
  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) {
995
            pCxt->errCode = TSDB_CODE_OUT_OF_MEMORY;
996 997 998 999
            return DEAL_RES_ERROR;
          }
          nodesDestroyNode(*pNode);
          *pNode = pExpr;
1000
          return DEAL_RES_IGNORE_CHILD;
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
        }
      }
    }
  }
  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;
  }
1019
  // TODO: remove it after full implementation of pushing down to child
1020
  if (1 != LIST_LENGTH(pAgg->node.pChildren)) {
1021 1022
    return TSDB_CODE_SUCCESS;
  }
1023 1024 1025

  SNode*  pAggFuncCond = NULL;
  SNode*  pGroupKeyCond = NULL;
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
  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;
}

1047 1048
typedef struct SRewriteProjCondContext {
  SProjectLogicNode* pProj;
1049 1050
  int32_t            errCode;
} SRewriteProjCondContext;
1051 1052 1053

static EDealRes rewriteProjectCondForPushDownImpl(SNode** ppNode, void* pContext) {
  SRewriteProjCondContext* pCxt = pContext;
1054
  SProjectLogicNode*       pProj = pCxt->pProj;
1055 1056 1057 1058 1059 1060 1061 1062 1063
  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) {
1064
              pCxt->errCode = TSDB_CODE_OUT_OF_MEMORY;
1065 1066 1067 1068
              return DEAL_RES_ERROR;
            }
            nodesDestroyNode(*ppNode);
            *ppNode = pExpr;
1069
            return DEAL_RES_IGNORE_CHILD;
1070 1071 1072 1073
          }  // end if expr alias name equal column name
        }    // end for each project
      }      // end if target node equals cond column node
    }        // end for each targets
1074 1075 1076 1077
  }
  return DEAL_RES_CONTINUE;
}

1078 1079
static int32_t rewriteProjectCondForPushDown(SOptimizeContext* pCxt, SProjectLogicNode* pProject,
                                             SNode** ppProjectCond) {
1080
  SRewriteProjCondContext cxt = {.pProj = pProject, .errCode = TSDB_CODE_SUCCESS};
1081
  SNode*                  pProjectCond = pProject->node.pConditions;
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
  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
1094
  if (1 != LIST_LENGTH(pProject->node.pChildren)) {
1095 1096 1097 1098 1099 1100 1101 1102
    return TSDB_CODE_SUCCESS;
  }

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

  int32_t code = TSDB_CODE_SUCCESS;
1103
  SNode*  pProjCond = NULL;
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
  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;
}

1119
static int32_t pushDownCondOptTrivialPushDown(SOptimizeContext* pCxt, SLogicNode* pLogicNode) {
1120 1121 1122 1123 1124
  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);
1125
  int32_t     code = pushDownCondOptPushCondToChild(pCxt, pChild, &pLogicNode->pConditions);
1126 1127 1128 1129 1130 1131 1132
  if (TSDB_CODE_SUCCESS == code) {
    OPTIMIZE_FLAG_SET_MASK(pLogicNode->optimizedFlag, OPTIMIZE_FLAG_PUSH_DOWN_CONDE);
    pCxt->optimized = true;
  }
  return code;
}

1133
static int32_t pushDownCondOptimizeImpl(SOptimizeContext* pCxt, SLogicNode* pLogicNode) {
1134 1135 1136
  int32_t code = TSDB_CODE_SUCCESS;
  switch (nodeType(pLogicNode)) {
    case QUERY_NODE_LOGIC_PLAN_SCAN:
1137
      code = pushDownCondOptDealScan(pCxt, (SScanLogicNode*)pLogicNode);
1138 1139
      break;
    case QUERY_NODE_LOGIC_PLAN_JOIN:
1140
      code = pushDownCondOptDealJoin(pCxt, (SJoinLogicNode*)pLogicNode);
1141 1142
      break;
    case QUERY_NODE_LOGIC_PLAN_AGG:
1143
      code = pushDownCondOptDealAgg(pCxt, (SAggLogicNode*)pLogicNode);
1144
      break;
1145 1146 1147
    case QUERY_NODE_LOGIC_PLAN_PROJECT:
      code = pushDownCondOptDealProject(pCxt, (SProjectLogicNode*)pLogicNode);
      break;
1148 1149
    case QUERY_NODE_LOGIC_PLAN_SORT:
    case QUERY_NODE_LOGIC_PLAN_PARTITION:
1150
      code = pushDownCondOptTrivialPushDown(pCxt, pLogicNode);
1151
      break;
1152 1153 1154 1155 1156 1157
    default:
      break;
  }
  if (TSDB_CODE_SUCCESS == code) {
    SNode* pChild = NULL;
    FOREACH(pChild, pLogicNode->pChildren) {
1158
      code = pushDownCondOptimizeImpl(pCxt, (SLogicNode*)pChild);
1159 1160 1161 1162 1163 1164 1165 1166
      if (TSDB_CODE_SUCCESS != code) {
        break;
      }
    }
  }
  return code;
}

1167 1168
static int32_t pushDownCondOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  return pushDownCondOptimizeImpl(pCxt, pLogicSubplan->pNode);
1169 1170
}

1171
static bool sortPriKeyOptIsPriKeyOrderBy(SNodeList* pSortKeys) {
X
Xiaoyu Wang 已提交
1172 1173 1174
  if (1 != LIST_LENGTH(pSortKeys)) {
    return false;
  }
X
Xiaoyu Wang 已提交
1175
  SNode* pNode = ((SOrderByExprNode*)nodesListGetNode(pSortKeys, 0))->pExpr;
X
Xiaoyu Wang 已提交
1176 1177 1178
  return (QUERY_NODE_COLUMN == nodeType(pNode) ? (PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)pNode)->colId) : false);
}

1179
static bool sortPriKeyOptMayBeOptimized(SLogicNode* pNode) {
X
Xiaoyu Wang 已提交
1180 1181 1182
  if (QUERY_NODE_LOGIC_PLAN_SORT != nodeType(pNode)) {
    return false;
  }
1183
  SSortLogicNode* pSort = (SSortLogicNode*)pNode;
1184
  if (!sortPriKeyOptIsPriKeyOrderBy(pSort->pSortKeys) || 1 != LIST_LENGTH(pSort->node.pChildren)) {
X
Xiaoyu Wang 已提交
1185
    return false;
X
Xiaoyu Wang 已提交
1186
  }
1187 1188 1189 1190 1191 1192 1193
  SNode* pChild;
  FOREACH(pChild, pSort->node.pChildren) {
    SLogicNode* pSortDescendent = optFindPossibleNode((SLogicNode*)pChild, sortPriKeyOptMayBeOptimized);
    if (pSortDescendent != NULL) {
      return false;
    }
  }
X
Xiaoyu Wang 已提交
1194 1195 1196
  return true;
}

1197
static int32_t sortPriKeyOptGetSequencingNodesImpl(SLogicNode* pNode, bool groupSort, bool* pNotOptimize,
X
Xiaoyu Wang 已提交
1198
                                                   SNodeList** pSequencingNodes) {
1199 1200 1201 1202
  if (NULL != pNode->pLimit || NULL != pNode->pSlimit) {
    *pNotOptimize = false;
    return TSDB_CODE_SUCCESS;
  }
1203

X
Xiaoyu Wang 已提交
1204
  switch (nodeType(pNode)) {
1205 1206
    case QUERY_NODE_LOGIC_PLAN_SCAN: {
      SScanLogicNode* pScan = (SScanLogicNode*)pNode;
1207
      if ((!groupSort && NULL != pScan->pGroupTags) || TSDB_SYSTEM_TABLE == pScan->tableType) {
1208 1209 1210
        *pNotOptimize = true;
        return TSDB_CODE_SUCCESS;
      }
X
Xiaoyu Wang 已提交
1211
      return nodesListMakeAppend(pSequencingNodes, (SNode*)pNode);
1212 1213
    }
    case QUERY_NODE_LOGIC_PLAN_JOIN: {
1214
      int32_t code = sortPriKeyOptGetSequencingNodesImpl((SLogicNode*)nodesListGetNode(pNode->pChildren, 0), groupSort,
X
Xiaoyu Wang 已提交
1215
                                                         pNotOptimize, pSequencingNodes);
X
Xiaoyu Wang 已提交
1216
      if (TSDB_CODE_SUCCESS == code) {
1217 1218
        code = sortPriKeyOptGetSequencingNodesImpl((SLogicNode*)nodesListGetNode(pNode->pChildren, 1), groupSort,
                                                   pNotOptimize, pSequencingNodes);
X
Xiaoyu Wang 已提交
1219 1220
      }
      return code;
1221
    }
X
Xiaoyu Wang 已提交
1222 1223
    case QUERY_NODE_LOGIC_PLAN_WINDOW:
      return nodesListMakeAppend(pSequencingNodes, (SNode*)pNode);
X
Xiaoyu Wang 已提交
1224
    case QUERY_NODE_LOGIC_PLAN_AGG:
1225
    case QUERY_NODE_LOGIC_PLAN_PARTITION:
X
Xiaoyu Wang 已提交
1226
      *pNotOptimize = true;
1227
      return TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
1228 1229 1230 1231 1232 1233
    default:
      break;
  }

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

1237 1238
  return sortPriKeyOptGetSequencingNodesImpl((SLogicNode*)nodesListGetNode(pNode->pChildren, 0), groupSort,
                                             pNotOptimize, pSequencingNodes);
X
Xiaoyu Wang 已提交
1239 1240
}

1241
static int32_t sortPriKeyOptGetSequencingNodes(SLogicNode* pNode, bool groupSort, SNodeList** pSequencingNodes) {
X
Xiaoyu Wang 已提交
1242
  bool    notOptimize = false;
1243
  int32_t code = sortPriKeyOptGetSequencingNodesImpl(pNode, groupSort, &notOptimize, pSequencingNodes);
X
Xiaoyu Wang 已提交
1244
  if (TSDB_CODE_SUCCESS != code || notOptimize) {
X
Xiaoyu Wang 已提交
1245
    NODES_CLEAR_LIST(*pSequencingNodes);
X
Xiaoyu Wang 已提交
1246 1247 1248 1249
  }
  return code;
}

1250
static EOrder sortPriKeyOptGetPriKeyOrder(SSortLogicNode* pSort) {
X
Xiaoyu Wang 已提交
1251 1252 1253
  return ((SOrderByExprNode*)nodesListGetNode(pSort->pSortKeys, 0))->order;
}

1254
static int32_t sortPriKeyOptApply(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan, SSortLogicNode* pSort,
X
Xiaoyu Wang 已提交
1255
                                  SNodeList* pSequencingNodes) {
1256
  EOrder order = sortPriKeyOptGetPriKeyOrder(pSort);
X
Xiaoyu Wang 已提交
1257 1258 1259 1260 1261 1262 1263
  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]);
      }
1264
      pScan->node.outputTsOrder = order;
X
Xiaoyu Wang 已提交
1265 1266 1267 1268 1269 1270 1271
      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)) {
1272
      ((SLogicNode*)pSequencingNode)->outputTsOrder = order;
1273
    }
1274
    optSetParentOrder(((SLogicNode*)pSequencingNode)->pParent, order, (SLogicNode*)pSort);
X
Xiaoyu Wang 已提交
1275
  }
X
Xiaoyu Wang 已提交
1276

X
Xiaoyu Wang 已提交
1277 1278 1279 1280 1281
  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);
1282 1283 1284
  if (TSDB_CODE_SUCCESS == code) {
    NODES_CLEAR_LIST(pSort->node.pChildren);
    nodesDestroyNode((SNode*)pSort);
X
Xiaoyu Wang 已提交
1285
  }
1286
  pCxt->optimized = true;
1287
  return code;
X
Xiaoyu Wang 已提交
1288 1289
}

1290
static int32_t sortPrimaryKeyOptimizeImpl(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan, SSortLogicNode* pSort) {
X
Xiaoyu Wang 已提交
1291
  SNodeList* pSequencingNodes = NULL;
1292 1293
  int32_t    code = sortPriKeyOptGetSequencingNodes((SLogicNode*)nodesListGetNode(pSort->node.pChildren, 0),
                                                    pSort->groupSort, &pSequencingNodes);
X
Xiaoyu Wang 已提交
1294 1295
  if (TSDB_CODE_SUCCESS == code && NULL != pSequencingNodes) {
    code = sortPriKeyOptApply(pCxt, pLogicSubplan, pSort, pSequencingNodes);
X
Xiaoyu Wang 已提交
1296
  }
X
Xiaoyu Wang 已提交
1297
  nodesClearList(pSequencingNodes);
X
Xiaoyu Wang 已提交
1298 1299 1300
  return code;
}

1301 1302
static int32_t sortPrimaryKeyOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  SSortLogicNode* pSort = (SSortLogicNode*)optFindPossibleNode(pLogicSubplan->pNode, sortPriKeyOptMayBeOptimized);
X
Xiaoyu Wang 已提交
1303 1304 1305
  if (NULL == pSort) {
    return TSDB_CODE_SUCCESS;
  }
1306
  return sortPrimaryKeyOptimizeImpl(pCxt, pLogicSubplan, pSort);
X
Xiaoyu Wang 已提交
1307 1308
}

1309
static bool smaIndexOptMayBeOptimized(SLogicNode* pNode) {
X
Xiaoyu Wang 已提交
1310 1311 1312
  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 已提交
1313 1314 1315 1316
    return false;
  }

  SScanLogicNode* pScan = (SScanLogicNode*)pNode;
X
Xiaoyu Wang 已提交
1317
  if (NULL == pScan->pSmaIndexes || NULL != pScan->node.pConditions) {
X
Xiaoyu Wang 已提交
1318 1319 1320
    return false;
  }

X
Xiaoyu Wang 已提交
1321
  return true;
X
Xiaoyu Wang 已提交
1322 1323
}

1324 1325
static int32_t smaIndexOptCreateSmaScan(SScanLogicNode* pScan, STableIndexInfo* pIndex, SNodeList* pCols,
                                        SLogicNode** pOutput) {
1326
  SScanLogicNode* pSmaScan = (SScanLogicNode*)nodesMakeNode(QUERY_NODE_LOGIC_PLAN_SCAN);
X
Xiaoyu Wang 已提交
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
  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 已提交
1341 1342
  pSmaScan->node.pTargets = nodesCloneList(pCols);
  if (NULL == pSmaScan->pVgroupList || NULL == pSmaScan->node.pTargets) {
1343
    nodesDestroyNode((SNode*)pSmaScan);
X
Xiaoyu Wang 已提交
1344 1345 1346 1347 1348 1349
    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 已提交
1350
  *pOutput = (SLogicNode*)pSmaScan;
X
Xiaoyu Wang 已提交
1351 1352 1353
  return TSDB_CODE_SUCCESS;
}

1354
static bool smaIndexOptEqualInterval(SScanLogicNode* pScan, SWindowLogicNode* pWindow, STableIndexInfo* pIndex) {
X
Xiaoyu Wang 已提交
1355 1356 1357 1358 1359
  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 已提交
1360 1361 1362 1363 1364 1365 1366 1367
  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};
1368 1369
    return (pScan->scanRange.skey == taosTimeTruncate(pScan->scanRange.skey, &interval)) &&
           (pScan->scanRange.ekey + 1 == taosTimeTruncate(pScan->scanRange.ekey + 1, &interval));
X
Xiaoyu Wang 已提交
1370
  }
X
Xiaoyu Wang 已提交
1371 1372 1373
  return true;
}

1374
static SNode* smaIndexOptCreateSmaCol(SNode* pFunc, uint64_t tableId, int32_t colId) {
1375
  SColumnNode* pCol = (SColumnNode*)nodesMakeNode(QUERY_NODE_COLUMN);
X
Xiaoyu Wang 已提交
1376 1377 1378 1379 1380 1381 1382
  if (NULL == pCol) {
    return NULL;
  }
  pCol->tableId = tableId;
  pCol->tableType = TSDB_SUPER_TABLE;
  pCol->colId = colId;
  pCol->colType = COLUMN_TYPE_COLUMN;
X
Xiaoyu Wang 已提交
1383
  strcpy(pCol->colName, ((SExprNode*)pFunc)->aliasName);
X
Xiaoyu Wang 已提交
1384 1385 1386 1387 1388
  pCol->node.resType = ((SExprNode*)pFunc)->resType;
  strcpy(pCol->node.aliasName, ((SExprNode*)pFunc)->aliasName);
  return (SNode*)pCol;
}

1389
static int32_t smaIndexOptFindSmaFunc(SNode* pQueryFunc, SNodeList* pSmaFuncs) {
X
Xiaoyu Wang 已提交
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
  int32_t index = 0;
  SNode*  pSmaFunc = NULL;
  FOREACH(pSmaFunc, pSmaFuncs) {
    if (nodesEqualNode(pQueryFunc, pSmaFunc)) {
      return index;
    }
    ++index;
  }
  return -1;
}

K
kailixu 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
static SNode* smaIndexOptFindWStartFunc(SNodeList* pSmaFuncs) {
  SNode* pSmaFunc = NULL;
  FOREACH(pSmaFunc, pSmaFuncs) {
    if (QUERY_NODE_FUNCTION == nodeType(pSmaFunc) && FUNCTION_TYPE_WSTART == ((SFunctionNode*)pSmaFunc)->funcType) {
      return pSmaFunc;
    }
  }
  return NULL;
}

1411 1412
static int32_t smaIndexOptCreateSmaCols(SNodeList* pFuncs, uint64_t tableId, SNodeList* pSmaFuncs,
                                        SNodeList** pOutput) {
X
Xiaoyu Wang 已提交
1413 1414 1415 1416
  SNodeList* pCols = NULL;
  SNode*     pFunc = NULL;
  int32_t    code = TSDB_CODE_SUCCESS;
  int32_t    index = 0;
X
Xiaoyu Wang 已提交
1417
  int32_t    smaFuncIndex = -1;
K
kailixu 已提交
1418
  bool       hasWStart = false;
X
Xiaoyu Wang 已提交
1419
  FOREACH(pFunc, pFuncs) {
1420
    smaFuncIndex = smaIndexOptFindSmaFunc(pFunc, pSmaFuncs);
X
Xiaoyu Wang 已提交
1421 1422 1423
    if (smaFuncIndex < 0) {
      break;
    } else {
1424
      code = nodesListMakeStrictAppend(&pCols, smaIndexOptCreateSmaCol(pFunc, tableId, smaFuncIndex + 1));
X
Xiaoyu Wang 已提交
1425 1426 1427
      if (TSDB_CODE_SUCCESS != code) {
        break;
      }
K
kailixu 已提交
1428
      if (!hasWStart) {
K
kailixu 已提交
1429 1430
        if (PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)pCols->pTail->pNode)->colId) {
          hasWStart = true;
K
kailixu 已提交
1431 1432
        }
      }
X
Xiaoyu Wang 已提交
1433 1434 1435 1436
    }
    ++index;
  }

X
Xiaoyu Wang 已提交
1437
  if (TSDB_CODE_SUCCESS == code && smaFuncIndex >= 0) {
K
kailixu 已提交
1438
    if (!hasWStart) {
K
kailixu 已提交
1439 1440 1441
      SNode* pWsNode = smaIndexOptFindWStartFunc(pSmaFuncs);
      if (!pWsNode) {
        nodesDestroyList(pCols);
K
kailixu 已提交
1442 1443 1444
        code = TSDB_CODE_APP_ERROR;
        qError("create sma cols failed since %s(_wstart not exist)", tstrerror(code));
        return code;
K
kailixu 已提交
1445
      }
K
kailixu 已提交
1446
      SExprNode exprNode;
K
kailixu 已提交
1447
      exprNode.resType = ((SExprNode*)pWsNode)->resType;
K
kailixu 已提交
1448
      sprintf(exprNode.aliasName, "#expr_%d", index + 1);
1449 1450
      SNode* pkNode = smaIndexOptCreateSmaCol((SNode*)&exprNode, tableId, PRIMARYKEY_TIMESTAMP_COL_ID);
      code = nodesListPushFront(pCols, pkNode);
K
kailixu 已提交
1451
      if (TSDB_CODE_SUCCESS != code) {
1452
        nodesDestroyNode(pkNode);
K
kailixu 已提交
1453 1454 1455 1456
        nodesDestroyList(pCols);
        return code;
      }
    }
X
Xiaoyu Wang 已提交
1457 1458 1459 1460 1461 1462 1463 1464
    *pOutput = pCols;
  } else {
    nodesDestroyList(pCols);
  }

  return code;
}

1465
static int32_t smaIndexOptCouldApplyIndex(SScanLogicNode* pScan, STableIndexInfo* pIndex, SNodeList** pCols) {
X
Xiaoyu Wang 已提交
1466
  SWindowLogicNode* pWindow = (SWindowLogicNode*)pScan->node.pParent;
1467
  if (!smaIndexOptEqualInterval(pScan, pWindow, pIndex)) {
X
Xiaoyu Wang 已提交
1468 1469 1470 1471 1472
    return TSDB_CODE_SUCCESS;
  }
  SNodeList* pSmaFuncs = NULL;
  int32_t    code = nodesStringToList(pIndex->expr, &pSmaFuncs);
  if (TSDB_CODE_SUCCESS == code) {
1473
    code = smaIndexOptCreateSmaCols(pWindow->pFuncs, pIndex->dstTbUid, pSmaFuncs, pCols);
X
Xiaoyu Wang 已提交
1474 1475 1476 1477 1478
  }
  nodesDestroyList(pSmaFuncs);
  return code;
}

1479
static int32_t smaIndexOptApplyIndex(SLogicSubplan* pLogicSubplan, SScanLogicNode* pScan, STableIndexInfo* pIndex,
1480
                                     SNodeList* pSmaCols) {
X
Xiaoyu Wang 已提交
1481
  SLogicNode* pSmaScan = NULL;
1482
  int32_t     code = smaIndexOptCreateSmaScan(pScan, pIndex, pSmaCols, &pSmaScan);
X
Xiaoyu Wang 已提交
1483 1484 1485
  if (TSDB_CODE_SUCCESS == code) {
    code = replaceLogicNode(pLogicSubplan, pScan->node.pParent, pSmaScan);
  }
X
Xiaoyu Wang 已提交
1486 1487 1488
  if (TSDB_CODE_SUCCESS == code) {
    nodesDestroyNode((SNode*)pScan->node.pParent);
  }
X
Xiaoyu Wang 已提交
1489 1490 1491
  return code;
}

1492
static int32_t smaIndexOptimizeImpl(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan, SScanLogicNode* pScan) {
X
Xiaoyu Wang 已提交
1493
  int32_t code = TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
1494 1495 1496 1497
  int32_t nindexes = taosArrayGetSize(pScan->pSmaIndexes);
  for (int32_t i = 0; i < nindexes; ++i) {
    STableIndexInfo* pIndex = taosArrayGet(pScan->pSmaIndexes, i);
    SNodeList*       pSmaCols = NULL;
1498
    code = smaIndexOptCouldApplyIndex(pScan, pIndex, &pSmaCols);
X
Xiaoyu Wang 已提交
1499
    if (TSDB_CODE_SUCCESS == code && NULL != pSmaCols) {
1500
      code = smaIndexOptApplyIndex(pLogicSubplan, pScan, pIndex, pSmaCols);
1501
      pCxt->optimized = true;
X
Xiaoyu Wang 已提交
1502
      break;
X
Xiaoyu Wang 已提交
1503 1504
    }
  }
X
Xiaoyu Wang 已提交
1505
  return code;
X
Xiaoyu Wang 已提交
1506
}
X
Xiaoyu Wang 已提交
1507

1508 1509
static int32_t smaIndexOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  SScanLogicNode* pScan = (SScanLogicNode*)optFindPossibleNode(pLogicSubplan->pNode, smaIndexOptMayBeOptimized);
X
Xiaoyu Wang 已提交
1510 1511 1512
  if (NULL == pScan) {
    return TSDB_CODE_SUCCESS;
  }
1513
  return smaIndexOptimizeImpl(pCxt, pLogicSubplan, pScan);
X
Xiaoyu Wang 已提交
1514 1515
}

X
Xiaoyu Wang 已提交
1516 1517
static EDealRes partTagsOptHasColImpl(SNode* pNode, void* pContext) {
  if (QUERY_NODE_COLUMN == nodeType(pNode)) {
X
Xiaoyu Wang 已提交
1518
    if (COLUMN_TYPE_TAG != ((SColumnNode*)pNode)->colType && COLUMN_TYPE_TBNAME != ((SColumnNode*)pNode)->colType) {
X
Xiaoyu Wang 已提交
1519 1520 1521 1522 1523 1524 1525
      *(bool*)pContext = true;
      return DEAL_RES_END;
    }
  }
  return DEAL_RES_CONTINUE;
}

S
slzhou@taodata.com 已提交
1526
static bool planOptNodeListHasCol(SNodeList* pKeys) {
X
Xiaoyu Wang 已提交
1527
  bool hasCol = false;
S
slzhou@taodata.com 已提交
1528
  nodesWalkExprs(pKeys, partTagsOptHasColImpl, &hasCol);
X
Xiaoyu Wang 已提交
1529 1530 1531
  return hasCol;
}

1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
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 已提交
1548
static bool partTagsIsOptimizableNode(SLogicNode* pNode) {
X
Xiaoyu Wang 已提交
1549
  return ((QUERY_NODE_LOGIC_PLAN_PARTITION == nodeType(pNode) ||
X
Xiaoyu Wang 已提交
1550
           (QUERY_NODE_LOGIC_PLAN_AGG == nodeType(pNode) && NULL != ((SAggLogicNode*)pNode)->pGroupKeys &&
X
Xiaoyu Wang 已提交
1551
            NULL != ((SAggLogicNode*)pNode)->pAggFuncs)) &&
X
Xiaoyu Wang 已提交
1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
          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;
  }
}

1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
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 已提交
1582
static bool partTagsOptMayBeOptimized(SLogicNode* pNode) {
X
Xiaoyu Wang 已提交
1583
  if (!partTagsIsOptimizableNode(pNode)) {
X
Xiaoyu Wang 已提交
1584 1585 1586
    return false;
  }

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

X
Xiaoyu Wang 已提交
1590 1591
static int32_t partTagsOptRebuildTbanme(SNodeList* pPartKeys) {
  int32_t code = TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
1592
  nodesRewriteExprs(pPartKeys, optRebuildTbanme, &code);
X
Xiaoyu Wang 已提交
1593 1594 1595
  return code;
}

1596 1597 1598 1599 1600
// 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);
}

1601
static SNode* partTagsCreateWrapperFunc(const char* pFuncName, SNode* pNode) {
1602 1603 1604 1605 1606
  SFunctionNode* pFunc = (SFunctionNode*)nodesMakeNode(QUERY_NODE_FUNCTION);
  if (NULL == pFunc) {
    return NULL;
  }

X
Xiaoyu Wang 已提交
1607
  snprintf(pFunc->functionName, sizeof(pFunc->functionName), "%s", pFuncName);
X
Xiaoyu Wang 已提交
1608
  if (QUERY_NODE_COLUMN == nodeType(pNode) && COLUMN_TYPE_TBNAME != ((SColumnNode*)pNode)->colType) {
1609
    SColumnNode* pCol = (SColumnNode*)pNode;
1610
    partTagsSetAlias(pFunc->node.aliasName, sizeof(pFunc->node.aliasName), pCol->tableAlias, pCol->colName);
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626
  } 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;
}

1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
static bool partTagsHasIndefRowsSelectFunc(SNodeList* pFuncs) {
  SNode* pFunc = NULL;
  FOREACH(pFunc, pFuncs) {
    if (fmIsIndefiniteRowsFunc(((SFunctionNode*)pFunc)->funcId)) {
      return true;
    }
  }
  return false;
}

X
Xiaoyu Wang 已提交
1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
static bool partTagsNeedOutput(SNode* pExpr, SNodeList* pTargets) {
  SNode* pOutput = NULL;
  FOREACH(pOutput, pTargets) {
    if (QUERY_NODE_COLUMN == nodeType(pExpr)) {
      if (nodesEqualNode(pExpr, pOutput)) {
        return true;
      }
    } else if (0 == strcmp(((SExprNode*)pExpr)->aliasName, ((SColumnNode*)pOutput)->colName)) {
      return true;
    }
  }
  return false;
}

static int32_t partTagsRewriteGroupTagsToFuncs(SNodeList* pGroupTags, int32_t start, SAggLogicNode* pAgg) {
  bool    hasIndefRowsSelectFunc = partTagsHasIndefRowsSelectFunc(pAgg->pAggFuncs);
1653
  int32_t code = TSDB_CODE_SUCCESS;
1654
  int32_t index = 0;
1655
  SNode*  pNode = NULL;
1656
  FOREACH(pNode, pGroupTags) {
X
Xiaoyu Wang 已提交
1657
    if (index++ < start || !partTagsNeedOutput(pNode, pAgg->node.pTargets)) {
1658 1659
      continue;
    }
1660
    if (hasIndefRowsSelectFunc) {
X
Xiaoyu Wang 已提交
1661
      code = nodesListStrictAppend(pAgg->pAggFuncs, partTagsCreateWrapperFunc("_select_value", pNode));
1662
    } else {
X
Xiaoyu Wang 已提交
1663
      code = nodesListStrictAppend(pAgg->pAggFuncs, partTagsCreateWrapperFunc("_group_key", pNode));
1664
    }
1665
    if (TSDB_CODE_SUCCESS != code) {
1666
      break;
1667 1668
    }
  }
1669
  return code;
1670 1671
}

X
Xiaoyu Wang 已提交
1672
static int32_t partTagsOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
X
Xiaoyu Wang 已提交
1673 1674
  SLogicNode* pNode = optFindPossibleNode(pLogicSubplan->pNode, partTagsOptMayBeOptimized);
  if (NULL == pNode) {
X
Xiaoyu Wang 已提交
1675 1676 1677
    return TSDB_CODE_SUCCESS;
  }

X
Xiaoyu Wang 已提交
1678 1679 1680
  int32_t         code = TSDB_CODE_SUCCESS;
  SScanLogicNode* pScan = (SScanLogicNode*)nodesListGetNode(pNode->pChildren, 0);
  if (QUERY_NODE_LOGIC_PLAN_PARTITION == nodeType(pNode)) {
1681
    TSWAP(((SPartitionLogicNode*)pNode)->pPartitionKeys, pScan->pGroupTags);
1682 1683
    TSWAP(((SPartitionLogicNode*)pNode)->pTags, pScan->pTags);
    TSWAP(((SPartitionLogicNode*)pNode)->pSubtable, pScan->pSubtable);
X
Xiaoyu Wang 已提交
1684
    int32_t code = replaceLogicNode(pLogicSubplan, pNode, (SLogicNode*)pScan);
X
Xiaoyu Wang 已提交
1685 1686 1687
    if (TSDB_CODE_SUCCESS == code) {
      code = adjustLogicNodeDataRequirement((SLogicNode*)pScan, pNode->resultDataOrder);
    }
X
Xiaoyu Wang 已提交
1688
    if (TSDB_CODE_SUCCESS == code) {
1689 1690
      if (QUERY_NODE_LOGIC_PLAN_AGG == pNode->pParent->type) {
        SAggLogicNode* pParent = (SAggLogicNode*)(pNode->pParent);
1691
        scanPathOptSetGroupOrderScan(pScan);
1692 1693
        pParent->hasGroupKeyOptimized = true;
      }
G
fix bug  
Ganlin Zhao 已提交
1694

X
Xiaoyu Wang 已提交
1695 1696 1697 1698
      NODES_CLEAR_LIST(pNode->pChildren);
      nodesDestroyNode((SNode*)pNode);
    }
  } else {
1699
    SAggLogicNode* pAgg = (SAggLogicNode*)pNode;
1700
    int32_t        start = -1;
1701 1702
    SNode*         pGroupKey = NULL;
    FOREACH(pGroupKey, pAgg->pGroupKeys) {
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
      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 已提交
1716 1717 1718 1719
      if (TSDB_CODE_SUCCESS != code) {
        break;
      }
    }
1720
    pAgg->hasGroupKeyOptimized = true;
G
fix bug  
Ganlin Zhao 已提交
1721

1722
    NODES_DESTORY_LIST(pAgg->pGroupKeys);
1723
    if (TSDB_CODE_SUCCESS == code && start >= 0) {
X
Xiaoyu Wang 已提交
1724
      code = partTagsRewriteGroupTagsToFuncs(pScan->pGroupTags, start, pAgg);
1725
    }
X
Xiaoyu Wang 已提交
1726 1727
  }
  if (TSDB_CODE_SUCCESS == code) {
1728
    code = partTagsOptRebuildTbanme(pScan->pGroupTags);
X
Xiaoyu Wang 已提交
1729
  }
1730

1731
  pCxt->optimized = true;
X
Xiaoyu Wang 已提交
1732 1733 1734
  return code;
}

S
slzhou 已提交
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
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;
}

1753
static bool eliminateProjOptMayBeOptimized(SLogicNode* pNode) {
X
Xiaoyu Wang 已提交
1754
  // TODO: enable this optimization after new mechanising that map projection and targets of project node
1755 1756 1757
  if (NULL != pNode->pParent) {
    return false;
  }
X
Xiaoyu Wang 已提交
1758

1759 1760 1761 1762
  // 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)) {
1763 1764 1765 1766
    return false;
  }

  SProjectLogicNode* pProjectNode = (SProjectLogicNode*)pNode;
1767 1768
  if (NULL != pProjectNode->node.pLimit || NULL != pProjectNode->node.pSlimit ||
      NULL != pProjectNode->node.pConditions) {
1769 1770 1771
    return false;
  }

X
Xiaoyu Wang 已提交
1772
  SNode* pProjection;
1773 1774 1775 1776 1777 1778
  FOREACH(pProjection, pProjectNode->pProjections) {
    SExprNode* pExprNode = (SExprNode*)pProjection;
    if (QUERY_NODE_COLUMN != nodeType(pExprNode)) {
      return false;
    }
  }
1779

S
slzhou 已提交
1780
  return eliminateProjOptCheckProjColumnNames(pProjectNode);
1781 1782
}

1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
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) {
1793 1794 1795
      if (nodesEqualNode(pTarget, pNode)) {
        pCxt->canUse = true;
        return DEAL_RES_CONTINUE;
1796 1797
      }
    }
1798 1799
    pCxt->canUse = false;
    return DEAL_RES_END;
1800 1801 1802 1803
  }
  return DEAL_RES_CONTINUE;
}

1804 1805 1806 1807 1808
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;
1809
  }
1810
  if (QUERY_NODE_LOGIC_PLAN_JOIN == nodeType(pChild) && NULL != ((SJoinLogicNode*)pChild)->pOnConditions) {
1811
    SJoinLogicNode*         pJoinLogicNode = (SJoinLogicNode*)pChild;
1812 1813 1814 1815 1816
    CheckNewChildTargetsCxt cxt = {.pNewChildTargets = pNewChildTargets, .canUse = false};
    nodesWalkExpr(pJoinLogicNode->pOnConditions, eliminateProjOptCanUseNewChildTargetsImpl, &cxt);
    if (!cxt.canUse) return false;
  }
  return true;
1817 1818
}

D
dapan1121 已提交
1819 1820 1821 1822 1823 1824
static void alignProjectionWithTarget(SLogicNode* pNode) {
  if (QUERY_NODE_LOGIC_PLAN_PROJECT != pNode->type) {
    return;
  }

  SProjectLogicNode* pProjectNode = (SProjectLogicNode*)pNode;
1825
  SNode*             pProjection = NULL;
D
dapan1121 已提交
1826 1827
  FOREACH(pProjection, pProjectNode->pProjections) {
    SNode* pTarget = NULL;
1828
    bool   keep = false;
D
dapan1121 已提交
1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840
    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 已提交
1841 1842
static int32_t eliminateProjOptimizeImpl(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan,
                                         SProjectLogicNode* pProjectNode) {
1843
  SLogicNode* pChild = (SLogicNode*)nodesListGetNode(pProjectNode->node.pChildren, 0);
X
Xiaoyu Wang 已提交
1844
  SNodeList*  pNewChildTargets = nodesMakeList();
1845 1846 1847 1848 1849

  SNode* pProjection = NULL;
  FOREACH(pProjection, pProjectNode->pProjections) {
    SNode* pChildTarget = NULL;
    FOREACH(pChildTarget, pChild->pTargets) {
1850
      if (0 == strcmp(((SColumnNode*)pProjection)->colName, ((SColumnNode*)pChildTarget)->colName)) {
1851
        nodesListAppend(pNewChildTargets, nodesCloneNode(pChildTarget));
1852
        break;
1853 1854 1855
      }
    }
  }
1856
  if (eliminateProjOptCanChildConditionUseChildTargets(pChild, pNewChildTargets)) {
1857 1858 1859 1860 1861 1862
    nodesDestroyList(pChild->pTargets);
    pChild->pTargets = pNewChildTargets;
  } else {
    nodesDestroyList(pNewChildTargets);
    return TSDB_CODE_SUCCESS;
  }
X
Xiaoyu Wang 已提交
1863

1864 1865 1866 1867
  int32_t code = replaceLogicNode(pLogicSubplan, (SLogicNode*)pProjectNode, pChild);
  if (TSDB_CODE_SUCCESS == code) {
    NODES_CLEAR_LIST(pProjectNode->node.pChildren);
    nodesDestroyNode((SNode*)pProjectNode);
1868
    // if pChild is a project logic node, remove its projection which is not reference by its target.
D
dapan1121 已提交
1869
    alignProjectionWithTarget(pChild);
1870
  }
1871
  pCxt->optimized = true;
1872 1873 1874 1875 1876
  return code;
}

static int32_t eliminateProjOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  SProjectLogicNode* pProjectNode =
X
Xiaoyu Wang 已提交
1877
      (SProjectLogicNode*)optFindPossibleNode(pLogicSubplan->pNode, eliminateProjOptMayBeOptimized);
1878 1879 1880 1881 1882 1883 1884 1885

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

  return eliminateProjOptimizeImpl(pCxt, pLogicSubplan, pProjectNode);
}

1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
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 已提交
1910
  pLimitNode->offset = NULL == pOffset ? 0 : ((SValueNode*)pOffset)->datum.i;
1911 1912 1913 1914 1915
  *pOutput = (SNode*)pLimitNode;
  return TSDB_CODE_SUCCESS;
}

static bool rewriteTailOptNeedGroupSort(SIndefRowsFuncLogicNode* pIndef) {
1916 1917 1918 1919 1920
  if (1 != LIST_LENGTH(pIndef->node.pChildren)) {
    return false;
  }
  SNode* pChild = nodesListGetNode(pIndef->node.pChildren, 0);
  return QUERY_NODE_LOGIC_PLAN_PARTITION == nodeType(pChild) ||
1921
         (QUERY_NODE_LOGIC_PLAN_SCAN == nodeType(pChild) && NULL != ((SScanLogicNode*)pChild)->pGroupTags);
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931
}

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);
1932
  optResetParent((SLogicNode*)pSort);
1933 1934
  pSort->node.precision = pIndef->node.precision;

1935 1936 1937 1938 1939 1940 1941 1942 1943
  SFunctionNode* pTail = NULL;
  SNode*         pFunc = NULL;
  FOREACH(pFunc, pIndef->pFuncs) {
    if (FUNCTION_TYPE_TAIL == ((SFunctionNode*)pFunc)->funcType) {
      pTail = (SFunctionNode*)pFunc;
      break;
    }
  }

1944
  // tail(expr, [limit, offset,] _rowts)
1945
  int32_t rowtsIndex = LIST_LENGTH(pTail->pParameterList) - 1;
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964

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

1965 1966
static SNode* rewriteTailOptCreateProjectExpr(SFunctionNode* pFunc) {
  SNode* pExpr = nodesCloneNode(nodesListGetNode(pFunc->pParameterList, 0));
1967 1968 1969
  if (NULL == pExpr) {
    return NULL;
  }
1970
  strcpy(((SExprNode*)pExpr)->aliasName, pFunc->node.aliasName);
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982
  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;

1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
  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 已提交
1995

1996 1997 1998
  // 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 已提交
1999 2000 2001 2002 2003
  if (TSDB_CODE_SUCCESS == code) {
    code = rewriteTailOptCreateLimit(limitIndex < 0 ? NULL : nodesListGetNode(pTail->pParameterList, limitIndex),
                                     offsetIndex < 0 ? NULL : nodesListGetNode(pTail->pParameterList, offsetIndex),
                                     &pProject->node.pLimit);
  }
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
  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);
  }
2034
  pCxt->optimized = true;
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
  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 已提交
2049 2050 2051
static bool eliminateSetOpMayBeOptimized(SLogicNode* pNode) {
  SLogicNode* pParent = pNode->pParent;
  if (NULL == pParent ||
X
Xiaoyu Wang 已提交
2052
      QUERY_NODE_LOGIC_PLAN_AGG != nodeType(pParent) && QUERY_NODE_LOGIC_PLAN_PROJECT != nodeType(pParent) ||
S
slzhou 已提交
2053 2054 2055
      LIST_LENGTH(pParent->pChildren) < 2) {
    return false;
  }
X
Xiaoyu Wang 已提交
2056
  if (nodeType(pNode) != nodeType(pNode->pParent) || LIST_LENGTH(pNode->pChildren) < 2) {
S
slzhou 已提交
2057 2058 2059 2060 2061
    return false;
  }
  return true;
}

X
Xiaoyu Wang 已提交
2062 2063
static int32_t eliminateSetOpOptimizeImpl(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan,
                                          SLogicNode* pSetOpNode) {
S
slzhou 已提交
2064 2065 2066 2067
  SNode* pSibling;
  FOREACH(pSibling, pSetOpNode->pParent->pChildren) {
    if (nodesEqualNode(pSibling, (SNode*)pSetOpNode)) {
      SNode* pChild;
X
Xiaoyu Wang 已提交
2068
      FOREACH(pChild, pSetOpNode->pChildren) { ((SLogicNode*)pChild)->pParent = pSetOpNode->pParent; }
S
slzhou 已提交
2069 2070
      INSERT_LIST(pSetOpNode->pParent->pChildren, pSetOpNode->pChildren);

S
slzhou 已提交
2071 2072
      pSetOpNode->pChildren = NULL;
      ERASE_NODE(pSetOpNode->pParent->pChildren);
2073
      pCxt->optimized = true;
S
slzhou 已提交
2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089
      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);
}

2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115
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) {
2116
    strcpy(pFunc->node.aliasName, pSelectValue->node.aliasName);
2117
  } else {
X
Xiaoyu Wang 已提交
2118 2119
    int64_t pointer = (int64_t)pFunc;
    snprintf(pFunc->node.aliasName, sizeof(pFunc->node.aliasName), "%s.%" PRId64 "", pFunc->functionName, pointer);
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140
  }
  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);
2141
  optResetParent((SLogicNode*)pAgg);
2142
  pAgg->node.precision = pIndef->node.precision;
2143 2144
  pAgg->node.requireDataOrder = DATA_ORDER_LEVEL_IN_BLOCK;  // first function requirement
  pAgg->node.resultDataOrder = DATA_ORDER_LEVEL_NONE;
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 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 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216

  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;
2217 2218
  pProject->node.requireDataOrder = DATA_ORDER_LEVEL_NONE;
  pProject->node.resultDataOrder = DATA_ORDER_LEVEL_NONE;
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253

  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) {
2254 2255
    code = adjustLogicNodeDataRequirement(
        pProject, NULL == pProject->pParent ? DATA_ORDER_LEVEL_NONE : pProject->pParent->requireDataOrder);
2256
    pProject = NULL;
2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278
  }
  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 已提交
2279 2280 2281 2282 2283
typedef struct SLastRowScanOptLastParaCkCxt {
  bool hasTag;
  bool hasCol;
} SLastRowScanOptLastParaCkCxt;

2284
static EDealRes lastRowScanOptLastParaIsTagImpl(SNode* pNode, void* pContext) {
X
Xiaoyu Wang 已提交
2285
  if (QUERY_NODE_COLUMN == nodeType(pNode)) {
X
Xiaoyu Wang 已提交
2286
    SLastRowScanOptLastParaCkCxt* pCxt = pContext;
X
Xiaoyu Wang 已提交
2287
    if (COLUMN_TYPE_TAG == ((SColumnNode*)pNode)->colType || COLUMN_TYPE_TBNAME == ((SColumnNode*)pNode)->colType) {
X
Xiaoyu Wang 已提交
2288 2289 2290
      pCxt->hasTag = true;
    } else {
      pCxt->hasCol = true;
X
Xiaoyu Wang 已提交
2291
    }
X
Xiaoyu Wang 已提交
2292
    return DEAL_RES_END;
X
Xiaoyu Wang 已提交
2293 2294 2295 2296
  }
  return DEAL_RES_CONTINUE;
}

2297
static bool lastRowScanOptLastParaIsTag(SNode* pExpr) {
X
Xiaoyu Wang 已提交
2298
  SLastRowScanOptLastParaCkCxt cxt = {.hasTag = false, .hasCol = false};
2299 2300
  nodesWalkExpr(pExpr, lastRowScanOptLastParaIsTagImpl, &cxt);
  return cxt.hasTag && !cxt.hasCol;
X
Xiaoyu Wang 已提交
2301 2302
}

X
Xiaoyu Wang 已提交
2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
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;
}

2319
static bool lastRowScanOptMayBeOptimized(SLogicNode* pNode) {
X
Xiaoyu Wang 已提交
2320 2321 2322 2323 2324 2325 2326
  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 已提交
2327 2328
  // Only one of LAST and LASTROW can appear
  if (pAgg->hasLastRow == pAgg->hasLast || NULL != pAgg->pGroupKeys || NULL != pScan->node.pConditions ||
X
Xiaoyu Wang 已提交
2329 2330
      !hasSuitableCache(pScan->cacheLastMode, pAgg->hasLastRow, pAgg->hasLast) ||
      IS_TSWINDOW_SPECIFIED(pScan->scanRange)) {
2331 2332 2333
    return false;
  }

X
Xiaoyu Wang 已提交
2334 2335
  bool   hasLastFunc = false;
  bool   hasSelectFunc = false;
2336 2337
  SNode* pFunc = NULL;
  FOREACH(pFunc, ((SAggLogicNode*)pNode)->pAggFuncs) {
X
Xiaoyu Wang 已提交
2338 2339
    SFunctionNode* pAggFunc = (SFunctionNode*)pFunc;
    if (FUNCTION_TYPE_LAST == pAggFunc->funcType) {
D
dapan1121 已提交
2340 2341 2342
      SNode* pPar = nodesListGetNode(pAggFunc->pParameterList, 0);
      if (QUERY_NODE_COLUMN == nodeType(pPar)) {
        SColumnNode* pCol = (SColumnNode*)pPar;
2343
        if (pCol->colType != COLUMN_TYPE_COLUMN) {
H
Haojun Liao 已提交
2344
          return false;
D
dapan1121 已提交
2345 2346
        }
      }
2347
      if (hasSelectFunc || QUERY_NODE_VALUE == nodeType(nodesListGetNode(pAggFunc->pParameterList, 0))) {
X
Xiaoyu Wang 已提交
2348 2349 2350
        return false;
      }
      hasLastFunc = true;
2351
    } else if (FUNCTION_TYPE_SELECT_VALUE == pAggFunc->funcType) {
X
Xiaoyu Wang 已提交
2352 2353 2354 2355
      if (hasLastFunc) {
        return false;
      }
      hasSelectFunc = true;
2356 2357 2358 2359
    } else if (FUNCTION_TYPE_GROUP_KEY == pAggFunc->funcType) {
      if (!lastRowScanOptLastParaIsTag(nodesListGetNode(pAggFunc->pParameterList, 0))) {
        return false;
      }
X
Xiaoyu Wang 已提交
2360
    } else if (FUNCTION_TYPE_LAST_ROW != pAggFunc->funcType) {
2361 2362 2363 2364 2365 2366 2367
      return false;
    }
  }

  return true;
}

X
Xiaoyu Wang 已提交
2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
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;
}

2393
static void lastRowScanOptSetLastTargets(SNodeList* pTargets, SNodeList* pLastCols, bool erase) {
X
Xiaoyu Wang 已提交
2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404
  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;
      }
    }
2405
    if (!found && erase) {
X
Xiaoyu Wang 已提交
2406 2407 2408 2409 2410 2411 2412
      ERASE_NODE(pTargets);
      continue;
    }
    WHERE_NEXT;
  }
}

2413 2414 2415 2416 2417 2418 2419
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 已提交
2420 2421
  SLastRowScanOptSetColDataTypeCxt cxt = {.doAgg = true, .pLastCols = NULL};
  SNode*                           pNode = NULL;
2422 2423
  FOREACH(pNode, pAgg->pAggFuncs) {
    SFunctionNode* pFunc = (SFunctionNode*)pNode;
X
Xiaoyu Wang 已提交
2424 2425 2426 2427
    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");
2428 2429 2430
      pFunc->functionName[len] = '\0';
      int32_t code = fmGetFuncInfo(pFunc, NULL, 0);
      if (TSDB_CODE_SUCCESS != code) {
X
Xiaoyu Wang 已提交
2431
        nodesClearList(cxt.pLastCols);
2432 2433
        return code;
      }
X
Xiaoyu Wang 已提交
2434 2435
      if (FUNCTION_TYPE_LAST == funcType) {
        nodesWalkExpr(nodesListGetNode(pFunc->pParameterList, 0), lastRowScanOptSetColDataType, &cxt);
X
Xiaoyu Wang 已提交
2436
        nodesListErase(pFunc->pParameterList, nodesListGetCell(pFunc->pParameterList, 1));
X
Xiaoyu Wang 已提交
2437
      }
2438
    }
2439 2440
  }

X
Xiaoyu Wang 已提交
2441 2442 2443
  SScanLogicNode* pScan = (SScanLogicNode*)nodesListGetNode(pAgg->node.pChildren, 0);
  pScan->scanType = SCAN_TYPE_LAST_ROW;
  pScan->igLastNull = pAgg->hasLast ? true : false;
X
Xiaoyu Wang 已提交
2444 2445
  if (NULL != cxt.pLastCols) {
    cxt.doAgg = false;
2446
    lastRowScanOptSetLastTargets(pScan->pScanCols, cxt.pLastCols, true);
2447
    nodesWalkExprs(pScan->pScanPseudoCols, lastRowScanOptSetColDataType, &cxt);
2448
    lastRowScanOptSetLastTargets(pScan->node.pTargets, cxt.pLastCols, false);
X
Xiaoyu Wang 已提交
2449 2450
    nodesClearList(cxt.pLastCols);
  }
X
Xiaoyu Wang 已提交
2451 2452
  pAgg->hasLastRow = false;
  pAgg->hasLast = false;
2453 2454 2455 2456 2457

  pCxt->optimized = true;
  return TSDB_CODE_SUCCESS;
}

S
slzhou 已提交
2458 2459 2460 2461 2462
// 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 已提交
2463
  SLogicNode* pChild = (SLogicNode*)nodesListGetNode(pNode->pChildren, 0);
S
slzhou 已提交
2464
  if (QUERY_NODE_LOGIC_PLAN_PROJECT != nodeType(pChild) || 1 < LIST_LENGTH(pChild->pChildren) ||
2465
      NULL != pChild->pConditions || NULL != pChild->pLimit || NULL != pChild->pSlimit) {
S
slzhou 已提交
2466 2467 2468 2469 2470 2471
    return false;
  }
  return true;
}

typedef struct SMergeProjectionsContext {
2472
  SProjectLogicNode* pChildProj;
X
Xiaoyu Wang 已提交
2473
  int32_t            errCode;
S
slzhou 已提交
2474 2475 2476
} SMergeProjectionsContext;

static EDealRes mergeProjectionsExpr(SNode** pNode, void* pContext) {
2477
  SMergeProjectionsContext* pCxt = pContext;
X
Xiaoyu Wang 已提交
2478
  SProjectLogicNode*        pChildProj = pCxt->pChildProj;
2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490
  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;
            }
2491 2492
            snprintf(((SExprNode*)pExpr)->aliasName, sizeof(((SExprNode*)pExpr)->aliasName), "%s",
                     ((SExprNode*)*pNode)->aliasName);
2493 2494
            nodesDestroyNode(*pNode);
            *pNode = pExpr;
2495
            return DEAL_RES_IGNORE_CHILD;
2496 2497 2498 2499 2500
          }
        }
      }
    }
  }
S
slzhou 已提交
2501 2502 2503
  return DEAL_RES_CONTINUE;
}

2504
static int32_t mergeProjectsOptimizeImpl(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan, SLogicNode* pSelfNode) {
2505
  SLogicNode* pChild = (SLogicNode*)nodesListGetNode(pSelfNode->pChildren, 0);
2506

2507
  SMergeProjectionsContext cxt = {.pChildProj = (SProjectLogicNode*)pChild, .errCode = TSDB_CODE_SUCCESS};
2508
  nodesRewriteExprs(((SProjectLogicNode*)pSelfNode)->pProjections, mergeProjectionsExpr, &cxt);
2509
  int32_t code = cxt.errCode;
2510

2511 2512 2513 2514 2515
  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
2516
      NODES_CLEAR_LIST(pSelfNode->pChildren);
2517 2518 2519 2520 2521 2522 2523
    }
  }

  if (TSDB_CODE_SUCCESS == code) {
    NODES_CLEAR_LIST(pChild->pChildren);
  }
  nodesDestroyNode((SNode*)pChild);
2524
  pCxt->optimized = true;
2525
  return code;
S
slzhou 已提交
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536
}

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

2537
static bool tagScanOptShouldBeOptimized(SLogicNode* pNode) {
S
slzhou@taodata.com 已提交
2538 2539 2540
  if (QUERY_NODE_LOGIC_PLAN_SCAN != nodeType(pNode) || (SCAN_TYPE_TAG == ((SScanLogicNode*)pNode)->scanType)) {
    return false;
  }
2541
  SScanLogicNode* pScan = (SScanLogicNode*)pNode;
2542
  if (pScan->hasNormalCols) {
2543 2544
    return false;
  }
S
slzhou 已提交
2545 2546 2547
  if (pScan->tableType == TSDB_SYSTEM_TABLE) {
    return false;
  }
2548 2549
  if (NULL == pNode->pParent || QUERY_NODE_LOGIC_PLAN_AGG != nodeType(pNode->pParent) ||
      1 != LIST_LENGTH(pNode->pParent->pChildren)) {
S
slzhou@taodata.com 已提交
2550 2551 2552 2553
    return false;
  }

  SAggLogicNode* pAgg = (SAggLogicNode*)(pNode->pParent);
2554 2555
  if (NULL == pAgg->pGroupKeys || NULL != pAgg->pAggFuncs || planOptNodeListHasCol(pAgg->pGroupKeys) ||
      !planOptNodeListHasTbname(pAgg->pGroupKeys)) {
S
slzhou@taodata.com 已提交
2556 2557
    return false;
  }
2558

2559 2560 2561 2562 2563 2564 2565 2566 2567
  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 已提交
2568 2569 2570
  return true;
}

2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
static SLogicNode* tagScanOptFindAncestorWithSlimit(SLogicNode* pTableScanNode) {
  SLogicNode* pNode = pTableScanNode->pParent;
  while (NULL != pNode) {
    if (QUERY_NODE_LOGIC_PLAN_PARTITION == nodeType(pNode) || QUERY_NODE_LOGIC_PLAN_AGG == nodeType(pNode) ||
        QUERY_NODE_LOGIC_PLAN_WINDOW == nodeType(pNode) || QUERY_NODE_LOGIC_PLAN_SORT == nodeType(pNode)) {
      return NULL;
    }
    if (NULL != pNode->pSlimit) {
      return pNode;
    }
    pNode = pNode->pParent;
  }
  return NULL;
}

static void tagScanOptCloneAncestorSlimit(SLogicNode* pTableScanNode) {
  if (NULL != pTableScanNode->pSlimit) {
    return;
  }

  SLogicNode* pNode = tagScanOptFindAncestorWithSlimit(pTableScanNode);
  if (NULL != pNode) {
2593
    // TODO: only set the slimit now. push down slimit later
2594
    pTableScanNode->pSlimit = nodesCloneNode(pNode->pSlimit);
2595 2596
    ((SLimitNode*)pTableScanNode->pSlimit)->limit += ((SLimitNode*)pTableScanNode->pSlimit)->offset;
    ((SLimitNode*)pTableScanNode->pSlimit)->offset = 0;
2597 2598 2599 2600
  }
  return;
}

S
slzhou@taodata.com 已提交
2601
static int32_t tagScanOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
2602
  SScanLogicNode* pScanNode = (SScanLogicNode*)optFindPossibleNode(pLogicSubplan->pNode, tagScanOptShouldBeOptimized);
S
slzhou@taodata.com 已提交
2603 2604 2605 2606 2607
  if (NULL == pScanNode) {
    return TSDB_CODE_SUCCESS;
  }

  pScanNode->scanType = SCAN_TYPE_TAG;
2608 2609
  SNode* pTarget = NULL;
  FOREACH(pTarget, pScanNode->node.pTargets) {
2610 2611 2612 2613
    if (PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)(pTarget))->colId) {
      ERASE_NODE(pScanNode->node.pTargets);
      break;
    }
2614
  }
2615

2616 2617
  NODES_DESTORY_LIST(pScanNode->pScanCols);

2618
  SLogicNode* pAgg = pScanNode->node.pParent;
2619 2620 2621 2622 2623 2624
  if (NULL == pAgg->pParent) {
    SNodeList* pScanTargets = nodesMakeList();

    SNode* pAggTarget = NULL;
    FOREACH(pAggTarget, pAgg->pTargets) {
      SNode* pScanTarget = NULL;
X
Xiaoyu Wang 已提交
2625
      FOREACH(pScanTarget, pScanNode->node.pTargets) {
2626
        if (0 == strcmp(((SColumnNode*)pAggTarget)->colName, ((SColumnNode*)pScanTarget)->colName)) {
2627 2628 2629 2630 2631 2632 2633 2634 2635
          nodesListAppend(pScanTargets, nodesCloneNode(pScanTarget));
          break;
        }
      }
    }
    nodesDestroyList(pScanNode->node.pTargets);
    pScanNode->node.pTargets = pScanTargets;
  }

2636 2637 2638 2639 2640
  int32_t code = replaceLogicNode(pLogicSubplan, pAgg, (SLogicNode*)pScanNode);
  if (TSDB_CODE_SUCCESS == code) {
    NODES_CLEAR_LIST(pAgg->pChildren);
  }
  nodesDestroyNode((SNode*)pAgg);
2641
  tagScanOptCloneAncestorSlimit((SLogicNode*)pScanNode);
S
slzhou@taodata.com 已提交
2642 2643 2644 2645
  pCxt->optimized = true;
  return TSDB_CODE_SUCCESS;
}

2646
static bool pushDownLimitOptShouldBeOptimized(SLogicNode* pNode) {
2647 2648 2649 2650 2651
  if (NULL == pNode->pLimit || 1 != LIST_LENGTH(pNode->pChildren)) {
    return false;
  }

  SLogicNode* pChild = (SLogicNode*)nodesListGetNode(pNode->pChildren, 0);
2652
  // push down to sort node
2653 2654
  if (QUERY_NODE_LOGIC_PLAN_SORT == nodeType(pChild)) {
    // if we have pushed down, we skip it
2655 2656 2657 2658
    if (pChild->pLimit) return false;
  } else if (QUERY_NODE_LOGIC_PLAN_SCAN != nodeType(pChild) || QUERY_NODE_LOGIC_PLAN_SORT == nodeType(pNode)) {
    // push down to table scan node
    // if pNode is sortNode, we skip push down limit info to table scan node
2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671
    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);
2672
  if (QUERY_NODE_LOGIC_PLAN_SORT == nodeType(pChild)) {
2673 2674 2675 2676
    pChild->pLimit = nodesCloneNode(pNode->pLimit);
    SLimitNode* pLimit = (SLimitNode*)pChild->pLimit;
    pLimit->limit += pLimit->offset;
    pLimit->offset = 0;
2677 2678 2679 2680
  } else {
    pChild->pLimit = pNode->pLimit;
    pNode->pLimit = NULL;
  }
2681 2682 2683 2684 2685
  pCxt->optimized = true;

  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
2686 2687 2688 2689 2690 2691
typedef struct STbCntScanOptInfo {
  SAggLogicNode*  pAgg;
  SScanLogicNode* pScan;
  SName           table;
} STbCntScanOptInfo;

X
Xiaoyu Wang 已提交
2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706
static bool tbCntScanOptIsEligibleGroupKeys(SNodeList* pGroupKeys) {
  if (NULL == pGroupKeys) {
    return true;
  }

  SNode* pGroupKey = NULL;
  FOREACH(pGroupKey, pGroupKeys) {
    SNode* pKey = nodesListGetNode(((SGroupingSetNode*)pGroupKey)->pParameterList, 0);
    if (QUERY_NODE_COLUMN != nodeType(pKey)) {
      return false;
    }
    SColumnNode* pCol = (SColumnNode*)pKey;
    if (0 != strcmp(pCol->colName, "db_name") && 0 != strcmp(pCol->colName, "stable_name")) {
      return false;
    }
X
Xiaoyu Wang 已提交
2707
  }
X
Xiaoyu Wang 已提交
2708 2709 2710 2711 2712 2713

  return true;
}

static bool tbCntScanOptNotNullableExpr(SNode* pNode) {
  if (QUERY_NODE_COLUMN != nodeType(pNode)) {
X
Xiaoyu Wang 已提交
2714 2715
    return false;
  }
X
Xiaoyu Wang 已提交
2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729
  const char* pColName = ((SColumnNode*)pNode)->colName;
  return 0 == strcmp(pColName, "*") || 0 == strcmp(pColName, "db_name") || 0 == strcmp(pColName, "stable_name") ||
         0 == strcmp(pColName, "table_name");
}

static bool tbCntScanOptIsEligibleAggFuncs(SNodeList* pAggFuncs) {
  SNode* pNode = NULL;
  FOREACH(pNode, pAggFuncs) {
    SFunctionNode* pFunc = (SFunctionNode*)nodesListGetNode(pAggFuncs, 0);
    if (FUNCTION_TYPE_COUNT != pFunc->funcType ||
        !tbCntScanOptNotNullableExpr(nodesListGetNode(pFunc->pParameterList, 0))) {
      return false;
    }
  }
2730
  return LIST_LENGTH(pAggFuncs) > 0;
X
Xiaoyu Wang 已提交
2731 2732
}

X
Xiaoyu Wang 已提交
2733
static bool tbCntScanOptIsEligibleAgg(SAggLogicNode* pAgg) {
2734
  return tbCntScanOptIsEligibleGroupKeys(pAgg->pGroupKeys) && tbCntScanOptIsEligibleAggFuncs(pAgg->pAggFuncs);
X
Xiaoyu Wang 已提交
2735 2736
}

X
Xiaoyu Wang 已提交
2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797
static bool tbCntScanOptGetColValFromCond(SOperatorNode* pOper, SColumnNode** pCol, SValueNode** pVal) {
  if (OP_TYPE_EQUAL != pOper->opType) {
    return false;
  }

  *pCol = NULL;
  *pVal = NULL;
  if (QUERY_NODE_COLUMN == nodeType(pOper->pLeft)) {
    *pCol = (SColumnNode*)pOper->pLeft;
  } else if (QUERY_NODE_VALUE == nodeType(pOper->pLeft)) {
    *pVal = (SValueNode*)pOper->pLeft;
  }
  if (QUERY_NODE_COLUMN == nodeType(pOper->pRight)) {
    *pCol = (SColumnNode*)pOper->pRight;
  } else if (QUERY_NODE_VALUE == nodeType(pOper->pRight)) {
    *pVal = (SValueNode*)pOper->pRight;
  }

  return NULL != *pCol && NULL != *pVal;
}

static bool tbCntScanOptIsEligibleLogicCond(STbCntScanOptInfo* pInfo, SLogicConditionNode* pCond) {
  if (LOGIC_COND_TYPE_AND != pCond->condType) {
    return false;
  }

  bool         hasDbCond = false;
  bool         hasStbCond = false;
  SColumnNode* pCol = NULL;
  SValueNode*  pVal = NULL;
  SNode*       pNode = NULL;
  FOREACH(pNode, pCond->pParameterList) {
    if (QUERY_NODE_OPERATOR != nodeType(pNode) || !tbCntScanOptGetColValFromCond((SOperatorNode*)pNode, &pCol, &pVal)) {
      return false;
    }
    if (!hasDbCond && 0 == strcmp(pCol->colName, "db_name")) {
      hasDbCond = true;
      strcpy(pInfo->table.dbname, pVal->literal);
    } else if (!hasStbCond && 0 == strcmp(pCol->colName, "stable_name")) {
      hasStbCond = true;
      strcpy(pInfo->table.tname, pVal->literal);
    } else {
      return false;
    }
  }
  return hasDbCond;
}

static bool tbCntScanOptIsEligibleOpCond(SOperatorNode* pCond) {
  SColumnNode* pCol = NULL;
  SValueNode*  pVal = NULL;
  if (!tbCntScanOptGetColValFromCond(pCond, &pCol, &pVal)) {
    return false;
  }
  return 0 == strcmp(pCol->colName, "db_name");
}

static bool tbCntScanOptIsEligibleConds(STbCntScanOptInfo* pInfo, SNode* pConditions) {
  if (NULL == pConditions) {
    return true;
  }
S
shenglian zhou 已提交
2798 2799 2800
  if (LIST_LENGTH(pInfo->pAgg->pGroupKeys) != 0) {
    return false;
  }
X
Xiaoyu Wang 已提交
2801
  if (QUERY_NODE_LOGIC_CONDITION == nodeType(pConditions)) {
S
shenglian zhou 已提交
2802
    return tbCntScanOptIsEligibleLogicCond(pInfo, (SLogicConditionNode*)pConditions);
X
Xiaoyu Wang 已提交
2803 2804 2805
  }

  if (QUERY_NODE_OPERATOR == nodeType(pConditions)) {
S
shenglian zhou 已提交
2806
    return tbCntScanOptIsEligibleOpCond((SOperatorNode*)pConditions);
X
Xiaoyu Wang 已提交
2807 2808 2809 2810 2811 2812 2813 2814 2815 2816
  }

  return false;
}

static bool tbCntScanOptIsEligibleScan(STbCntScanOptInfo* pInfo) {
  if (0 != strcmp(pInfo->pScan->tableName.dbname, TSDB_INFORMATION_SCHEMA_DB) ||
      0 != strcmp(pInfo->pScan->tableName.tname, TSDB_INS_TABLE_TABLES) || NULL != pInfo->pScan->pGroupTags) {
    return false;
  }
X
Xiaoyu Wang 已提交
2817 2818 2819
  if (1 == pInfo->pScan->pVgroupList->numOfVgroups && MNODE_HANDLE == pInfo->pScan->pVgroupList->vgroups[0].vgId) {
    return false;
  }
X
Xiaoyu Wang 已提交
2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847
  return tbCntScanOptIsEligibleConds(pInfo, pInfo->pScan->node.pConditions);
}

static bool tbCntScanOptShouldBeOptimized(SLogicNode* pNode, STbCntScanOptInfo* pInfo) {
  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;
  }

  pInfo->pAgg = (SAggLogicNode*)pNode;
  pInfo->pScan = (SScanLogicNode*)nodesListGetNode(pNode->pChildren, 0);
  return tbCntScanOptIsEligibleAgg(pInfo->pAgg) && tbCntScanOptIsEligibleScan(pInfo);
}

static SNode* tbCntScanOptCreateTableCountFunc() {
  SFunctionNode* pFunc = (SFunctionNode*)nodesMakeNode(QUERY_NODE_FUNCTION);
  if (NULL == pFunc) {
    return NULL;
  }
  strcpy(pFunc->functionName, "_table_count");
  strcpy(pFunc->node.aliasName, "_table_count");
  if (TSDB_CODE_SUCCESS != fmGetFuncInfo(pFunc, NULL, 0)) {
    nodesDestroyNode((SNode*)pFunc);
    return NULL;
  }
  return (SNode*)pFunc;
}

X
Xiaoyu Wang 已提交
2848 2849 2850 2851
static int32_t tbCntScanOptRewriteScan(STbCntScanOptInfo* pInfo) {
  pInfo->pScan->scanType = SCAN_TYPE_TABLE_COUNT;
  strcpy(pInfo->pScan->tableName.dbname, pInfo->table.dbname);
  strcpy(pInfo->pScan->tableName.tname, pInfo->table.tname);
X
Xiaoyu Wang 已提交
2852 2853
  NODES_DESTORY_LIST(pInfo->pScan->node.pTargets);
  NODES_DESTORY_LIST(pInfo->pScan->pScanCols);
X
Xiaoyu Wang 已提交
2854 2855 2856
  NODES_DESTORY_NODE(pInfo->pScan->node.pConditions);
  NODES_DESTORY_LIST(pInfo->pScan->pScanPseudoCols);
  int32_t code = nodesListMakeStrictAppend(&pInfo->pScan->pScanPseudoCols, tbCntScanOptCreateTableCountFunc());
X
Xiaoyu Wang 已提交
2857
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
2858 2859 2860 2861
    code = createColumnByRewriteExpr(nodesListGetNode(pInfo->pScan->pScanPseudoCols, 0), &pInfo->pScan->node.pTargets);
  }
  SNode* pGroupKey = NULL;
  FOREACH(pGroupKey, pInfo->pAgg->pGroupKeys) {
X
Xiaoyu Wang 已提交
2862 2863 2864 2865 2866 2867 2868 2869
    SNode* pGroupCol = nodesListGetNode(((SGroupingSetNode*)pGroupKey)->pParameterList, 0);
    code = nodesListMakeStrictAppend(&pInfo->pScan->pGroupTags, nodesCloneNode(pGroupCol));
    if (TSDB_CODE_SUCCESS == code) {
      code = nodesListMakeStrictAppend(&pInfo->pScan->pScanCols, nodesCloneNode(pGroupCol));
    }
    if (TSDB_CODE_SUCCESS == code) {
      code = nodesListMakeStrictAppend(&pInfo->pScan->node.pTargets, nodesCloneNode(pGroupCol));
    }
X
Xiaoyu Wang 已提交
2870 2871 2872
    if (TSDB_CODE_SUCCESS != code) {
      break;
    }
X
Xiaoyu Wang 已提交
2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883
  }
  return code;
}

static int32_t tbCntScanOptCreateSumFunc(SFunctionNode* pCntFunc, SNode* pParam, SNode** pOutput) {
  SFunctionNode* pFunc = (SFunctionNode*)nodesMakeNode(QUERY_NODE_FUNCTION);
  if (NULL == pFunc) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  strcpy(pFunc->functionName, "sum");
  strcpy(pFunc->node.aliasName, pCntFunc->node.aliasName);
X
Xiaoyu Wang 已提交
2884
  int32_t code = createColumnByRewriteExpr(pParam, &pFunc->pParameterList);
X
Xiaoyu Wang 已提交
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896
  if (TSDB_CODE_SUCCESS == code) {
    code = fmGetFuncInfo(pFunc, NULL, 0);
  }
  if (TSDB_CODE_SUCCESS == code) {
    *pOutput = (SNode*)pFunc;
  } else {
    nodesDestroyNode((SNode*)pFunc);
  }
  return code;
}

static int32_t tbCntScanOptRewriteAgg(SAggLogicNode* pAgg) {
X
Xiaoyu Wang 已提交
2897 2898 2899 2900
  SScanLogicNode* pScan = (SScanLogicNode*)nodesListGetNode(pAgg->node.pChildren, 0);
  SNode*          pSum = NULL;
  int32_t         code = tbCntScanOptCreateSumFunc((SFunctionNode*)nodesListGetNode(pAgg->pAggFuncs, 0),
                                                   nodesListGetNode(pScan->pScanPseudoCols, 0), &pSum);
X
Xiaoyu Wang 已提交
2901 2902 2903 2904
  if (TSDB_CODE_SUCCESS == code) {
    NODES_DESTORY_LIST(pAgg->pAggFuncs);
    code = nodesListMakeStrictAppend(&pAgg->pAggFuncs, pSum);
  }
X
Xiaoyu Wang 已提交
2905 2906 2907
  if (TSDB_CODE_SUCCESS == code) {
    code = partTagsRewriteGroupTagsToFuncs(pScan->pGroupTags, 0, pAgg);
  }
X
Xiaoyu Wang 已提交
2908
  NODES_DESTORY_LIST(pAgg->pGroupKeys);
X
Xiaoyu Wang 已提交
2909 2910 2911 2912 2913 2914 2915 2916 2917
  return code;
}

static int32_t tableCountScanOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  STbCntScanOptInfo info = {0};
  if (!optFindEligibleNode(pLogicSubplan->pNode, (FShouldBeOptimized)tbCntScanOptShouldBeOptimized, &info)) {
    return TSDB_CODE_SUCCESS;
  }

X
Xiaoyu Wang 已提交
2918
  int32_t code = tbCntScanOptRewriteScan(&info);
X
Xiaoyu Wang 已提交
2919 2920 2921 2922 2923 2924
  if (TSDB_CODE_SUCCESS == code) {
    code = tbCntScanOptRewriteAgg(info.pAgg);
  }
  return code;
}

2925 2926 2927 2928 2929
static SSortLogicNode* sortNonPriKeySatisfied(SLogicNode* pNode) {
  if (QUERY_NODE_LOGIC_PLAN_SORT != nodeType(pNode)) {
    return NULL;
  }
  SSortLogicNode* pSort = (SSortLogicNode*)pNode;
W
wangjiaming0909 已提交
2930
  if (sortPriKeyOptIsPriKeyOrderBy(pSort->pSortKeys)) {
2931 2932
    return NULL;
  }
2933
  SNode *pSortKeyNode = NULL, *pSortKeyExpr = NULL;
W
wangjiaming0909 已提交
2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944
  FOREACH(pSortKeyNode, pSort->pSortKeys) {
    pSortKeyExpr = ((SOrderByExprNode*)pSortKeyNode)->pExpr;
    switch (nodeType(pSortKeyExpr)) {
      case QUERY_NODE_COLUMN:
        break;
      case QUERY_NODE_VALUE:
        continue;
      default:
        return NULL;
    }
  }
2945

W
wangjiaming0909 已提交
2946 2947
  if (!pSortKeyExpr || ((SColumnNode*)pSortKeyExpr)->projIdx != 1 ||
      ((SColumnNode*)pSortKeyExpr)->node.resType.type != TSDB_DATA_TYPE_TIMESTAMP) {
2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965
    return NULL;
  }
  return pSort;
}

static bool sortNonPriKeyShouldOptimize(SLogicNode* pNode, void* pInfo) {
  SSortLogicNode* pSort = sortNonPriKeySatisfied(pNode);
  if (!pSort) return false;
  SNodeList* pSortNodeList = pInfo;
  nodesListAppend(pSortNodeList, (SNode*)pSort);
  return false;
}

static int32_t sortNonPriKeyOptimize(SOptimizeContext* pCxt, SLogicSubplan* pLogicSubplan) {
  SNodeList* pNodeList = nodesMakeList();
  optFindEligibleNode(pLogicSubplan->pNode, sortNonPriKeyShouldOptimize, pNodeList);
  SNode* pNode = NULL;
  FOREACH(pNode, pNodeList) {
2966
    SSortLogicNode*   pSort = (SSortLogicNode*)pNode;
2967 2968 2969 2970 2971 2972 2973 2974 2975
    SOrderByExprNode* pOrderByExpr = (SOrderByExprNode*)nodesListGetNode(pSort->pSortKeys, 0);
    pSort->node.outputTsOrder = pOrderByExpr->order;
    optSetParentOrder(pSort->node.pParent, pOrderByExpr->order, NULL);
  }
  pCxt->optimized = false;
  nodesClearList(pNodeList);
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
2976 2977
// clang-format off
static const SOptimizeRule optimizeRuleSet[] = {
2978
  {.pName = "ScanPath",                   .optimizeFunc = scanPathOptimize},
2979
  {.pName = "PushDownCondition",          .optimizeFunc = pushDownCondOptimize},
2980
  {.pName = "sortNonPriKeyOptimize",      .optimizeFunc = sortNonPriKeyOptimize},
2981
  {.pName = "SortPrimaryKey",             .optimizeFunc = sortPrimaryKeyOptimize},
2982
  {.pName = "SmaIndex",                   .optimizeFunc = smaIndexOptimize},
S
slzhou 已提交
2983
  {.pName = "PartitionTags",              .optimizeFunc = partTagsOptimize},
S
slzhou 已提交
2984
  {.pName = "MergeProjects",              .optimizeFunc = mergeProjectsOptimize},
S
slzhou 已提交
2985
  {.pName = "EliminateProject",           .optimizeFunc = eliminateProjOptimize},
X
Xiaoyu Wang 已提交
2986
  {.pName = "EliminateSetOperator",       .optimizeFunc = eliminateSetOpOptimize},
2987
  {.pName = "RewriteTail",                .optimizeFunc = rewriteTailOptimize},
2988
  {.pName = "RewriteUnique",              .optimizeFunc = rewriteUniqueOptimize},
X
Xiaoyu Wang 已提交
2989
  {.pName = "LastRowScan",                .optimizeFunc = lastRowScanOptimize},
2990
  {.pName = "TagScan",                    .optimizeFunc = tagScanOptimize},
X
Xiaoyu Wang 已提交
2991 2992
  {.pName = "PushDownLimit",              .optimizeFunc = pushDownLimitOptimize},
  {.pName = "TableCountScan",             .optimizeFunc = tableCountScanOptimize},
X
Xiaoyu Wang 已提交
2993 2994
};
// clang-format on
2995 2996 2997

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

2998
static void dumpLogicSubplan(const char* pRuleName, SLogicSubplan* pSubplan) {
2999
  if (!tsQueryPlannerTrace) {
3000 3001
    return;
  }
3002 3003
  char* pStr = NULL;
  nodesNodeToString((SNode*)pSubplan, false, &pStr, NULL);
3004 3005 3006 3007 3008
  if (NULL == pRuleName) {
    qDebugL("before optimize: %s", pStr);
  } else {
    qDebugL("apply optimize %s rule: %s", pRuleName, pStr);
  }
3009 3010 3011
  taosMemoryFree(pStr);
}

X
Xiaoyu Wang 已提交
3012
static int32_t applyOptimizeRule(SPlanContext* pCxt, SLogicSubplan* pLogicSubplan) {
X
Xiaoyu Wang 已提交
3013
  SOptimizeContext cxt = {.pPlanCxt = pCxt, .optimized = false};
3014
  bool             optimized = false;
3015
  dumpLogicSubplan(NULL, pLogicSubplan);
3016
  do {
3017
    optimized = false;
3018
    for (int32_t i = 0; i < optimizeRuleNum; ++i) {
3019
      cxt.optimized = false;
X
Xiaoyu Wang 已提交
3020
      int32_t code = optimizeRuleSet[i].optimizeFunc(&cxt, pLogicSubplan);
3021 3022 3023
      if (TSDB_CODE_SUCCESS != code) {
        return code;
      }
3024 3025 3026 3027
      if (cxt.optimized) {
        optimized = true;
        dumpLogicSubplan(optimizeRuleSet[i].pName, pLogicSubplan);
      }
3028
    }
3029
  } while (optimized);
X
Xiaoyu Wang 已提交
3030 3031
  return TSDB_CODE_SUCCESS;
}
3032

X
Xiaoyu Wang 已提交
3033
int32_t optimizeLogicPlan(SPlanContext* pCxt, SLogicSubplan* pLogicSubplan) {
3034 3035 3036
  if (SUBPLAN_TYPE_MODIFY == pLogicSubplan->subplanType && NULL == pLogicSubplan->pNode->pChildren) {
    return TSDB_CODE_SUCCESS;
  }
X
Xiaoyu Wang 已提交
3037
  return applyOptimizeRule(pCxt, pLogicSubplan);
X
Xiaoyu Wang 已提交
3038
}