astValidate.c 144.0 KB
Newer Older
H
Haojun Liao 已提交
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 "astGenerator.h"
17
#include "function.h"
H
Haojun Liao 已提交
18
#include "parserInt.h"
19
#include "parserUtil.h"
20
#include "queryInfoUtil.h"
21 22 23 24
#include "tbuffer.h"
#include "tglobal.h"
#include "tmsgtype.h"
#include "ttime.h"
25
#include "astToMsg.h"
26

27 28 29 30
#define TSQL_TBNAME_L "tbname"
#define DEFAULT_PRIMARY_TIMESTAMP_COL_NAME "_c0"
#define VALID_COLUMN_INDEX(index) (((index).tableIndex >= 0) && ((index).columnIndex >= TSDB_TBNAME_COLUMN_INDEX))

31 32
#define TSWINDOW_IS_EQUAL(t1, t2) (((t1).skey == (t2).skey) && ((t1).ekey == (t2).ekey))

33 34 35 36
// -1 is tbname column index, so here use the -2 as the initial value
#define COLUMN_INDEX_INITIAL_VAL (-2)
#define COLUMN_INDEX_INITIALIZER { COLUMN_INDEX_INITIAL_VAL, COLUMN_INDEX_INITIAL_VAL }

H
Haojun Liao 已提交
37 38 39 40 41
static int32_t resColId = 5000;
int32_t getNewResColId() {
  return resColId++;
}

42
static int32_t validateSelectNodeList(SQueryStmtInfo* pQueryInfo, SArray* pSelNodeList, bool outerQuery, SMsgBuf* pMsgBuf);
43 44
static int32_t extractFunctionParameterInfo(SQueryStmtInfo* pQueryInfo, int32_t tokenId, STableMetaInfo** pTableMetaInfo, SSchema* columnSchema,
                                            tExprNode** pNode, SColumnIndex* pIndex, tSqlExprItem* pParamElem, SMsgBuf* pMsgBuf);
45

46
void setTokenAndResColumnName(tSqlExprItem* pItem, char* resColumnName, char* rawName, int32_t nameLength) {
47 48 49 50 51 52
  memset(resColumnName, 0, nameLength);

  int32_t len = ((int32_t)pItem->pNode->exprToken.n < nameLength) ? (int32_t)pItem->pNode->exprToken.n : nameLength;
  strncpy(rawName, pItem->pNode->exprToken.z, len);

  if (pItem->aliasName != NULL) {
53 54
    assert(strlen(pItem->aliasName) < nameLength);
    tstrncpy(resColumnName, pItem->aliasName, len);
55 56 57 58
  } else {
    strncpy(resColumnName, rawName, len);
  }
}
59

60
static int32_t evaluateSqlNodeImpl(tSqlExpr* pExpr, int32_t tsPrecision) {
61 62
  int32_t code = 0;
  if (pExpr->type == SQL_NODE_EXPR) {
63
    code = evaluateSqlNodeImpl(pExpr->pLeft, tsPrecision);
64 65 66 67
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

68
    code = evaluateSqlNodeImpl(pExpr->pRight, tsPrecision);
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    if (pExpr->pLeft->type == SQL_NODE_VALUE && pExpr->pRight->type == SQL_NODE_VALUE) {
      tSqlExpr* pLeft  = pExpr->pLeft;
      tSqlExpr* pRight = pExpr->pRight;
      if ((pLeft->tokenId == TK_TIMESTAMP && (pRight->tokenId == TK_INTEGER || pRight->tokenId == TK_FLOAT)) ||
          ((pRight->tokenId == TK_TIMESTAMP && (pLeft->tokenId == TK_INTEGER || pLeft->tokenId == TK_FLOAT)))) {
        return TSDB_CODE_TSC_SQL_SYNTAX_ERROR;
      } else if (pLeft->tokenId == TK_TIMESTAMP && pRight->tokenId == TK_TIMESTAMP) {
        tSqlExprEvaluate(pExpr);
      } else {
        tSqlExprEvaluate(pExpr);
      }
    } else {
      // Other types of expressions are not evaluated, they will be handled during the validation of the abstract syntax tree.
    }
  } else if (pExpr->type == SQL_NODE_VALUE) {
    if (pExpr->tokenId == TK_NOW) {
89
      pExpr->value.i     = taosGetTimestamp(tsPrecision);
90 91 92 93 94
      pExpr->value.nType = TSDB_DATA_TYPE_BIGINT;
      pExpr->tokenId     = TK_TIMESTAMP;
    } else if (pExpr->tokenId == TK_VARIABLE) {
      char    unit = 0;
      SToken* pToken = &pExpr->exprToken;
95
      int32_t ret = parseAbsoluteDuration(pToken->z, pToken->n, &pExpr->value.i, &unit, tsPrecision);
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
      if (ret != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_TSC_SQL_SYNTAX_ERROR;
      }

      pExpr->value.nType = TSDB_DATA_TYPE_BIGINT;
      pExpr->tokenId = TK_TIMESTAMP;
    }  else if (pExpr->tokenId == TK_NULL) {
      pExpr->value.nType = TSDB_DATA_TYPE_NULL;
    } else if (pExpr->tokenId == TK_INTEGER || pExpr->tokenId == TK_STRING || pExpr->tokenId == TK_FLOAT || pExpr->tokenId == TK_BOOL) {
      SToken* pToken = &pExpr->exprToken;

      int32_t tokenType = pToken->type;
      toTSDBType(tokenType);
      taosVariantCreate(&pExpr->value, pToken->z, pToken->n, tokenType);
    }

    return  TSDB_CODE_SUCCESS;
    // other types of data are handled in the parent level.
114 115
  } else if (pExpr->type == SQL_NODE_SQLFUNCTION) {
    SArray* pParam = pExpr->Expr.paramList;
H
Haojun Liao 已提交
116 117 118 119 120 121

    if (pParam != NULL) {
      for (int32_t i = 0; i < taosArrayGetSize(pParam); ++i) {
        tSqlExprItem* pItem = taosArrayGet(pParam, i);
        evaluateSqlNodeImpl(pItem->pNode, tsPrecision);
      }
122
    }
123 124 125 126 127
  }

  return  TSDB_CODE_SUCCESS;
}

128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
void destroyFilterInfo(SColumnFilterList* pFilterList) {
  if (pFilterList->filterInfo == NULL) {
    pFilterList->numOfFilters = 0;
    return;
  }

  for(int32_t i = 0; i < pFilterList->numOfFilters; ++i) {
    if (pFilterList->filterInfo[i].filterstr) {
      tfree(pFilterList->filterInfo[i].pz);
    }
  }

  tfree(pFilterList->filterInfo);
  pFilterList->numOfFilters = 0;
}

void columnDestroy(SColumn* pCol) {
  destroyFilterInfo(&pCol->info.flist);
  free(pCol);
}

149
void destroyColumnList(SArray* pColumnList) {
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
  if (pColumnList == NULL) {
    return;
  }

  size_t num = taosArrayGetSize(pColumnList);
  for (int32_t i = 0; i < num; ++i) {
    SColumn* pCol = taosArrayGetP(pColumnList, i);
    columnDestroy(pCol);
  }

  taosArrayDestroy(pColumnList);
}

void clearTableMetaInfo(STableMetaInfo* pTableMetaInfo) {
  if (pTableMetaInfo == NULL) {
    return;
  }

  tfree(pTableMetaInfo->pTableMeta);
  tfree(pTableMetaInfo->vgroupList);

171
  destroyColumnList(pTableMetaInfo->tagColList);
172 173 174 175 176 177
  pTableMetaInfo->tagColList = NULL;

  free(pTableMetaInfo);
}

static STableMeta* extractTempTableMetaFromSubquery(SQueryStmtInfo* pUpstream) {
H
Haojun Liao 已提交
178
  STableMetaInfo* pUpstreamTableMetaInfo = getMetaInfo(pUpstream, 0);
179 180 181 182 183 184 185 186 187 188 189 190

  int32_t     numOfColumns = pUpstream->fieldsInfo.numOfOutput;
  STableMeta *meta = calloc(1, sizeof(STableMeta) + sizeof(SSchema) * numOfColumns);
  meta->tableType = TSDB_TEMP_TABLE;

  STableComInfo *info = &meta->tableInfo;
  info->numOfColumns = numOfColumns;
  info->precision    = pUpstreamTableMetaInfo->pTableMeta->tableInfo.precision;
  info->numOfTags    = 0;

  int32_t n = 0;
  for(int32_t i = 0; i < numOfColumns; ++i) {
H
Haojun Liao 已提交
191 192 193 194 195 196 197 198
    SInternalField* pField = getInternalField(&pUpstream->fieldsInfo, i);
    if (!pField->visible) {
      continue;
    }

    meta->schema[n] = pField->pExpr->base.resSchema;
    info->rowSize += meta->schema[n].bytes;
    n += 1;
199 200 201 202 203 204
  }

  info->numOfColumns = n;
  return meta;
}

205 206 207
SQueryStmtInfo *createQueryInfo() {
  SQueryStmtInfo* pQueryInfo = calloc(1, sizeof(SQueryStmtInfo));

208
  pQueryInfo->fieldsInfo.internalField = taosArrayInit(4, sizeof(SInternalField));
209 210 211 212 213 214 215
  pQueryInfo->colList        = taosArrayInit(4, POINTER_BYTES);
  pQueryInfo->udColumnId     = TSDB_UD_COLUMN_INDEX;
  pQueryInfo->limit.limit    = -1;
  pQueryInfo->limit.offset   = 0;

  pQueryInfo->slimit.limit   = -1;
  pQueryInfo->slimit.offset  = 0;
H
Haojun Liao 已提交
216
  pQueryInfo->pDownstream = taosArrayInit(4, POINTER_BYTES);
217
  pQueryInfo->window         = TSWINDOW_INITIALIZER;
218

219 220 221 222 223 224 225
  pQueryInfo->exprList       = calloc(10, POINTER_BYTES);
  for(int32_t i = 0; i < 10; ++i) {
    pQueryInfo->exprList[i] = taosArrayInit(4, POINTER_BYTES);
  }

  pQueryInfo->exprListLevelIndex     = 0;

226 227 228 229 230 231 232 233
  return pQueryInfo;
}

static void destroyQueryInfoImpl(SQueryStmtInfo* pQueryInfo) {
  cleanupTagCond(&pQueryInfo->tagCond);
  cleanupColumnCond(&pQueryInfo->colCond);
  cleanupFieldInfo(&pQueryInfo->fieldsInfo);

234
  dropAllExprInfo(pQueryInfo->exprList, 10);
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
  pQueryInfo->exprList = NULL;

  columnListDestroy(pQueryInfo->colList);
  pQueryInfo->colList = NULL;

  if (pQueryInfo->groupbyExpr.columnInfo != NULL) {
    taosArrayDestroy(pQueryInfo->groupbyExpr.columnInfo);
    pQueryInfo->groupbyExpr.columnInfo = NULL;
  }

  pQueryInfo->fillType = 0;

  tfree(pQueryInfo->fillVal);
  tfree(pQueryInfo->buf);

H
Haojun Liao 已提交
250 251
  taosArrayDestroy(pQueryInfo->pDownstream);
  pQueryInfo->pDownstream = NULL;
252 253 254 255 256 257 258
  pQueryInfo->bufLen = 0;
}

void destroyQueryInfo(SQueryStmtInfo* pQueryInfo) {
  while (pQueryInfo != NULL) {
    SQueryStmtInfo* p = pQueryInfo->sibling;

H
Haojun Liao 已提交
259
    size_t numOfUpstream = taosArrayGetSize(pQueryInfo->pDownstream);
260
    for (int32_t i = 0; i < numOfUpstream; ++i) {
H
Haojun Liao 已提交
261
      SQueryStmtInfo* pUpQueryInfo = taosArrayGetP(pQueryInfo->pDownstream, i);
262 263 264 265 266 267 268 269 270 271
      destroyQueryInfoImpl(pUpQueryInfo);
      clearAllTableMetaInfo(pUpQueryInfo, false, 0);
      tfree(pUpQueryInfo);
    }

    destroyQueryInfoImpl(pQueryInfo);
    clearAllTableMetaInfo(pQueryInfo, false, 0);
    tfree(pQueryInfo);
    pQueryInfo = p;
  }
272 273
}

274
static int32_t doValidateSubquery(SSqlNode* pSqlNode, int32_t index, SQueryStmtInfo* pQueryInfo, SMsgBuf* pMsgBuf) {
275
  SRelElement* subInfo = taosArrayGet(pSqlNode->from->list, index);
276 277

  // union all is not support currently
278 279
  SSqlNode* p = taosArrayGetP(subInfo->pSubquery->node, 0);
  if (taosArrayGetSize(subInfo->pSubquery->node) >= 2) {
280
    return buildInvalidOperationMsg(pMsgBuf, "not support union in subquery");
281 282
  }

283
  SQueryStmtInfo* pSub = createQueryInfo();
284 285 286 287 288 289 290

  SArray *pUdfInfo = NULL;
  if (pQueryInfo->pUdfInfo) {
    pUdfInfo = taosArrayDup(pQueryInfo->pUdfInfo);
  }

  pSub->pUdfInfo = pUdfInfo;
291
  int32_t code = validateSqlNode(p, pSub, pMsgBuf);
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  // create dummy table meta info
  STableMetaInfo* pTableMetaInfo1 = calloc(1, sizeof(STableMetaInfo));
  if (pTableMetaInfo1 == NULL) {
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }

  pTableMetaInfo1->pTableMeta = extractTempTableMetaFromSubquery(pSub);

  if (subInfo->aliasName.n > 0) {
    if (subInfo->aliasName.n >= TSDB_TABLE_FNAME_LEN) {
      tfree(pTableMetaInfo1);
307
      return buildInvalidOperationMsg(pMsgBuf, "subquery alias name too long");
308 309 310 311 312
    }

    tstrncpy(pTableMetaInfo1->aliasName, subInfo->aliasName.z, subInfo->aliasName.n + 1);
  }

H
Haojun Liao 已提交
313
  taosArrayPush(pQueryInfo->pDownstream, &pSub);
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333

  // NOTE: order mix up in subquery not support yet.
  pQueryInfo->order = pSub->order;

  STableMetaInfo** tmp = realloc(pQueryInfo->pTableMetaInfo, (pQueryInfo->numOfTables + 1) * POINTER_BYTES);
  if (tmp == NULL) {
    tfree(pTableMetaInfo1);
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }

  pQueryInfo->pTableMetaInfo = tmp;

  pQueryInfo->pTableMetaInfo[pQueryInfo->numOfTables] = pTableMetaInfo1;
  pQueryInfo->numOfTables += 1;

  // all columns are added into the table column list
  STableMeta* pMeta = pTableMetaInfo1->pTableMeta;
  int32_t startOffset = (int32_t) taosArrayGetSize(pQueryInfo->colList);

  for(int32_t i = 0; i < pMeta->tableInfo.numOfColumns; ++i) {
334
    columnListInsert(pQueryInfo->colList, pMeta->uid, &pMeta->schema[i], TSDB_COL_NORMAL);
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
  }

  return TSDB_CODE_SUCCESS;
}

int32_t getTableIndexImpl(SToken* pTableToken, SQueryStmtInfo* pQueryInfo, SColumnIndex* pIndex) {
  if (pTableToken->n == 0) {  // only one table and no table name prefix in column name
    if (pQueryInfo->numOfTables == 1) {
      pIndex->tableIndex = 0;
    } else {
      pIndex->tableIndex = COLUMN_INDEX_INITIAL_VAL;
    }

    return TSDB_CODE_SUCCESS;
  }

  pIndex->tableIndex = COLUMN_INDEX_INITIAL_VAL;
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
353
    STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, i);
354 355 356
    char* name = pTableMetaInfo->aliasName;
    if (strncasecmp(name, pTableToken->z, pTableToken->n) == 0 && strlen(name) == pTableToken->n) {
      pIndex->tableIndex = i;
357
      return TSDB_CODE_SUCCESS;
358 359 360
    }
  }

361
  return TSDB_CODE_TSC_INVALID_OPERATION;
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
}

void extractTableNameFromToken(SToken* pToken, SToken* pTable) {
  const char sep = TS_PATH_DELIMITER[0];

  if (pToken == pTable || pToken == NULL || pTable == NULL) {
    return;
  }

  char* r = strnchr(pToken->z, sep, pToken->n, false);

  if (r != NULL) {  // record the table name token
    pTable->n = (uint32_t)(r - pToken->z);
    pTable->z = pToken->z;

    r += 1;
    pToken->n -= (uint32_t)(r - pToken->z);
    pToken->z = r;
  }
}

int32_t getTableIndexByName(SToken* pToken, SQueryStmtInfo* pQueryInfo, SColumnIndex* pIndex) {
  SToken tableToken = {0};
  extractTableNameFromToken(pToken, &tableToken);

  if (getTableIndexImpl(&tableToken, pQueryInfo, pIndex) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

  return TSDB_CODE_SUCCESS;
}

394
static int16_t doGetColumnIndex(SQueryStmtInfo* pQueryInfo, int32_t index, const SToken* pToken, int16_t* type) {
395 396 397
  STableMeta* pTableMeta = getMetaInfo(pQueryInfo, index)->pTableMeta;

  int32_t  numOfCols = getNumOfColumns(pTableMeta) + getNumOfTags(pTableMeta);
398
  SSchema* pSchema = getTableColumnSchema(pTableMeta);
399 400 401

  int16_t columnIndex = COLUMN_INDEX_INITIAL_VAL;

402
  for (int32_t i = 0; i < numOfCols; ++i) {
403 404 405 406 407 408 409 410 411 412
    if (pToken->n != strlen(pSchema[i].name)) {
      continue;
    }

    if (strncasecmp(pSchema[i].name, pToken->z, pToken->n) == 0) {
      columnIndex = i;
      break;
    }
  }

413
  *type = (columnIndex >= getNumOfColumns(pTableMeta))? TSDB_COL_TAG:TSDB_COL_NORMAL;
414 415 416 417 418 419 420 421 422 423 424
  return columnIndex;
}

static bool isTablenameToken(SToken* token) {
  SToken tmpToken = *token;
  SToken tableToken = {0};

  extractTableNameFromToken(&tmpToken, &tableToken);
  return (tmpToken.n == strlen(TSQL_TBNAME_L) && strncasecmp(TSQL_TBNAME_L, tmpToken.z, tmpToken.n) == 0);
}

425
int32_t doGetColumnIndexByName(SToken* pToken, SQueryStmtInfo* pQueryInfo, SColumnIndex* pIndex, SMsgBuf* pMsgBuf) {
426 427 428
  const char* msg0 = "ambiguous column name";
  const char* msg1 = "invalid column name";

429 430
  pIndex->type = TSDB_COL_NORMAL;

431 432
  if (isTablenameToken(pToken)) {
    pIndex->columnIndex = TSDB_TBNAME_COLUMN_INDEX;
433
    pIndex->type = TSDB_COL_TAG;
434 435
  } else if (strlen(DEFAULT_PRIMARY_TIMESTAMP_COL_NAME) == pToken->n &&
             strncasecmp(pToken->z, DEFAULT_PRIMARY_TIMESTAMP_COL_NAME, pToken->n) == 0) {
436
    pIndex->columnIndex = PRIMARYKEY_TIMESTAMP_COL_ID; // just make runtime happy, need fix java test case InsertSpecialCharacterJniTest
437
  } else if (pToken->n == 0) {
438
    pIndex->columnIndex = PRIMARYKEY_TIMESTAMP_COL_ID; // just make runtime happy, need fix java test case InsertSpecialCharacterJniTest
439 440 441 442
  } else {
    // not specify the table name, try to locate the table index by column name
    if (pIndex->tableIndex == COLUMN_INDEX_INITIAL_VAL) {
      for (int16_t i = 0; i < pQueryInfo->numOfTables; ++i) {
443
        int16_t colIndex = doGetColumnIndex(pQueryInfo, i, pToken, &pIndex->type);
444 445 446

        if (colIndex != COLUMN_INDEX_INITIAL_VAL) {
          if (pIndex->columnIndex != COLUMN_INDEX_INITIAL_VAL) {
447
            return buildInvalidOperationMsg(pMsgBuf, msg0);
448 449 450 451 452 453 454
          } else {
            pIndex->tableIndex = i;
            pIndex->columnIndex = colIndex;
          }
        }
      }
    } else {  // table index is valid, get the column index
455
      pIndex->columnIndex = doGetColumnIndex(pQueryInfo, pIndex->tableIndex, pToken, &pIndex->type);
456 457 458
    }

    if (pIndex->columnIndex == COLUMN_INDEX_INITIAL_VAL) {
459
      return buildInvalidOperationMsg(pMsgBuf, msg1);
460 461 462 463 464 465 466 467 468 469
    }
  }

  if (VALID_COLUMN_INDEX(*pIndex)) {
    return TSDB_CODE_SUCCESS;
  } else {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }
}

470
int32_t getColumnIndexByName(const SToken* pToken, SQueryStmtInfo* pQueryInfo, SColumnIndex* pIndex, SMsgBuf* pMsgBuf) {
471 472 473 474 475 476 477 478 479
  if (pQueryInfo->pTableMetaInfo == NULL || pQueryInfo->numOfTables == 0) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

  SToken tmpToken = *pToken;
  if (getTableIndexByName(&tmpToken, pQueryInfo, pIndex) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

480
  return doGetColumnIndexByName(&tmpToken, pQueryInfo, pIndex, pMsgBuf);
481 482
}

483
int32_t validateGroupbyNode(SQueryStmtInfo* pQueryInfo, SArray* pList, SMsgBuf* pMsgBuf) {
484 485 486 487 488 489
  const char* msg1 = "too many columns in group by clause";
  const char* msg2 = "invalid column name in group by clause";
  const char* msg3 = "columns from one table allowed as group by columns";
  const char* msg4 = "join query does not support group by";
  const char* msg5 = "not allowed column type for group by";
  const char* msg6 = "tags not allowed for table query";
H
Haojun Liao 已提交
490
  const char* msg7 = "normal column and tags can not be mixed up in group by clause";
491 492
  const char* msg8 = "normal column can only locate at the end of group by clause";

H
Haojun Liao 已提交
493 494 495 496 497 498
  SGroupbyExpr* pGroupExpr = &(pQueryInfo->groupbyExpr);
  pGroupExpr->columnInfo = taosArrayInit(4, sizeof(SColIndex));
  if (pGroupExpr->columnInfo == NULL) {
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }

499 500 501 502 503 504 505
  // todo : handle two tables situation
  STableMetaInfo* pTableMetaInfo = NULL;
  if (pList == NULL) {
    return TSDB_CODE_SUCCESS;
  }

  if (pQueryInfo->numOfTables > 1) {
506
    return buildInvalidOperationMsg(pMsgBuf, msg4);
507 508
  }

509 510
  size_t num = taosArrayGetSize(pList);
  if (num > TSDB_MAX_TAGS) {
511
    return buildInvalidOperationMsg(pMsgBuf, msg1);
512 513
  }

514 515 516
  int32_t  numOfGroupbyCols = 0;
  SSchema *pSchema          = NULL;
  int32_t  tableIndex       = COLUMN_INDEX_INITIAL_VAL;
H
Haojun Liao 已提交
517
  bool groupbyTag           = false;
518 519

  for (int32_t i = 0; i < num; ++i) {
520 521
    SListItem * pItem = taosArrayGet(pList, i);
    SVariant* pVar = &pItem->pVar;
522 523

    SColumnIndex index = COLUMN_INDEX_INITIALIZER;
524
    SToken token = {pVar->nLen, pVar->nType, pVar->pz};
525 526
    if (getColumnIndexByName(&token, pQueryInfo, &index, pMsgBuf) != TSDB_CODE_SUCCESS) {
      return buildInvalidOperationMsg(pMsgBuf, msg2);
527 528
    }

529
    // Group by multiple tables is not supported.
530 531 532
    if (tableIndex == COLUMN_INDEX_INITIAL_VAL) {
      tableIndex = index.tableIndex;
    } else if (tableIndex != index.tableIndex) {
533
      return buildInvalidOperationMsg(pMsgBuf, msg3);
534 535 536 537 538 539 540 541
    }

    pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);
    STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;

    if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
      pSchema = getTbnameColumnSchema();
    } else {
542
      pSchema = getOneColumnSchema(pTableMeta, index.columnIndex);
543 544
    }

545
    bool groupTag = TSDB_COL_IS_TAG(index.type);
546 547
    if (groupTag) {
      if (!UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
548
        return buildInvalidOperationMsg(pMsgBuf, msg6);
549 550
      }

H
Haojun Liao 已提交
551 552
      groupbyTag = true;

553 554
      SColumn c = createColumn(pTableMeta->uid, pTableMetaInfo->aliasName, TSDB_COL_TAG, pSchema);
      taosArrayPush(pGroupExpr->columnInfo, &c);
555

556
      columnListInsert(pTableMetaInfo->tagColList, pTableMeta->uid, pSchema, TSDB_COL_TAG);
557 558
    } else {
      // check if the column type is valid, here only support the bool/tinyint/smallint/bigint group by
559
      if (pSchema->type == TSDB_DATA_TYPE_FLOAT || pSchema->type == TSDB_DATA_TYPE_DOUBLE) {
560
        return buildInvalidOperationMsg(pMsgBuf, msg5);
561 562
      }

563 564
      SColumn c = createColumn(pTableMeta->uid, pTableMetaInfo->aliasName, TSDB_COL_NORMAL, pSchema);
      taosArrayPush(pGroupExpr->columnInfo, &c);
565

566
      columnListInsert(pQueryInfo->colList, pTableMeta->uid, pSchema, TSDB_COL_NORMAL);
567 568 569

      numOfGroupbyCols++;
      pQueryInfo->info.groupbyColumn = true;
570 571 572
    }
  }

H
Haojun Liao 已提交
573
  if (numOfGroupbyCols > 0 && groupbyTag) {
574
    return buildInvalidOperationMsg(pMsgBuf, msg7);
575 576
  }

H
Haojun Liao 已提交
577 578
  // todo ???
  // 1. the normal column in the group by clause can only located at the end position
579 580 581
  for(int32_t i = 0; i < num; ++i) {
    SColIndex* pIndex = taosArrayGet(pGroupExpr->columnInfo, i);
    if (TSDB_COL_IS_NORMAL_COL(pIndex->flag) && i != num - 1) {
582
      return buildInvalidOperationMsg(pMsgBuf, msg8);
583 584 585
    }
  }

586
  pGroupExpr->groupbyTag = groupbyTag;
587 588 589
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
590 591
int32_t checkForUnsupportedQuery(SQueryStmtInfo* pQueryInfo, SMsgBuf* pMsgBuf) {
  const char* msg1 = "not support percentile/interp/block_dist in the outer query yet";
592

593
  for (int32_t i = 0; i < getNumOfExprs(pQueryInfo); ++i) {
594 595 596
    SExprInfo* pExpr = getExprInfo(pQueryInfo, i);
    assert(pExpr->pExpr->nodeType == TEXPR_UNARYEXPR_NODE);

H
Haojun Liao 已提交
597 598 599
    int32_t f = getExprFunctionId(pExpr);
    if (f == FUNCTION_PERCT || f == FUNCTION_INTERP) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
600 601
    }

H
Haojun Liao 已提交
602
    if (f == FUNCTION_BLKINFO && taosArrayGetSize(pQueryInfo->pDownstream) > 0) {
H
Haojun Liao 已提交
603
      return buildInvalidOperationMsg(pMsgBuf, msg1);
604 605
    }

H
Haojun Liao 已提交
606 607
#if 0
    //todo planner handle this
608 609
    if (/*(timeWindowQuery || pQueryInfo->stateWindow) &&*/ f == FUNCTION_LAST) {
      pExpr->base.numOfParams = 1;
610
      pExpr->base.param[0].i = TSDB_ORDER_ASC;
611 612
      pExpr->base.param[0].nType = TSDB_DATA_TYPE_INT;
    }
H
Haojun Liao 已提交
613
#endif
614 615 616 617 618 619 620
  }
}

int32_t validateWhereNode(SQueryStmtInfo *pQueryInfo, tSqlExpr* pWhereExpr, SMsgBuf* pMsgBuf) {
  return 0;
}

621 622 623 624 625 626
static int32_t parseIntervalOffset(SQueryStmtInfo* pQueryInfo, SToken* offsetToken, int32_t precision, SMsgBuf* pMsgBuf) {
  const char* msg1 = "interval offset cannot be negative";
  const char* msg2 = "interval offset should be shorter than interval";
  const char* msg3 = "cannot use 'year' as offset when interval is 'month'";

  SToken* t = offsetToken;
H
Haojun Liao 已提交
627 628
  SInterval* pInterval = &pQueryInfo->interval;

629
  if (t->n == 0) {
H
Haojun Liao 已提交
630 631
    pInterval->offsetUnit = pInterval->intervalUnit;
    pInterval->offset = 0;
632 633 634
    return TSDB_CODE_SUCCESS;
  }

H
Haojun Liao 已提交
635
  if (parseNatualDuration(t->z, t->n, &pInterval->offset, &pInterval->offsetUnit, precision) != TSDB_CODE_SUCCESS) {
636 637 638
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

H
Haojun Liao 已提交
639
  if (pInterval->offset < 0) {
640 641 642
    return buildInvalidOperationMsg(pMsgBuf, msg1);
  }

H
Haojun Liao 已提交
643 644 645
  if (!TIME_IS_VAR_DURATION(pInterval->offsetUnit)) {
    if (!TIME_IS_VAR_DURATION(pInterval->intervalUnit)) {
      if (pInterval->offset > pInterval->interval) {
646 647 648
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }
    }
H
Haojun Liao 已提交
649 650
  } else if (pInterval->offsetUnit == pInterval->intervalUnit) {
    if (pInterval->offset >= pInterval->interval) {
651 652
      return buildInvalidOperationMsg(pMsgBuf, msg2);
    }
H
Haojun Liao 已提交
653
  } else if (pInterval->intervalUnit == 'n' && pInterval->offsetUnit == 'y') {
654
    return buildInvalidOperationMsg(pMsgBuf, msg3);
H
Haojun Liao 已提交
655 656
  } else if (pInterval->intervalUnit == 'y' && pInterval->offsetUnit == 'n') {
    if (pInterval->interval * 12 <= pQueryInfo->interval.offset) {
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
      return buildInvalidOperationMsg(pMsgBuf, msg2);
    }
  } else {
    // TODO: offset should be shorter than interval, but how to check
    // conflicts like 30days offset and 1 month interval
  }

  return TSDB_CODE_SUCCESS;
}

static int32_t parseSlidingClause(SQueryStmtInfo* pQueryInfo, SToken* pSliding, int32_t precision, SMsgBuf* pMsgBuf) {
  const char* msg1 = "sliding value no larger than the interval value";
  const char* msg2 = "sliding value can not less than 1% of interval value";
  const char* msg3 = "does not support sliding when interval is natural month/year";
  const char* msg4 = "sliding value too small";

  const static int32_t INTERVAL_SLIDING_FACTOR = 100;

  SInterval* pInterval = &pQueryInfo->interval;
  if (pSliding->n == 0) {
    pInterval->slidingUnit = pInterval->intervalUnit;
    pInterval->sliding     = pInterval->interval;
    return TSDB_CODE_SUCCESS;
  }

  if (TIME_IS_VAR_DURATION(pInterval->intervalUnit)) {
    return buildInvalidOperationMsg(pMsgBuf, msg3);
  }

  parseAbsoluteDuration(pSliding->z, pSliding->n, &pInterval->sliding, &pInterval->slidingUnit, precision);

  // less than the threshold
  if (pInterval->sliding < convertTimePrecision(tsMinSlidingTime, TSDB_TIME_PRECISION_MILLI, precision)) {
    return buildInvalidOperationMsg(pMsgBuf, msg4);
  }

  if (pInterval->sliding > pInterval->interval) {
    return buildInvalidOperationMsg(pMsgBuf, msg1);
  }

  if ((pInterval->interval != 0) && (pInterval->interval/pInterval->sliding > INTERVAL_SLIDING_FACTOR)) {
    return buildInvalidOperationMsg(pMsgBuf, msg2);
  }

  return TSDB_CODE_SUCCESS;
}

704 705
static void setTsOutputExprInfo(SQueryStmtInfo* pQueryInfo, STableMetaInfo* pTableMetaInfo, int32_t outputIndex, int32_t tableIndex);

706 707
// validate the interval info
int32_t validateIntervalNode(SQueryStmtInfo *pQueryInfo, SSqlNode* pSqlNode, SMsgBuf* pMsgBuf) {
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 747 748 749 750
  const char* msg1 = "sliding cannot be used without interval";
  const char* msg2 = "only point interpolation query requires keyword EVERY";
  const char* msg3 = "interval value is too small";

  STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, 0);
  STableComInfo tinfo = getTableInfo(pTableMetaInfo->pTableMeta);

  if (!TPARSER_HAS_TOKEN(pSqlNode->interval.interval)) {
    if (TPARSER_HAS_TOKEN(pSqlNode->sliding)) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    } else {
      return TSDB_CODE_SUCCESS;
    }
  }

  // interval is not null
  SToken *t = &pSqlNode->interval.interval;
  if (parseNatualDuration(t->z, t->n, &pQueryInfo->interval.interval,
                          &pQueryInfo->interval.intervalUnit, tinfo.precision) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

  if (pQueryInfo->interval.interval <= 0) {
    return buildInvalidOperationMsg(pMsgBuf, msg3);
  }

  if (!TIME_IS_VAR_DURATION(pQueryInfo->interval.intervalUnit)) {
    // interval cannot be less than 10 milliseconds
    if (convertTimePrecision(pQueryInfo->interval.interval, tinfo.precision, TSDB_TIME_PRECISION_MICRO) < tsMinIntervalTime) {
      char msg[50] = {0};
      snprintf(msg, 50, "interval time window can not be less than %d %s", tsMinIntervalTime, TSDB_TIME_PRECISION_MICRO_STR);
      return buildInvalidOperationMsg(pMsgBuf, msg);
    }
  }

  if (parseIntervalOffset(pQueryInfo, &pSqlNode->interval.offset, tinfo.precision, pMsgBuf) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

  if (parseSlidingClause(pQueryInfo, &pSqlNode->sliding, tinfo.precision, pMsgBuf) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

751 752 753 754 755 756 757
  if (tsCompatibleModel) {
    SExprInfo* pFirstExpr = getExprInfo(pQueryInfo, 0);
    if (pFirstExpr->pExpr->nodeType != TEXPR_FUNCTION_NODE || strcasecmp(pFirstExpr->pExpr->_function.functionName, "dummy") != 0) {
      setTsOutputExprInfo(pQueryInfo, pTableMetaInfo, 0, 0);
    }
  }

758 759 760
  // It is a time window query
  pQueryInfo->info.timewindow = true;
  return TSDB_CODE_SUCCESS;
761 762
}

763 764 765 766 767
int32_t validateSessionNode(SQueryStmtInfo *pQueryInfo, SSessionWindowVal* pSession, int32_t precision, SMsgBuf* pMsgBuf) {
  const char* msg1 = "gap should be fixed time window";
  const char* msg2 = "only one type time window allowed";
  const char* msg3 = "invalid column name";
  const char* msg4 = "invalid time window";
768
  const char* msg5 = "only the primary time stamp column can be used in session window";
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800

  // no session window
  if (!TPARSER_HAS_TOKEN(pSession->gap)) {
    return TSDB_CODE_SUCCESS;
  }

  SToken* col = &pSession->col;
  SToken* gap = &pSession->gap;

  char timeUnit = 0;
  if (parseNatualDuration(gap->z, gap->n, &pQueryInfo->sessionWindow.gap, &timeUnit, precision) != TSDB_CODE_SUCCESS) {
    return buildInvalidOperationMsg(pMsgBuf, msg4);
  }

  if (TIME_IS_VAR_DURATION(timeUnit)) {
    return buildInvalidOperationMsg(pMsgBuf, msg1);
  }

  if (pQueryInfo->sessionWindow.gap != 0 && pQueryInfo->interval.interval != 0) {
    return buildInvalidOperationMsg(pMsgBuf, msg2);
  }

  if (pQueryInfo->sessionWindow.gap == 0) {
    return buildInvalidOperationMsg(pMsgBuf, msg4);
  }

  SColumnIndex index = COLUMN_INDEX_INITIALIZER;
  if ((getColumnIndexByName(col, pQueryInfo, &index, pMsgBuf) != TSDB_CODE_SUCCESS)) {
    return buildInvalidOperationMsg(pMsgBuf, msg3);
  }

  if (index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_ID) {
801
    return buildInvalidOperationMsg(pMsgBuf, msg5);
802 803
  }

804 805 806 807 808
  STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);
  STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;

  SSchema* pSchema = getOneColumnSchema(pTableMeta, index.columnIndex);
  pQueryInfo->sessionWindow.col = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, index.type, pSchema);
809
  pQueryInfo->info.sessionWindow = true;
810
  return TSDB_CODE_SUCCESS;
811 812 813
}

// parse the window_state
814 815
int32_t validateStateWindowNode(SQueryStmtInfo *pQueryInfo, SWindowStateVal* pWindowState, SMsgBuf* pMsgBuf) {
  const char* msg1 = "invalid column name";
816 817
  const char* msg2 = "invalid column type to create state window";
  const char* msg3 = "not support state_window with group by";
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
  const char* msg4 = "function not support for super table query";
  const char* msg5 = "not support state_window on tag column";

  SToken *col = &(pWindowState->col) ;
  if (!TPARSER_HAS_TOKEN(*col)) {
    return TSDB_CODE_SUCCESS;
  }

  SGroupbyExpr* pGroupExpr = &pQueryInfo->groupbyExpr;
  if (taosArrayGetSize(pGroupExpr->columnInfo) > 0) {
    return buildInvalidOperationMsg(pMsgBuf, msg3);
  }

  SColumnIndex index = COLUMN_INDEX_INITIALIZER;
  if (getColumnIndexByName(col, pQueryInfo, &index, pMsgBuf) !=  TSDB_CODE_SUCCESS) {
    return buildInvalidOperationMsg(pMsgBuf, msg1);
  }

  STableMetaInfo *pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);
  STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;

  if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
    return buildInvalidOperationMsg(pMsgBuf, msg4);
  }

  if (TSDB_COL_IS_TAG(index.type)) {
    return buildInvalidOperationMsg(pMsgBuf, msg5);
  }

  SSchema* pSchema = getOneColumnSchema(pTableMeta, index.columnIndex);
  if (pSchema->type == TSDB_DATA_TYPE_TIMESTAMP || IS_FLOAT_TYPE(pSchema->type)) {
    return buildInvalidOperationMsg(pMsgBuf, msg2);
  }

852
  pQueryInfo->stateWindow.col = createColumn(pTableMeta->uid, pTableMetaInfo->aliasName, index.type, pSchema);
853 854
  pQueryInfo->info.stateWindow = true;

855
  columnListInsert(pQueryInfo->colList, pTableMeta->uid, pSchema, index.type);
856
  return TSDB_CODE_SUCCESS;
857 858 859 860 861 862 863 864
}

// parse the having clause in the first place
int32_t validateHavingNode(SQueryStmtInfo *pQueryInfo, SSqlNode* pSqlNode, SMsgBuf* pMsgBuf) {
  return 0;
}

int32_t validateLimitNode(SQueryStmtInfo *pQueryInfo, SSqlNode* pSqlNode, SMsgBuf* pMsgBuf) {
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
  STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, 0);

  const char* msg1 = "slimit/soffset only available for STable query";
  const char* msg2 = "slimit/soffset can not apply to projection query";
  const char* msg3 = "soffset/offset can not be less than 0";

  // handle the limit offset value, validate the limit
  pQueryInfo->limit = pSqlNode->limit;
  pQueryInfo->slimit = pSqlNode->slimit;

//  tscDebug("0x%"PRIx64" limit:%" PRId64 ", offset:%" PRId64 " slimit:%" PRId64 ", soffset:%" PRId64, pSql->self,
//           pQueryInfo->limit.limit, pQueryInfo->limit.offset, pQueryInfo->slimit.limit, pQueryInfo->slimit.offset);

  if (pQueryInfo->slimit.offset < 0 || pQueryInfo->limit.offset < 0) {
    return buildInvalidOperationMsg(pMsgBuf, msg3);
  }

  if (pQueryInfo->limit.limit == 0) {
//    tscDebug("0x%"PRIx64" limit 0, no output result", pSql->self);
    pQueryInfo->command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
    return TSDB_CODE_SUCCESS;
  }

  if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
//    if (!tscQueryTags(pQueryInfo)) {  // local handle the super table tag query
//      if (tscIsProjectionQueryOnSTable(pQueryInfo, 0)) {
//        if (pQueryInfo->slimit.limit > 0 || pQueryInfo->slimit.offset > 0) {
//          return buildInvalidOperationMsg(pMsgBuf, msg2);
//        }
//
//        // for projection query on super table, all queries are subqueries
//        if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) &&
//            !TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_QUERY)) {
//          pQueryInfo->type |= TSDB_QUERY_TYPE_SUBQUERY;
//        }
//      }
//    }

    if (pQueryInfo->slimit.limit == 0) {
//      tscDebug("0x%"PRIx64" slimit 0, no output result", pSql->self);
      pQueryInfo->command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
      return TSDB_CODE_SUCCESS;
    }
    
    // No tables included. No results generated. Query results are empty.
    if (pTableMetaInfo->vgroupList->numOfVgroups == 0) {
//      tscDebug("0x%"PRIx64" no table in super table, no output result", pSql->self);
      pQueryInfo->command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
      return TSDB_CODE_SUCCESS;
    }
  } else {
    if (pQueryInfo->slimit.limit != -1 || pQueryInfo->slimit.offset != 0) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }
  }
920 921 922
}

int32_t validateOrderbyNode(SQueryStmtInfo *pQueryInfo, SSqlNode* pSqlNode, SMsgBuf* pMsgBuf) {
923 924 925 926 927 928 929 930 931
  const char* msg1 = "invalid column name in orderby clause";
  const char* msg2 = "too many order by columns";
  const char* msg3 = "only one column allowed in orderby";
  const char* msg4 = "invalid order by column index";

  if (pSqlNode->pSortOrder == NULL) {
    return TSDB_CODE_SUCCESS;
  }

932 933
  pQueryInfo->order = taosArrayInit(4, sizeof(SOrder));

934 935 936 937 938 939 940 941 942 943
  STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, 0);
  SArray* pSortOrder = pSqlNode->pSortOrder;

  /*
   * for table query, there is only one or none order option is allowed, which is the
   * ts or values(top/bottom) order is supported.
   *
   * for super table query, the order option must be less than 3.
   */
  size_t size = taosArrayGetSize(pSortOrder);
944
  if ((UTIL_TABLE_IS_NORMAL_TABLE(pTableMetaInfo) || UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) && (pQueryInfo->info.projectionQuery)) {
945 946 947 948 949 950
    if (size > 1) {
      return buildInvalidOperationMsg(pMsgBuf, msg3);
    }
  }

  // handle the first part of order by
951
  bool found = false;
952
  for(int32_t i = 0; i < taosArrayGetSize(pSortOrder); ++i) {
953 954 955
    SListItem* pItem = taosArrayGet(pSortOrder, i);

    SVariant* pVar = &pItem->pVar;
956
    if (pVar->nType == TSDB_DATA_TYPE_BINARY) {
957
      SOrder order = {0};
958 959 960 961 962 963

      // find the orde column among the result field.
      for (int32_t j = 0; j < getNumOfFields(&pQueryInfo->fieldsInfo); ++j) {
        SInternalField* pInfo = taosArrayGet(pQueryInfo->fieldsInfo.internalField, j);
        SSchema* pSchema = &pInfo->pExpr->base.resSchema;
        if (strcasecmp(pVar->pz, pSchema->name) == 0) {
964 965 966 967 968 969
          setColumn(&order.col, pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, TSDB_COL_TMP, pSchema);

          order.order = pItem->sortOrder;
          taosArrayPush(pQueryInfo->order, &order);
          found = true;
          break;
970 971
        }
      }
972

973 974 975 976
      if (!found) {
        return buildInvalidOperationMsg(pMsgBuf, "invalid order by column");
      }

977 978 979 980
    } else {  // order by [1|2|3]
      if (pVar->i > getNumOfFields(&pQueryInfo->fieldsInfo)) {
        return buildInvalidOperationMsg(pMsgBuf, msg4);
      }
981

982 983
      int32_t    index = pVar->i - 1;
      SExprInfo* pExprInfo = getExprInfo(pQueryInfo, index);
984

985 986
      SOrder c = {0};
      setColumn(&c.col, pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, TSDB_COL_TMP, &pExprInfo->base.resSchema);
987
      c.order = pItem->sortOrder;
988 989 990
      taosArrayPush(pQueryInfo->order, &c);
    }
  }
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121

  return TSDB_CODE_SUCCESS;
}

#if 0
// set order by info
int32_t checkForInvalidOrderby(SQueryStmtInfo *pQueryInfo, SSqlNode* pSqlNode, SMsgBuf* pMsgBuf) {
  const char* msg0 = "only one column allowed in orderby";
  const char* msg1 = "invalid column name in orderby clause";
  const char* msg2 = "too many order by columns";
  const char* msg3 = "only primary timestamp/tbname/first tag in groupby clause allowed";
  const char* msg4 = "only tag in groupby clause allowed in order clause";
  const char* msg5 = "only primary timestamp/column in top/bottom function allowed as order column";
  const char* msg6 = "only primary timestamp allowed as the second order column";
  const char* msg7 = "only primary timestamp/column in groupby clause allowed as order column";
  const char* msg8 = "only column in groupby clause allowed as order column";
  const char* msg9 = "orderby column must projected in subquery";
  const char* msg10 = "not support distinct mixed with order by";

//  setDefaultOrderInfo(pQueryInfo);
  STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, 0);
  SSchema* pSchema = getTableColumnSchema(pTableMetaInfo->pTableMeta);
  int32_t numOfCols = getNumOfColumns(pTableMetaInfo->pTableMeta);

  if (pSqlNode->pSortOrder == NULL) {
    return TSDB_CODE_SUCCESS;
  }

  SArray* pSortOrder = pSqlNode->pSortOrder;

  /*
   * for table query, there is only one or none order option is allowed, which is the
   * ts or values(top/bottom) order is supported.
   *
   * for super table query, the order option must be less than 3.
   */
  size_t size = taosArrayGetSize(pSortOrder);
  if (UTIL_TABLE_IS_NORMAL_TABLE(pTableMetaInfo) || UTIL_TABLE_IS_TMP_TABLE(pTableMetaInfo)) {
    if (size > 1) {
      return buildInvalidOperationMsg(pMsgBuf, msg0);
    }
  } else {
    if (size > 2) {
      return buildInvalidOperationMsg(pMsgBuf, msg2);
    }
  }

#if 0
  if (size > 0 && pQueryInfo->distinct) {
    return buildInvalidOperationMsg(pMsgBuf, msg10);
  }
#endif

  // handle the first part of order by
  SVariant* pVar = taosArrayGet(pSortOrder, 0);

#if 0
  // e.g., order by 1 asc, return directly with out further check.
  if (pVar->nType >= TSDB_DATA_TYPE_TINYINT && pVar->nType <= TSDB_DATA_TYPE_BIGINT) {
    return TSDB_CODE_SUCCESS;
  }
#endif

  SToken columnName = {pVar->nLen, pVar->nType, pVar->pz};

  SColumnIndex index = COLUMN_INDEX_INITIALIZER;
  if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {  // super table query
    if (getColumnIndexByName(&columnName, pQueryInfo, &index, pMsgBuf) != TSDB_CODE_SUCCESS) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }

    bool orderByTags = false;
    bool orderByTS = false;
    bool orderByGroupbyCol = false;

    if (TSDB_COL_IS_TAG(index.type) && index.columnIndex != TSDB_TBNAME_COLUMN_INDEX) {
      // it is a tag column
      if (pQueryInfo->groupbyExpr.columnInfo == NULL) {
        return buildInvalidOperationMsg(pMsgBuf, msg4);
      }

      int32_t relTagIndex = index.columnIndex - numOfCols;
      SColIndex* pColIndex = taosArrayGet(pQueryInfo->groupbyExpr.columnInfo, 0);
      if (relTagIndex == pColIndex->colIndex) {
        orderByTags = true;
      }
    } else if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
      orderByTags = true;
    }

    if (PRIMARYKEY_TIMESTAMP_COL_ID == index.columnIndex) {
      orderByTS = true;
    }

    SArray *columnInfo = pQueryInfo->groupbyExpr.columnInfo;
    if (columnInfo != NULL && taosArrayGetSize(columnInfo) > 0) {
      SColIndex* pColIndex = taosArrayGet(columnInfo, 0);
      if (PRIMARYKEY_TIMESTAMP_COL_ID != index.columnIndex && pColIndex->colIndex == index.columnIndex) {
        orderByGroupbyCol = true;
      }
    }

    if (!(orderByTags || orderByTS || orderByGroupbyCol) /*&& !isTopBottomQuery(pQueryInfo)*/) {
      return buildInvalidOperationMsg(pMsgBuf, msg3);
    } else {  // order by top/bottom result value column is not supported in case of interval query.
      assert(!(orderByTags && orderByTS && orderByGroupbyCol));
    }

    size_t s = taosArrayGetSize(pSortOrder);
    if (s == 1) {
      if (orderByTags) {
        pQueryInfo->groupbyExpr.orderIndex = index.columnIndex - numOfCols;

        SListItem* p1 = taosArrayGet(pSqlNode->pSortOrder, 0);
        pQueryInfo->groupbyExpr.orderType = p1->sortOrder;
      } else if (orderByGroupbyCol) {
        SListItem* p1 = taosArrayGet(pSqlNode->pSortOrder, 0);

        pQueryInfo->groupbyExpr.orderType = p1->sortOrder;
        pQueryInfo->order.orderColId = pSchema[index.columnIndex].colId;
      } else if (isTopBottomQuery(pQueryInfo)) {
        /* order of top/bottom query in interval is not valid  */
        int32_t pos = tscExprTopBottomIndex(pQueryInfo);
        assert(pos > 0);
        
        SExprInfo* pExpr = getExprInfo(pQueryInfo, pos - 1);
//        assert(getExprFunctionId(pExpr) == FUNCTION_TS);

        pExpr = getExprInfo(pQueryInfo, pos);

        // other tag are not allowed
1122
        if (pExpr->base.pColumns->colIndex != index.columnIndex && index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_ID) {
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
          return buildInvalidOperationMsg(pMsgBuf, msg5);
        }

        SListItem* p1 = taosArrayGet(pSqlNode->pSortOrder, 0);
        pQueryInfo->order.order = p1->sortOrder;
        pQueryInfo->order.orderColId = pSchema[index.columnIndex].colId;
        return TSDB_CODE_SUCCESS;
      } else {
        SListItem* p1 = taosArrayGet(pSqlNode->pSortOrder, 0);

        pQueryInfo->order.order = p1->sortOrder;
        pQueryInfo->order.orderColId = PRIMARYKEY_TIMESTAMP_COL_ID;

        // orderby ts query on super table
        if (tscOrderedProjectionQueryOnSTable(pQueryInfo, 0)) {
          bool found = false;
1139
          for (int32_t i = 0; i < getNumOfExprs(pQueryInfo); ++i) {
1140
            SExprInfo* pExpr = getExprInfo(pQueryInfo, i);
1141
            if (getExprFunctionId(pExpr) == FUNCTION_PRJ && pExpr->base.pColumns->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
              found = true;
              break;
            }
          }

          if (!found && pQueryInfo->pDownstream) {
            return buildInvalidOperationMsg(pMsgBuf, msg9);
          }

          // this is a invisible output column, in order to used to sort the result.
          setTsOutputExprInfo(pQueryInfo, pTableMetaInfo, 0, index.tableIndex);
        }
      }
    } else {
      SListItem *pItem = taosArrayGet(pSqlNode->pSortOrder, 0);
      if (orderByTags) {
        pQueryInfo->groupbyExpr.orderIndex = index.columnIndex - numOfCols;
        pQueryInfo->groupbyExpr.orderType = pItem->sortOrder;
      } else if (orderByGroupbyCol) {
        pQueryInfo->order.order = pItem->sortOrder;
        pQueryInfo->order.orderColId = index.columnIndex;
      } else {
        pQueryInfo->order.order = pItem->sortOrder;
        pQueryInfo->order.orderColId = PRIMARYKEY_TIMESTAMP_COL_ID;
      }

      pItem = taosArrayGet(pSqlNode->pSortOrder, 1);
      SVariant* pVar2 = &pItem->pVar;
      SToken cname = {pVar2->nLen, pVar2->nType, pVar2->pz};
      if (getColumnIndexByName(&cname, pQueryInfo, &index, pMsgBuf) != TSDB_CODE_SUCCESS) {
        return buildInvalidOperationMsg(pMsgBuf, msg1);
      }

      if (index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_ID) {
        return buildInvalidOperationMsg(pMsgBuf, msg6);
      } else {
        SListItem* p1 = taosArrayGet(pSortOrder, 1);
        pQueryInfo->order.order = p1->sortOrder;
        pQueryInfo->order.orderColId = PRIMARYKEY_TIMESTAMP_COL_ID;
      }
    }

  } else if (UTIL_TABLE_IS_NORMAL_TABLE(pTableMetaInfo) || UTIL_TABLE_IS_CHILD_TABLE(pTableMetaInfo)) { // check order by clause for normal table & temp table
    if (getColumnIndexByName(&columnName, pQueryInfo, &index, pMsgBuf) != TSDB_CODE_SUCCESS) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }

    if (index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_ID && !isTopBottomQuery(pQueryInfo)) {
      bool validOrder = false;
      SArray *columnInfo = pQueryInfo->groupbyExpr.columnInfo;
      if (columnInfo != NULL && taosArrayGetSize(columnInfo) > 0) {
        SColIndex* pColIndex = taosArrayGet(columnInfo, 0);
        validOrder = (pColIndex->colIndex == index.columnIndex);
      }

      if (!validOrder) {
        return buildInvalidOperationMsg(pMsgBuf, msg7);
      }

      SListItem* p1 = taosArrayGet(pSqlNode->pSortOrder, 0);
      pQueryInfo->groupbyExpr.orderIndex = pSchema[index.columnIndex].colId;
      pQueryInfo->groupbyExpr.orderType = p1->sortOrder;
    }

    if (isTopBottomQuery(pQueryInfo)) {
      SArray *columnInfo = pQueryInfo->groupbyExpr.columnInfo;
      if (columnInfo != NULL && taosArrayGetSize(columnInfo) > 0) {
        SColIndex* pColIndex = taosArrayGet(columnInfo, 0);

        if (pColIndex->colIndex == index.columnIndex) {
          return buildInvalidOperationMsg(pMsgBuf, msg8);
        }
      } else {
        int32_t pos = tscExprTopBottomIndex(pQueryInfo);
        assert(pos > 0);
        SExprInfo* pExpr = getExprInfo(pQueryInfo, pos - 1);
        assert(getExprFunctionId(pExpr) == FUNCTION_TS);

        pExpr = getExprInfo(pQueryInfo, pos);

1222
        if (pExpr->base.pColumns->colIndex != index.columnIndex && index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_ID) {
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
          return buildInvalidOperationMsg(pMsgBuf, msg5);
        }
      }

      SListItem* pItem = taosArrayGet(pSqlNode->pSortOrder, 0);
      pQueryInfo->order.order = pItem->sortOrder;

      pQueryInfo->order.orderColId = pSchema[index.columnIndex].colId;
      return TSDB_CODE_SUCCESS;
    }

    SListItem* pItem = taosArrayGet(pSqlNode->pSortOrder, 0);
    pQueryInfo->order.order = pItem->sortOrder;
    pQueryInfo->order.orderColId = pSchema[index.columnIndex].colId;
  } else {
    // handle the temp table order by clause. You can order by any single column in case of the temp table, created by
    // inner subquery.
    assert(UTIL_TABLE_IS_TMP_TABLE(pTableMetaInfo) && taosArrayGetSize(pSqlNode->pSortOrder) == 1);

    if (getColumnIndexByName(&columnName, pQueryInfo, &index, pMsgBuf) != TSDB_CODE_SUCCESS) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }

    SListItem* pItem = taosArrayGet(pSqlNode->pSortOrder, 0);
    pQueryInfo->order.order = pItem->sortOrder;
    pQueryInfo->order.orderColId = pSchema[index.columnIndex].colId;
  }

  return TSDB_CODE_SUCCESS;
}
#endif

H
Haojun Liao 已提交
1255
static int32_t checkFillQueryRange(SQueryStmtInfo* pQueryInfo, SMsgBuf* pMsgBuf) {
1256
  const char* msg1 = "start(end) time of time range required or time range too large";
1257 1258 1259 1260 1261

  if (pQueryInfo->interval.interval == 0) {
    return TSDB_CODE_SUCCESS;
  }

1262 1263 1264 1265 1266
  // TODO disable this check temporarily
//  bool initialWindows = TSWINDOW_IS_EQUAL(pQueryInfo->window, TSWINDOW_INITIALIZER);
//  if (initialWindows) {
//    return buildInvalidOperationMsg(pMsgBuf, msg1);
//  }
1267 1268 1269 1270 1271 1272 1273 1274 1275

  int64_t timeRange = ABS(pQueryInfo->window.skey - pQueryInfo->window.ekey);

  int64_t intervalRange = 0;
  if (!TIME_IS_VAR_DURATION(pQueryInfo->interval.intervalUnit)) {
    intervalRange = pQueryInfo->interval.interval;

    // number of result is not greater than 10,000,000
    if ((timeRange == 0) || (timeRange / intervalRange) >= MAX_INTERVAL_TIME_WINDOW) {
1276
      return buildInvalidOperationMsg(pMsgBuf, msg1);
1277 1278 1279 1280
    }
  }

  return TSDB_CODE_SUCCESS;
1281 1282 1283
}

int32_t validateFillNode(SQueryStmtInfo *pQueryInfo, SSqlNode* pSqlNode, SMsgBuf* pMsgBuf) {
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
  SArray* pFillToken = pSqlNode->fillType;
  if (pSqlNode->fillType == NULL) {
    return TSDB_CODE_SUCCESS;
  }

  SListItem* pItem = taosArrayGet(pFillToken, 0);

  const int32_t START_INTERPO_COL_IDX = 1;

  const char* msg1 = "value is expected";
  const char* msg2 = "invalid fill option";
  const char* msg4 = "illegal value or data overflow";
  const char* msg6 = "not supported function now";

  /*
   * fill options are set at the end position, when all columns are set properly
   * the columns may be increased due to group by operation
   */
H
Haojun Liao 已提交
1302
  if (checkFillQueryRange(pQueryInfo, pMsgBuf) != TSDB_CODE_SUCCESS) {
1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }


  if (pItem->pVar.nType != TSDB_DATA_TYPE_BINARY) {
    return buildInvalidOperationMsg(pMsgBuf, msg2);
  }

  int32_t numOfFields = (int32_t) getNumOfFields(&pQueryInfo->fieldsInfo);

  pQueryInfo->fillVal = calloc(numOfFields, sizeof(int64_t));
  if (pQueryInfo->fillVal == NULL) {
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }

  pQueryInfo->numOfFillVal = (int32_t)numOfFields;
  if (strncasecmp(pItem->pVar.pz, "none", 4) == 0 && pItem->pVar.nLen == 4) {
    pQueryInfo->fillType = TSDB_FILL_NONE;
  } else if (strncasecmp(pItem->pVar.pz, "null", 4) == 0 && pItem->pVar.nLen == 4) {
    pQueryInfo->fillType = TSDB_FILL_NULL;
    for (int32_t i = START_INTERPO_COL_IDX; i < numOfFields; ++i) {
      TAOS_FIELD* pField = &getInternalField(&pQueryInfo->fieldsInfo, i)->field;
      setNull((char*)&pQueryInfo->fillVal[i], pField->type, pField->bytes);
    }
  } else if (strncasecmp(pItem->pVar.pz, "prev", 4) == 0 && pItem->pVar.nLen == 4) {
    pQueryInfo->fillType = TSDB_FILL_PREV;
//    if (pQueryInfo->info.interpQuery && pQueryInfo->order.order == TSDB_ORDER_DESC) {
//      return buildInvalidOperationMsg(pMsgBuf, msg6);
//    }
  } else if (strncasecmp(pItem->pVar.pz, "next", 4) == 0 && pItem->pVar.nLen == 4) {
    pQueryInfo->fillType = TSDB_FILL_NEXT;
  } else if (strncasecmp(pItem->pVar.pz, "linear", 6) == 0 && pItem->pVar.nLen == 6) {
    pQueryInfo->fillType = TSDB_FILL_LINEAR;
  } else if (strncasecmp(pItem->pVar.pz, "value", 5) == 0 && pItem->pVar.nLen == 5) {
    pQueryInfo->fillType = TSDB_FILL_SET_VALUE;

    size_t num = taosArrayGetSize(pFillToken);
    if (num == 1) {  // no actual value, return with error code
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }

    int32_t startPos = 1;
    int32_t numOfFillVal = (int32_t)(num - 1);

    // for point interpolation query, we do not have the timestamp column
    if (pQueryInfo->info.interpQuery) {
      startPos = 0;
      if (numOfFillVal > numOfFields) {
        numOfFillVal = numOfFields;
      }
    } else {
      numOfFillVal = MIN(num, numOfFields);
    }

    int32_t j = 1;

    for (int32_t i = startPos; i < numOfFillVal; ++i, ++j) {
      TAOS_FIELD* pField = &getInternalField(&pQueryInfo->fieldsInfo, i)->field;
      if (pField->type == TSDB_DATA_TYPE_BINARY || pField->type == TSDB_DATA_TYPE_NCHAR) {
        setVardataNull((char*) &pQueryInfo->fillVal[i], pField->type);
        continue;
      }

      SVariant* p = taosArrayGet(pFillToken, j);
      int32_t ret = taosVariantDump(p, (char*)&pQueryInfo->fillVal[i], pField->type, true);
      if (ret != TSDB_CODE_SUCCESS) {
        return buildInvalidOperationMsg(pMsgBuf, msg4);
      }
    }

    if ((num < numOfFields) || ((num - 1 < numOfFields) && (pQueryInfo->info.interpQuery))) {
      SListItem* lastItem = taosArrayGetLast(pFillToken);

      for (int32_t i = numOfFillVal; i < numOfFields; ++i) {
        TAOS_FIELD* pField = &getInternalField(&pQueryInfo->fieldsInfo, i)->field;

        if (pField->type == TSDB_DATA_TYPE_BINARY || pField->type == TSDB_DATA_TYPE_NCHAR) {
          setVardataNull((char*) &pQueryInfo->fillVal[i], pField->type);
        } else {
          taosVariantDump(&lastItem->pVar, (char*)&pQueryInfo->fillVal[i], pField->type, true);
        }
      }
    }
  } else {
    return buildInvalidOperationMsg(pMsgBuf, msg2);
  }

  return TSDB_CODE_SUCCESS;
1391 1392
}

1393 1394
static void pushDownAggFuncExprInfo(SQueryStmtInfo* pQueryInfo);
static void addColumnNodeFromLowerLevel(SQueryStmtInfo* pQueryInfo);
1395

1396
int32_t validateSqlNode(SSqlNode* pSqlNode, SQueryStmtInfo* pQueryInfo, SMsgBuf* pMsgBuf) {
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
  assert(pSqlNode != NULL && (pSqlNode->from == NULL || taosArrayGetSize(pSqlNode->from->list) > 0));

  const char* msg1 = "point interpolation query needs timestamp";
  const char* msg2 = "too many tables in from clause";
  const char* msg3 = "start(end) time of query range required or time range too large";
  const char* msg4 = "interval query not supported, since the result of sub query not include valid timestamp column";
  const char* msg5 = "only tag query not compatible with normal column filter";
  const char* msg7 = "derivative/twa/irate requires timestamp column exists in subquery";
  const char* msg8 = "condition missing for join query";

  int32_t  code = TSDB_CODE_SUCCESS;

  /*
   * handle the sql expression without from subclause
   * select server_status();
   * select server_version();
   * select client_version();
   * select database();
H
Haojun Liao 已提交
1415 1416
   * select 1+2;
   * select now();
1417 1418 1419 1420
   */
  if (pSqlNode->from == NULL) {
    assert(pSqlNode->fillType == NULL && pSqlNode->pGroupby == NULL && pSqlNode->pWhere == NULL &&
           pSqlNode->pSortOrder == NULL);
1421 1422
    assert(0);
//    return doLocalQueryProcess(pCmd, pQueryInfo, pSqlNode);
1423 1424
  }

1425
  if (pSqlNode->from->type == SQL_FROM_NODE_SUBQUERY) {
1426 1427 1428 1429 1430
    pQueryInfo->numOfTables = 0;

    // parse the subquery in the first place
    int32_t numOfSub = (int32_t)taosArrayGetSize(pSqlNode->from->list);
    for (int32_t i = 0; i < numOfSub; ++i) {
1431
      SRelElement* subInfo = taosArrayGet(pSqlNode->from->list, i);
1432
      code = doValidateSubquery(pSqlNode, i, pQueryInfo, pMsgBuf);
1433 1434 1435 1436 1437 1438
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
    }

    // parse the group by clause in the first place
1439
    if (validateGroupbyNode(pQueryInfo, pSqlNode->pGroupby, pMsgBuf) != TSDB_CODE_SUCCESS) {
1440 1441 1442
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

1443
    if (validateSelectNodeList(pQueryInfo, pSqlNode->pSelNodeList, true, pMsgBuf) != TSDB_CODE_SUCCESS) {
1444 1445 1446
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

H
Haojun Liao 已提交
1447
    code = checkForUnsupportedQuery(pQueryInfo, pMsgBuf);
1448

1449
    STableMeta* pTableMeta = getMetaInfo(pQueryInfo, 0)->pTableMeta;
1450
    SSchema*    pSchema = getOneColumnSchema(pTableMeta, 0);
1451
    int32_t precision = pTableMeta->tableInfo.precision;
1452

H
Haojun Liao 已提交
1453
#if 0
1454
    if (pSchema->type != TSDB_DATA_TYPE_TIMESTAMP) {
1455
      int32_t numOfExprs = (int32_t)getNumOfExprs(pQueryInfo);
1456 1457

      for (int32_t i = 0; i < numOfExprs; ++i) {
1458
        SExprInfo* pExpr = getExprInfo(pQueryInfo, i);
1459

1460 1461 1462
        int32_t f = pExpr->pExpr->_node.functionId;
        if (f == FUNCTION_DERIVATIVE || f == FUNCTION_TWA || f == FUNCTION_IRATE) {
          return buildInvalidOperationMsg(pMsgBuf, msg7);
1463 1464 1465
        }
      }
    }
H
Haojun Liao 已提交
1466
#endif
1467 1468 1469

    // validate the query filter condition info
    if (pSqlNode->pWhere != NULL) {
1470
      if (validateWhereNode(pQueryInfo, pSqlNode->pWhere, pMsgBuf) != TSDB_CODE_SUCCESS) {
1471 1472 1473 1474
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }
    } else {
      if (pQueryInfo->numOfTables > 1) {
1475
        return buildInvalidOperationMsg(pMsgBuf, msg8);
1476 1477 1478 1479
      }
    }

    // validate the interval info
1480
    if (validateIntervalNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1481 1482
      return TSDB_CODE_TSC_INVALID_OPERATION;
    } else {
1483
      if (validateSessionNode(pQueryInfo, &pSqlNode->sessionVal, precision, pMsgBuf) != TSDB_CODE_SUCCESS) {
1484 1485 1486 1487
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }

      // parse the window_state
1488
      if (validateStateWindowNode(pQueryInfo, &pSqlNode->windowstateVal, pMsgBuf) != TSDB_CODE_SUCCESS) {
1489 1490 1491 1492 1493 1494
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }
    }

    // parse the having clause in the first place
    int32_t joinQuery = (pSqlNode->from != NULL && taosArrayGetSize(pSqlNode->from->list) > 1);
1495
    if (validateHavingNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1496 1497 1498
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

1499
    if ((code = validateLimitNode(pQueryInfo, pSqlNode, pMsgBuf)) != TSDB_CODE_SUCCESS) {
1500 1501 1502 1503
      return code;
    }

    // set order by info
1504
    if (validateOrderbyNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1505 1506 1507
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

1508
    if ((code = validateFillNode(pQueryInfo, pSqlNode, pMsgBuf)) != TSDB_CODE_SUCCESS) {
1509 1510 1511 1512
      return code;
    }
  } else {
    pQueryInfo->command = TSDB_SQL_SELECT;
1513
    if (taosArrayGetSize(pSqlNode->from->list) > TSDB_MAX_JOIN_TABLE_NUM) {
1514
      return buildInvalidOperationMsg(pMsgBuf, msg2);
1515 1516
    }

1517
    STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, 0);
1518
    pQueryInfo->info.stableQuery = UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo);
1519

1520
    int32_t precision = pTableMetaInfo->pTableMeta->tableInfo.precision;
1521 1522

    // parse the group by clause in the first place
1523
    if (validateGroupbyNode(pQueryInfo, pSqlNode->pGroupby, pMsgBuf) != TSDB_CODE_SUCCESS) {
1524 1525
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }
1526

1527 1528
    // set where info
    if (pSqlNode->pWhere != NULL) {
1529
      if (validateWhereNode(pQueryInfo, pSqlNode->pWhere, pMsgBuf) != TSDB_CODE_SUCCESS) {
1530 1531 1532 1533
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }
    } else {
      if (taosArrayGetSize(pSqlNode->from->list) > 1) { // Cross join not allowed yet
1534
        return buildInvalidOperationMsg(pMsgBuf, "cross join not supported yet");
1535 1536 1537
      }
    }

H
Haojun Liao 已提交
1538
    if (validateSelectNodeList(pQueryInfo, pSqlNode->pSelNodeList, false, pMsgBuf) != TSDB_CODE_SUCCESS) {
1539 1540 1541 1542
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    // parse the window_state
1543
    if (validateStateWindowNode(pQueryInfo, &pSqlNode->windowstateVal, pMsgBuf) != TSDB_CODE_SUCCESS) {
1544 1545 1546 1547
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    // set interval value
1548
    if (validateIntervalNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1549 1550 1551 1552
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    // parse the having clause in the first place
1553
    if (validateHavingNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1554 1555 1556 1557 1558 1559 1560
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    /*
     * transfer sql functions that need secondary merge into another format
     * in dealing with super table queries such as: count/first/last
     */
1561
    if (validateSessionNode(pQueryInfo, &pSqlNode->sessionVal, precision, pMsgBuf) != TSDB_CODE_SUCCESS) {
1562 1563 1564 1565 1566 1567 1568 1569 1570
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    // no result due to invalid query time range
    if (pQueryInfo->window.skey > pQueryInfo->window.ekey) {
      pQueryInfo->command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
      return TSDB_CODE_SUCCESS;
    }

1571 1572 1573 1574 1575
    // set order by info
    if (validateOrderbyNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

1576
    if ((code = validateLimitNode(pQueryInfo, pSqlNode, pMsgBuf)) != TSDB_CODE_SUCCESS) {
1577 1578 1579
      return code;
    }

1580
    if ((code = validateFillNode(pQueryInfo, pSqlNode, pMsgBuf)) != TSDB_CODE_SUCCESS) {
1581 1582 1583 1584
      return code;
    }
  }

1585
  pushDownAggFuncExprInfo(pQueryInfo);
1586 1587

  for(int32_t i = 0; i < 1; ++i) {
H
Haojun Liao 已提交
1588 1589 1590 1591 1592 1593 1594 1595
    SArray* functionList = extractFunctionList(pQueryInfo->exprList[i]);
    extractFunctionDesc(functionList, &pQueryInfo->info);

    if ((code = checkForInvalidExpr(pQueryInfo, pMsgBuf)) != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

1596 1597 1598
  return TSDB_CODE_SUCCESS;  // Does not build query message here
}

1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
static bool isTagOrPrimaryTs(SExprInfo* pExprInfo) {
  if (pExprInfo->pExpr->nodeType != TEXPR_COL_NODE) {
    return false;
  }

  assert(pExprInfo->base.pColumns->info.colId == pExprInfo->pExpr->pSchema->colId);
  return (TSDB_COL_IS_TAG(pExprInfo->base.pColumns->flag) || pExprInfo->pExpr->pSchema->colId == PRIMARYKEY_TIMESTAMP_COL_ID);
}

// todo extract the table column in expression

static bool isGroupbyCol(SExprInfo* pExprInfo, SGroupbyExpr* pGroupbyExpr) {
  assert(pExprInfo != NULL && pGroupbyExpr != NULL);

  int32_t nodeType = pExprInfo->pExpr->nodeType;
  assert(nodeType == TEXPR_COL_NODE || nodeType == TEXPR_BINARYEXPR_NODE);

  for(int32_t i = 0; i < taosArrayGetSize(pGroupbyExpr->columnInfo); ++i) {
    SColumn* pCol = taosArrayGet(pGroupbyExpr->columnInfo, i);
    if (pCol->info.colId == pExprInfo->pExpr->pSchema->colId) {
      return true;
    }
  }

  return false;
}

static bool isAllAggExpr(SArray* pList) {
  assert(pList != NULL);

  for (int32_t k = 0; k < taosArrayGetSize(pList); ++k) {
    SExprInfo* p = taosArrayGetP(pList, k);
    if (p->pExpr->nodeType != TEXPR_FUNCTION_NODE || !qIsAggregateFunction(p->pExpr->_function.functionName)) {
      return false;
    }
  }

  return true;
}

1639 1640 1641 1642 1643 1644 1645 1646 1647
static bool isAllProjectExpr(SArray *pList) {
  assert(pList != NULL);

  for(int32_t i = 0; i < taosArrayGetSize(pList); ++i) {
    SExprInfo* p = taosArrayGetP(pList, i);
    if (p->pExpr->nodeType == TEXPR_FUNCTION_NODE && !qIsAggregateFunction(p->pExpr->_function.functionName)) {
      return false;
    }
  }
1648

1649 1650 1651 1652 1653 1654
  return true;
}

static SExprInfo* createColumnNodeFromAggFunc(SSchema* pSchema);

static void pushDownAggFuncExprInfo(SQueryStmtInfo* pQueryInfo) {
1655 1656 1657 1658 1659 1660
  assert(pQueryInfo != NULL);

  size_t level = getExprFunctionLevel(pQueryInfo);
  for(int32_t i = 0; i < level - 1; ++i) {
    SArray* p = pQueryInfo->exprList[i];

1661
    // If direct lower level expressions are all aggregate function, check if current function can be push down or not
1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673
    SArray* pNext = pQueryInfo->exprList[i + 1];
    if (!isAllAggExpr(pNext)) {
      continue;
    }

    for (int32_t j = 0; j < taosArrayGetSize(p); ++j) {
      SExprInfo* pExpr = taosArrayGetP(p, j);

      if (pExpr->pExpr->nodeType == TEXPR_FUNCTION_NODE && qIsAggregateFunction(pExpr->pExpr->_function.functionName)) {
        bool canPushDown = true;
        for (int32_t k = 0; k < taosArrayGetSize(pNext); ++k) {
          SExprInfo* pNextLevelExpr = taosArrayGetP(pNext, k);
1674
          // pExpr depends on the output of the down level, so it can not be push downwards
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
          if (pExpr->base.pColumns->info.colId == pNextLevelExpr->base.resSchema.colId) {
            canPushDown = false;
            break;
          }
        }

        if (canPushDown) {
          taosArrayInsert(pNext, j, &pExpr);
          taosArrayRemove(p, j);

1685 1686
          // Add the project function of the current level, to output the calculated result
          SExprInfo* pNew = createColumnNodeFromAggFunc(&pExpr->base.resSchema);
1687 1688 1689 1690 1691 1692 1693
          taosArrayInsert(p, j, &pNew);
        }
      }
    }
  }
}

1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
// todo change the logic plan data
static void addColumnNodeFromLowerLevel(SQueryStmtInfo* pQueryInfo) {
  assert(pQueryInfo != NULL);

  size_t level = getExprFunctionLevel(pQueryInfo);
  for (int32_t i = 0; i < level - 1; ++i) {
    SArray* p = pQueryInfo->exprList[i];
    if (isAllAggExpr(p)) {
      continue;
    }

    // If direct lower level expressions are all aggregate function, check if current function can be push down or not
    SArray* pNext = pQueryInfo->exprList[i + 1];
    if (isAllAggExpr(pNext)) {
      continue;
    }

    for (int32_t j = 0; j < taosArrayGetSize(pNext); ++j) {
      SExprInfo* pExpr = taosArrayGetP(p, j);

      bool exists = false;
      for (int32_t k = 0; k < taosArrayGetSize(p); ++k) {
        SExprInfo* pNextLevelExpr = taosArrayGetP(pNext, k);
        // pExpr depends on the output of the down level, so it can not be push downwards
        if (pExpr->base.pColumns->info.colId == pNextLevelExpr->base.resSchema.colId) {
          exists = true;
          break;
        }
      }

      if (!exists) {
        SExprInfo* pNew = calloc(1, sizeof(SExprInfo));
        pNew->pExpr = exprdup(pExpr->pExpr);
        memcpy(&pNew->base, &pExpr->base, sizeof(SSqlExpr));

        int32_t pos = taosArrayGetSize(p);
        // Add the project function of the current level, to output the calculated result
        taosArrayInsert(p, pos - 1, &pExpr);
      }
    }
  }
}

1737 1738 1739
int32_t checkForInvalidExpr(SQueryStmtInfo* pQueryInfo, SMsgBuf* pMsgBuf) {
  assert(pQueryInfo != NULL && pMsgBuf != NULL);

H
Haojun Liao 已提交
1740 1741 1742 1743 1744
  const char* msg1 = "invalid query expression";
  const char* msg2 = "top/bottom query does not support order by value in time window query";
  const char* msg3 = "fill only available in time window query";
  const char* msg4 = "top/bottom not support fill";
  const char* msg5 = "scalar function can not be used in time window query";
1745 1746
  const char* msg6 = "not support distinct mixed with join";
  const char* msg7 = "not support distinct mixed with groupby";
1747 1748
  const char* msg8 = "block_dist not support subquery, only support stable/table";
  const char* msg9 = "time window aggregate can not be mixed up with group by column";
H
Haojun Liao 已提交
1749 1750 1751 1752 1753 1754

  if (pQueryInfo->info.topbotQuery) {

    // 1. invalid sql:
    // select top(col, k) from table_name [interval(1d)|session(ts, 1d)|statewindow(col)] order by k asc
    // order by normal column is not supported
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766
    if (pQueryInfo->order != NULL) {
      size_t numOfOrder = taosArrayGetSize(pQueryInfo->order);
      if (numOfOrder > 1) {
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }

      if (numOfOrder > 0) {
        SColumn* pOrderCol = taosArrayGet(pQueryInfo->order, 0);
        if (pQueryInfo->info.timewindow && pOrderCol->info.colId != PRIMARYKEY_TIMESTAMP_COL_ID) {
          return buildInvalidOperationMsg(pMsgBuf, msg2);
        }
      }
H
Haojun Liao 已提交
1767 1768 1769 1770 1771 1772 1773
    }

    // select top(col, k) from table_name interval(10s) fill(prev)
    // not support fill in top/bottom query.
    if (pQueryInfo->fillType != TSDB_FILL_NONE) {
      return buildInvalidOperationMsg(pMsgBuf, msg4);
    }
1774 1775 1776 1777 1778 1779

    // select top(col, k), count(*) from table_name
    size_t size = getNumOfExprs(pQueryInfo);
    for (int32_t i = 0; i < size; ++i) {
      SExprInfo* pExpr = getExprInfo(pQueryInfo, i);

1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
      if (pExpr->pExpr->nodeType == TEXPR_COL_NODE) {
        if (!isTagOrPrimaryTs(pExpr) && !isGroupbyCol(pExpr, &pQueryInfo->groupbyExpr)) {
          return buildInvalidOperationMsg(pMsgBuf, "invalid expression in select clause");
        }

      } else if (pExpr->pExpr->nodeType == TEXPR_BINARYEXPR_NODE) {
        continue;
        // todo extract all column node in tree, and check for each node

        continue;
      }

      // dummy column is also the placeholder for primary timestamp column in the result.
      const char* functionName = pExpr->pExpr->_function.functionName;
      if (strcmp(functionName, "top") != 0 && strcmp(functionName, "bottom") != 0 && strcmp(functionName, "dummy") != 0) {
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808
        if (qIsAggregateFunction(functionName)) {
          return buildInvalidOperationMsg(pMsgBuf, "invalid expression in select clause");
        }

        // the primary key is valid
        if (pExpr->pExpr->nodeType == TEXPR_COL_NODE) {
          if (pExpr->pExpr->pSchema->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
            continue;
          }
        }

        continue;
      }
    }
H
Haojun Liao 已提交
1809
  }
1810

H
Haojun Liao 已提交
1811 1812 1813 1814 1815 1816 1817 1818
  /*
   * 2. invalid sql:
   * select count(tbname)/count(tag1)/count(tag2) from super_table_name [interval(1d)|session(ts, 1d)|statewindow(col)];
   */
  if (pQueryInfo->info.timewindow) {
    size_t size = getNumOfExprs(pQueryInfo);
    for (int32_t i = 0; i < size; ++i) {
      SExprInfo* pExpr = getExprInfo(pQueryInfo, i);
H
Haojun Liao 已提交
1819 1820 1821 1822 1823
      if (pExpr->pExpr->nodeType != TEXPR_FUNCTION_NODE) {
        continue;
      }

      int32_t functionId = getExprFunctionId(pExpr);
1824
      if (functionId == FUNCTION_COUNT && TSDB_COL_IS_TAG(pExpr->base.pColumns->flag)) {
H
Haojun Liao 已提交
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
        return buildInvalidOperationMsg(pMsgBuf, msg1);
      }
    }
  }

  /*
   * 3. invalid sql:
   * select tbname, tags_fields from super_table_name [interval(1s)|session(ts,1s)|statewindow(col)]
   */
  if (pQueryInfo->info.onlyTagQuery && pQueryInfo->info.timewindow) {
    return buildInvalidOperationMsg(pMsgBuf, msg1);
  }

  /*
   * 4. invalid sql:
   * select * from table_name fill(prev|next|null|none)
   */
  if (!pQueryInfo->info.timewindow && !pQueryInfo->info.interpQuery && pQueryInfo->fillType != TSDB_FILL_NONE) {
    return buildInvalidOperationMsg(pMsgBuf, msg3);
  }

  /*
   * 5. invalid sql:
   * select diff(col)|derivative(col)|* from table_name interval(1s)|session(20s)|statewindow(col)
   * projection query not compatible with the time window query
   */
  if (pQueryInfo->info.timewindow && pQueryInfo->info.projectionQuery) {
    return buildInvalidOperationMsg(pMsgBuf, msg5);
  }

  /*
   * 6. invalid sql:
   * distinct + join not supported.
   * select distinct a,b from table1, table2 where table1.ts=table2.ts
   *
   * distinct + group by not supported:
   * select distinct count(a) from table_name group by col1;
   */
  if (pQueryInfo->info.distinct) {
    if (pQueryInfo->info.join) {
1865 1866
      return buildInvalidOperationMsg(pMsgBuf, msg6);
    }
1867

1868 1869 1870
    if (taosArrayGetSize(pQueryInfo->groupbyExpr.columnInfo) != 0) {
      return buildInvalidOperationMsg(pMsgBuf, msg7);
    }
1871
  }
H
Haojun Liao 已提交
1872 1873 1874 1875 1876 1877

  /*
   * 7. invalid sql:
   * nested subquery not support block_dist query
   * select block_dist() from (select * from table_name)
   */
1878 1879 1880 1881 1882 1883 1884 1885 1886

  /*
   * 8. invalid sql:
   * select count(*) from table_name [interval(10s)|session(ts, 10s)|state_window(col_name)] group by col_name
   */
  if ((pQueryInfo->info.timewindow || pQueryInfo->info.stateWindow || pQueryInfo->info.sessionWindow) &&
      pQueryInfo->info.groupbyColumn) {
    return buildInvalidOperationMsg(pMsgBuf, msg9);
  }
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915

  /*
   * 9. invalid sql:
   * select count(*), col_name from table_name
   */
  if (pQueryInfo->info.agg) {
    bool isSelectivity = false;

    if (pQueryInfo->info.projectionQuery) {
      size_t size = getNumOfExprs(pQueryInfo);
      for (int32_t i = 0; i < size; ++i) {
        SExprInfo* pExpr = getExprInfo(pQueryInfo, i);
        if (pExpr->pExpr->nodeType == TEXPR_FUNCTION_NODE) {
          if (!isSelectivity) {
            isSelectivity = qIsSelectivityFunction(pExpr->pExpr->_function.functionName);
          }
          continue;
        }

        if (isSelectivity && isTagOrPrimaryTs(pExpr)) {
          continue;
        }

        if (!isGroupbyCol(pExpr, &pQueryInfo->groupbyExpr)) {
          return buildInvalidOperationMsg(pMsgBuf, "invalid expression in select");
        }
      }
    }
  }
1916
}
1917

1918
int32_t addResColumnInfo(SQueryStmtInfo* pQueryInfo, int32_t outputIndex, SSchema* pSchema, SExprInfo* pSqlExpr) {
1919 1920 1921 1922
  SInternalField* pInfo = insertFieldInfo(&pQueryInfo->fieldsInfo, outputIndex, pSchema);
  pInfo->pExpr = pSqlExpr;
  return TSDB_CODE_SUCCESS;
}
1923

1924 1925 1926 1927 1928 1929 1930
void setResultColName(char* name, tSqlExprItem* pItem, SToken* pToken, SToken* functionToken, bool multiCols) {
  if (pItem->aliasName != NULL) {
    tstrncpy(name, pItem->aliasName, TSDB_COL_NAME_LEN);
  } else if (multiCols) {
    char uname[TSDB_COL_NAME_LEN] = {0};
    int32_t len = MIN(pToken->n + 1, TSDB_COL_NAME_LEN);
    tstrncpy(uname, pToken->z, len);
1931

1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949
    if (tsKeepOriginalColumnName) { // keep the original column name
      tstrncpy(name, uname, TSDB_COL_NAME_LEN);
    } else {
      const int32_t size = TSDB_COL_NAME_LEN + FUNCTIONS_NAME_MAX_LENGTH + 2 + 1;
      char tmp[TSDB_COL_NAME_LEN + FUNCTIONS_NAME_MAX_LENGTH + 2 + 1] = {0};

      char f[FUNCTIONS_NAME_MAX_LENGTH] = {0};
      strncpy(f, functionToken->z, functionToken->n);

      snprintf(tmp, size, "%s(%s)", f, uname);
      tstrncpy(name, tmp, TSDB_COL_NAME_LEN);
    }
  } else  { // use the user-input result column name
    int32_t len = MIN(pItem->pNode->exprToken.n + 1, TSDB_COL_NAME_LEN);
    tstrncpy(name, pItem->pNode->exprToken.z, len);
  }
}

1950
SExprInfo* doAddOneExprInfo(SQueryStmtInfo* pQueryInfo, const char* funcName, SSourceParam* pSourceParam, int32_t outputIndex,
1951
                           STableMetaInfo* pTableMetaInfo, SSchema* pResultSchema, int32_t interSize, const char* token, bool finalResult) {
1952
  SExprInfo* pExpr = createExprInfo(pTableMetaInfo, funcName, pSourceParam, pResultSchema, interSize);
1953
  tstrncpy(pExpr->base.token, token, sizeof(pExpr->base.token));
1954 1955

  SArray* pExprList = getCurrentExprList(pQueryInfo);
1956
  addExprInfo(pExprList, outputIndex, pExpr, pQueryInfo->exprListLevelIndex);
1957

1958
  uint64_t uid = pTableMetaInfo->pTableMeta->uid;
1959

1960 1961 1962
  if (pSourceParam->pColumnList != NULL) {
    SColumn* pCol = taosArrayGetP(pSourceParam->pColumnList, 0);

1963
    if (TSDB_COL_IS_TAG(pCol->flag) || TSDB_COL_IS_NORMAL_COL(pCol->flag)) {
1964
      SArray* p = TSDB_COL_IS_TAG(pCol->flag) ? pTableMetaInfo->tagColList : pQueryInfo->colList;
1965

1966 1967 1968 1969 1970 1971 1972 1973
      for (int32_t i = 0; i < pSourceParam->num; ++i) {
        SColumn* pColumn = taosArrayGetP(pSourceParam->pColumnList, i);
        SSchema s = createSchema(pColumn->info.type, pColumn->info.bytes, pColumn->info.colId, pColumn->name) ;
        columnListInsert(p, uid, &s, pCol->flag);
      }
    }

    if (TSDB_COL_IS_NORMAL_COL(pCol->flag)) {
1974 1975
      char* colName = pTableMetaInfo->pTableMeta->schema[0].name;
      insertPrimaryTsColumn(pQueryInfo->colList, colName, uid);
1976
    }
1977
  }
1978

1979
  if (finalResult) {
1980
    addResColumnInfo(pQueryInfo, outputIndex, pResultSchema, pExpr);
1981 1982
  }

1983
  return pExpr;
1984 1985
}

1986 1987 1988 1989 1990 1991
static void extractFunctionName(char* name, const tSqlExprItem* pItem) {
  assert(pItem != NULL);
  SToken* funcToken = &pItem->pNode->Expr.operand;
  memcpy(name, funcToken->z, funcToken->n);
}

1992
static int32_t addOneExprInfo(SQueryStmtInfo* pQueryInfo, tSqlExprItem* pItem, int32_t functionId, int32_t outputIndex, SSchema* pSchema, SColumnIndex* pColIndex, tExprNode* pNode, bool finalResult, SMsgBuf* pMsgBuf) {
1993 1994 1995 1996 1997 1998 1999
  const char* msg1 = "not support column types";
  if (functionId == FUNCTION_SPREAD) {
    if (IS_VAR_DATA_TYPE(pSchema->type) || pSchema->type == TSDB_DATA_TYPE_BOOL) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }
  }

2000 2001 2002
  char name[TSDB_COL_NAME_LEN] = {0};
  SToken t = {.z = pSchema->name, .n = (uint32_t)strnlen(pSchema->name, TSDB_COL_NAME_LEN)};
  setResultColName(name, pItem, &t, &pItem->pNode->Expr.operand, true);
2003

2004 2005
  SResultDataInfo resInfo = {0};
  getResultDataInfo(pSchema->type, pSchema->bytes, functionId, 0, &resInfo, 0, false);
2006

2007
  SSchema resultSchema = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), name);
2008 2009

  STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, pColIndex->tableIndex);
2010
  SColumn c = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, pColIndex->type, pSchema);
2011 2012 2013 2014

  SSourceParam param = {0};
  addIntoSourceParam(&param, pNode, &c);

2015 2016 2017 2018
  char fname[FUNCTIONS_NAME_MAX_LENGTH] = {0};
  extractFunctionName(fname, pItem);
  doAddOneExprInfo(pQueryInfo, fname, &param, outputIndex, pTableMetaInfo, &resultSchema, resInfo.intermediateBytes, name, finalResult);

2019 2020 2021
  return TSDB_CODE_SUCCESS;
}

2022 2023 2024 2025 2026 2027 2028 2029 2030
static int32_t checkForAliasName(SMsgBuf* pMsgBuf, char* aliasName) {
  const char* msg1 = "column alias name too long";
  if (aliasName != NULL && strlen(aliasName) >= TSDB_COL_NAME_LEN) {
    return buildInvalidOperationMsg(pMsgBuf, msg1);
  }

  return TSDB_CODE_SUCCESS;
}

2031
static int32_t sqlExprToExprNode(tExprNode **pExpr, const tSqlExpr* pSqlExpr, SQueryStmtInfo* pQueryInfo, SArray* pCols, bool* keepTableCols, SMsgBuf* pMsgBuf);
2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054

static int64_t getTickPerSecond(SVariant* pVariant, int32_t precision, int64_t* tickPerSec, SMsgBuf *pMsgBuf) {
  const char* msg10 = "derivative duration should be greater than 1 Second";

  if (taosVariantDump(pVariant, (char*) tickPerSec, TSDB_DATA_TYPE_BIGINT, true) < 0) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

  if (precision == TSDB_TIME_PRECISION_MILLI) {
    *tickPerSec /= TSDB_TICK_PER_SECOND(TSDB_TIME_PRECISION_MICRO);
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
    *tickPerSec /= TSDB_TICK_PER_SECOND(TSDB_TIME_PRECISION_MILLI);
  }

  if (*tickPerSec <= 0 || *tickPerSec < TSDB_TICK_PER_SECOND(precision)) {
    return buildInvalidOperationMsg(pMsgBuf, msg10);
  }

  return TSDB_CODE_SUCCESS;
}

// set the first column ts for top/bottom query
static void setTsOutputExprInfo(SQueryStmtInfo* pQueryInfo, STableMetaInfo* pTableMetaInfo, int32_t outputIndex, int32_t tableIndex) {
2055
  SColumnIndex indexTS = {.tableIndex = tableIndex, .columnIndex = PRIMARYKEY_TIMESTAMP_COL_ID, .type = TSDB_COL_NORMAL};
2056 2057
  SSchema s = createSchema(TSDB_DATA_TYPE_TIMESTAMP, TSDB_KEYSIZE, getNewResColId(), "ts");

2058 2059 2060 2061 2062
  SColumn col = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, TSDB_COL_NORMAL, &s);

  SSourceParam param = {0};
  addIntoSourceParam(&param, NULL, &col);

2063
  SExprInfo* pExpr = createExprInfo(pTableMetaInfo, "dummy", &param, &s, TSDB_KEYSIZE);
H
Haojun Liao 已提交
2064 2065
  strncpy(pExpr->base.token, "ts", tListLen(pExpr->base.token));

2066 2067
  SArray* pExprList = getCurrentExprList(pQueryInfo);
  addExprInfo(pExprList, outputIndex, pExpr, pQueryInfo->exprListLevelIndex);
2068 2069

  SSchema* pSourceSchema = getOneColumnSchema(pTableMetaInfo->pTableMeta, indexTS.columnIndex);
2070
  columnListInsert(pQueryInfo->colList, pTableMetaInfo->pTableMeta->uid, pSourceSchema, TSDB_COL_NORMAL);
2071 2072 2073
  addResColumnInfo(pQueryInfo, outputIndex, &pExpr->base.resSchema, pExpr);
}

2074 2075 2076
static int32_t setColumnIndex(SQueryStmtInfo* pQueryInfo, SArray* pParamList, SColumnIndex* index, SSchema* columnSchema, tExprNode** pNode, SMsgBuf* pMsgBuf) {
  const char* msg1 = "illegal column name";
  const char* msg2 = "invalid table name";
2077

2078 2079 2080 2081 2082 2083
  STableMeta* pTableMeta = getMetaInfo(pQueryInfo, 0)->pTableMeta;
  if (pParamList == NULL) {
    // count(*) is equalled to count(primary_timestamp_key)
    *index = (SColumnIndex) {0, PRIMARYKEY_TIMESTAMP_COL_ID, false};
    *columnSchema = *(SSchema*) getOneColumnSchema(pTableMeta, index->columnIndex);
  } else {
2084 2085 2086 2087 2088 2089
    tSqlExprItem* pParamElem = taosArrayGet(pParamList, 0);

    SToken* pToken = &pParamElem->pNode->columnName;
    int16_t tokenId = pParamElem->pNode->tokenId;

    // select count(table.*), select count(1), count(2)
2090
    if (tokenId == TK_ALL || tokenId == TK_INTEGER || tokenId == TK_FLOAT) {
2091 2092 2093
      // check if the table name is valid or not
      SToken tmpToken = pParamElem->pNode->columnName;
      if (getTableIndexByName(&tmpToken, pQueryInfo, index) != TSDB_CODE_SUCCESS) {
2094
        return buildInvalidOperationMsg(pMsgBuf, msg2);
2095 2096
      }

2097 2098 2099
      *index = (SColumnIndex) {0, PRIMARYKEY_TIMESTAMP_COL_ID, false};
      *columnSchema = *(SSchema*) getOneColumnSchema(pTableMeta, index->columnIndex);
    } else if (pToken->z != NULL && pToken->n > 0) {
2100 2101
      // count the number of table created according to the super table
      if (getColumnIndexByName(pToken, pQueryInfo, index, pMsgBuf) != TSDB_CODE_SUCCESS) {
2102 2103 2104 2105 2106 2107 2108 2109 2110
        return buildInvalidOperationMsg(pMsgBuf, msg1);
      }

      *columnSchema = *(SSchema*) getOneColumnSchema(pTableMeta, index->columnIndex);
    } else {
      STableMetaInfo* pTableMetaInfo = NULL;
      int32_t code = extractFunctionParameterInfo(pQueryInfo, tokenId, &pTableMetaInfo, columnSchema, pNode, index, pParamElem, pMsgBuf);
      if (code != TSDB_CODE_SUCCESS) {
        return buildInvalidOperationMsg(pMsgBuf, msg1);
2111 2112 2113 2114 2115 2116 2117 2118 2119
      }
    }
  }

  return TSDB_CODE_SUCCESS;
}

static int32_t doAddAllColumnExprInSelectClause(SQueryStmtInfo *pQueryInfo, STableMetaInfo* pTableMetaInfo, tSqlExprItem* pItem, int32_t functionId,
    int32_t tableIndex, int32_t* colIndex, bool finalResult, SMsgBuf* pMsgBuf) {
2120 2121
  STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;
  for (int32_t i = 0; i < getNumOfColumns(pTableMeta); ++i) {
2122 2123
    SColumnIndex index = {.tableIndex = tableIndex, .columnIndex = i, .type = TSDB_COL_NORMAL};

2124 2125
    SSchema* pSchema = getOneColumnSchema(pTableMeta, i);
    if (addOneExprInfo(pQueryInfo, pItem, functionId, *colIndex, pSchema, &index, NULL, finalResult, pMsgBuf) != 0) {
2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    (*colIndex)++;
  }
}

static int32_t doHandleOneParam(SQueryStmtInfo *pQueryInfo, tSqlExprItem* pItem, tSqlExprItem* pParamElem, int32_t functionId,
    int32_t* outputIndex, bool finalResult, SMsgBuf* pMsgBuf) {
  const char* msg3 = "illegal column name";
  const char* msg4 = "invalid table name";
  const char* msg6 = "functions applied to tags are not allowed";

  SColumnIndex index = COLUMN_INDEX_INITIALIZER;

  if (pParamElem->pNode->tokenId == TK_ALL) { // select table.*
    SToken tmpToken = pParamElem->pNode->columnName;

    if (getTableIndexByName(&tmpToken, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
      return buildInvalidOperationMsg(pMsgBuf, msg4);
    }

    STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);
    doAddAllColumnExprInSelectClause(pQueryInfo, pTableMetaInfo, pItem, functionId, index.tableIndex, outputIndex, finalResult, pMsgBuf);
  } else {
    tExprNode* pNode = NULL;
    int32_t tokenId = pParamElem->pNode->tokenId;
    SSchema columnSchema = {0};
    STableMetaInfo* pTableMetaInfo = {0};

2156
    int32_t code = extractFunctionParameterInfo(pQueryInfo, tokenId, &pTableMetaInfo, &columnSchema, &pNode, &index, pParamElem, pMsgBuf);
2157

2158
    if (code != TSDB_CODE_SUCCESS) {
2159 2160 2161 2162
      return buildInvalidOperationMsg(pMsgBuf, msg3);
    }

    // functions can not be applied to tags
2163
    if (TSDB_COL_IS_TAG(index.type) && (functionId == FUNCTION_INTERP || functionId == FUNCTION_SPREAD)) {
2164 2165 2166
      return buildInvalidOperationMsg(pMsgBuf, msg6);
    }

2167
    if (addOneExprInfo(pQueryInfo, pItem, functionId, (*outputIndex)++, &columnSchema, &index, pNode, finalResult, pMsgBuf) != 0) {
2168 2169 2170 2171 2172
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }
  }
}

2173
static int32_t multiColumnListInsert(SQueryStmtInfo* pQueryInfo, SArray* pColumnList, SMsgBuf* pMsgBuf);
2174
static int32_t addScalarExprAndResColumn(SQueryStmtInfo* pQueryInfo, int32_t exprIndex, tSqlExprItem* pItem, SMsgBuf* pMsgBuf);
2175

2176 2177 2178
int32_t extractFunctionParameterInfo(SQueryStmtInfo* pQueryInfo, int32_t tokenId, STableMetaInfo** pTableMetaInfo,
                                     SSchema* columnSchema, tExprNode** pNode, SColumnIndex* pIndex,
                                     tSqlExprItem* pParamElem, SMsgBuf* pMsgBuf) {
2179 2180 2181
  const char* msg1 = "not support column types";
  const char* msg2 = "invalid parameters";
  const char* msg3 = "illegal column name";
2182 2183
  const char* msg4 = "nested function is not supported";
  const char* msg5 = "functions applied to tags are not allowed";
2184 2185
  const char* msg6 = "aggregate function can not be nested in aggregate function";
  const char* msg7 = "invalid function name";
2186

2187 2188
  pQueryInfo->exprListLevelIndex += 1;

2189
  if (tokenId == TK_ALL || tokenId == TK_ID) {  // simple parameter
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
    // simple parameter or nested function
    // It is a parameter of a aggregate function, so it can not be still a aggregate function.
    // E.g., the sql statement of "select count(count(*)) from table_name" is invalid.
    tSqlExpr* pSqlExpr = pParamElem->pNode;
    if (pParamElem->pNode->type == SQL_NODE_SQLFUNCTION) {
      bool scalarFunc = false;
      pParamElem->functionId = qIsBuiltinFunction(pSqlExpr->Expr.operand.z, pSqlExpr->Expr.operand.n, &scalarFunc);
      if (pParamElem->functionId == FUNCTION_INVALID_ID) {
        return buildInvalidOperationMsg(pMsgBuf, msg7);
      }
2200

2201 2202 2203 2204
      if (!scalarFunc) {
        return buildInvalidOperationMsg(pMsgBuf, msg6);
      }

2205 2206 2207 2208 2209
      SArray* pExprList = getCurrentExprList(pQueryInfo);
      size_t n = taosArrayGetSize(pExprList);

      // todo extract the table uid
      pIndex->tableIndex = 0;
2210
      int32_t code = addScalarExprAndResColumn(pQueryInfo, n, pParamElem, pMsgBuf);
2211 2212 2213 2214
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

2215 2216 2217 2218
      SExprInfo** pLastExpr = taosArrayGetLast(pExprList);
      *pNode = (*pLastExpr)->pExpr;
      *(SSchema*)  columnSchema = (*pLastExpr)->base.resSchema;
      *pTableMetaInfo = getMetaInfo(pQueryInfo, 0);
2219 2220 2221 2222
    } else {
      if ((getColumnIndexByName(&pParamElem->pNode->columnName, pQueryInfo, pIndex, pMsgBuf) != TSDB_CODE_SUCCESS)) {
        return buildInvalidOperationMsg(pMsgBuf, msg3);
      }
2223

2224 2225 2226 2227
      // functions can not be applied to tags
      if (TSDB_COL_IS_TAG(pIndex->type)) {
        return buildInvalidOperationMsg(pMsgBuf, msg5);
      }
2228

2229 2230 2231 2232
      // 2. check if sql function can be applied on this column data type
      *pTableMetaInfo = getMetaInfo(pQueryInfo, pIndex->tableIndex);
      *columnSchema = *(SSchema*)getOneColumnSchema((*pTableMetaInfo)->pTableMeta, pIndex->columnIndex);
    }
2233 2234
  } else if (tokenId == TK_PLUS || tokenId == TK_MINUS || tokenId == TK_STAR || tokenId == TK_REM || tokenId == TK_DIVIDE || tokenId == TK_CONCAT) {
    pIndex->tableIndex = 0; // todo set the correct table index
2235
    pIndex->type = TSDB_COL_TMP;  // It is a temporary column generated by arithmetic expression.
2236

2237 2238
    SArray* pExprList = getCurrentExprList(pQueryInfo);
    size_t n = taosArrayGetSize(pExprList);
2239
    int32_t code = addScalarExprAndResColumn(pQueryInfo, n, pParamElem, pMsgBuf);
2240 2241
    if (code != TSDB_CODE_SUCCESS) {
      return code;
2242 2243
    }

2244 2245 2246 2247
    SExprInfo** pLastExpr = taosArrayGetLast(getCurrentExprList(pQueryInfo));
    *pNode = (*pLastExpr)->pExpr;
    *(SSchema*)  columnSchema = (*pLastExpr)->base.resSchema;
    *pTableMetaInfo = getMetaInfo(pQueryInfo, 0);
2248 2249 2250
  } else {
    assert(0);
  }
2251 2252

  pQueryInfo->exprListLevelIndex -= 1;
2253 2254 2255 2256 2257 2258
  return TSDB_CODE_SUCCESS;
}

static int32_t checkForkParam(tSqlExpr* pSqlExpr, size_t k, SMsgBuf* pMsgBuf) {
  const char* msg1 = "invalid parameters";

H
Haojun Liao 已提交
2259 2260
  SArray* pParamList = pSqlExpr->Expr.paramList;

2261
  if (k == 0) {
H
Haojun Liao 已提交
2262
    if (pParamList != NULL && taosArrayGetSize(pParamList) != 0) {
2263 2264
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }
H
Haojun Liao 已提交
2265 2266 2267 2268
  } else if (k == 1) {
    if (!(pParamList == NULL || taosArrayGetSize(pParamList) == k)) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);;
    }
2269
  } else {
H
Haojun Liao 已提交
2270
    if (pParamList != NULL && taosArrayGetSize(pParamList) != k) {
2271 2272 2273 2274 2275 2276
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }
  }
  return TSDB_CODE_SUCCESS;
}

2277
int32_t addAggExprAndResColumn(SQueryStmtInfo* pQueryInfo, int32_t colIndex, tSqlExprItem* pItem, bool finalResult, SMsgBuf* pMsgBuf) {
2278 2279
  STableMetaInfo* pTableMetaInfo = NULL;
  int32_t functionId = pItem->functionId;
2280
  int32_t code = TSDB_CODE_SUCCESS;
2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293

  const char* msg1 = "not support column types";
  const char* msg2 = "invalid parameters";
  const char* msg3 = "illegal column name";
  const char* msg4 = "invalid table name";
  const char* msg5 = "parameter is out of range [0, 100]";
  const char* msg6 = "functions applied to tags are not allowed";
  const char* msg7 = "normal table can not apply this function";
  const char* msg8 = "multi-columns selection does not support alias column name";
  const char* msg9 = "diff/derivative can no be applied to unsigned numeric type";
  const char* msg10 = "derivative duration should be greater than 1 Second";
  const char* msg11 = "third parameter in derivative should be 0 or 1";
  const char* msg12 = "parameter is out of range [1, 100]";
2294 2295 2296 2297 2298
  const char* msg13 = "nested function is not supported";

  if (checkForAliasName(pMsgBuf, pItem->aliasName) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }
2299 2300 2301 2302 2303

  switch (functionId) {
    case FUNCTION_COUNT: {
      // more than one parameter for count() function
      SArray* pParamList = pItem->pNode->Expr.paramList;
2304 2305
      if ((code = checkForkParam(pItem->pNode, 1, pMsgBuf)) != TSDB_CODE_SUCCESS) {
        return code;
2306 2307
      }

2308
      tExprNode* pNode = NULL;
2309
      SColumnIndex index = COLUMN_INDEX_INITIALIZER;
2310 2311 2312
      SSchema columnSchema = {0};

      code = setColumnIndex(pQueryInfo, pParamList, &index, &columnSchema, &pNode, pMsgBuf);
2313 2314
      if (code != TSDB_CODE_SUCCESS) {
        return code;
2315 2316 2317
      }

      int32_t size = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
2318
      SSchema s = createSchema(TSDB_DATA_TYPE_BIGINT, size, getNewResColId(), "");
2319

2320 2321
      char token[TSDB_COL_NAME_LEN] = {0};
      setTokenAndResColumnName(pItem, s.name, token,sizeof(s.name) - 1);
2322

2323
      pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);
2324 2325 2326 2327 2328
      SColumn c = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, index.type, &columnSchema);

      SSourceParam param = {0};
      addIntoSourceParam(&param, pNode, &c);

2329
      int32_t outputIndex = getNumOfFields(&pQueryInfo->fieldsInfo);
2330 2331 2332 2333

      char fname[FUNCTIONS_NAME_MAX_LENGTH] = {0};
      extractFunctionName(fname, pItem);
      doAddOneExprInfo(pQueryInfo, fname, &param, outputIndex, pTableMetaInfo, &s, size, token, finalResult);
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359
      return TSDB_CODE_SUCCESS;
    }

    case FUNCTION_SUM:
    case FUNCTION_AVG:
    case FUNCTION_RATE:
    case FUNCTION_IRATE:
    case FUNCTION_TWA:
    case FUNCTION_MIN:
    case FUNCTION_MAX:
    case FUNCTION_DIFF:
    case FUNCTION_DERIVATIVE:
    case FUNCTION_STDDEV:
    case FUNCTION_LEASTSQR: {
      // 1. valid the number of parameters
      int32_t numOfParams = (pItem->pNode->Expr.paramList == NULL)? 0: (int32_t) taosArrayGetSize(pItem->pNode->Expr.paramList);

      // no parameters or more than one parameter for function
      if (pItem->pNode->Expr.paramList == NULL ||
          (functionId != FUNCTION_LEASTSQR && functionId != FUNCTION_DERIVATIVE && numOfParams != 1) ||
          ((functionId == FUNCTION_LEASTSQR || functionId == FUNCTION_DERIVATIVE) && numOfParams != 3)) {
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }

      tSqlExprItem* pParamElem = taosArrayGet(pItem->pNode->Expr.paramList, 0);

2360 2361 2362
      tExprNode* pNode     = NULL;
      int32_t tokenId      = pParamElem->pNode->tokenId;
      SColumnIndex index   = COLUMN_INDEX_INITIALIZER;
2363
      SSchema columnSchema = {0};
2364 2365
      code = extractFunctionParameterInfo(pQueryInfo, tokenId, &pTableMetaInfo, &columnSchema, &pNode, &index, pParamElem, pMsgBuf);

2366 2367 2368 2369 2370
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
      
      if (tokenId == TK_ALL || tokenId == TK_ID) {
2371 2372 2373 2374 2375
        if (!IS_NUMERIC_TYPE(columnSchema.type)) {
          return buildInvalidOperationMsg(pMsgBuf, msg1);
        } else if (IS_UNSIGNED_NUMERIC_TYPE(columnSchema.type) && (functionId == FUNCTION_DIFF || functionId == FUNCTION_DERIVATIVE)) {
          return buildInvalidOperationMsg(pMsgBuf, msg9);
        }
2376 2377
      }

2378 2379
      int32_t precision = pTableMetaInfo->pTableMeta->tableInfo.precision;

2380 2381
      SResultDataInfo resInfo = {0};
      if (getResultDataInfo(columnSchema.type, columnSchema.bytes, functionId, 0, &resInfo, 0, false) != TSDB_CODE_SUCCESS) {
2382 2383
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }
2384 2385 2386 2387

      // set the first column ts for diff query
      int32_t numOfOutput = getNumOfFields(&pQueryInfo->fieldsInfo);
      if (functionId == FUNCTION_DIFF || functionId == FUNCTION_DERIVATIVE) {
2388
        setTsOutputExprInfo(pQueryInfo, pTableMetaInfo, numOfOutput, index.tableIndex);
2389 2390 2391
        numOfOutput += 1;
      }

2392 2393 2394 2395
      SSchema s = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), "ts");

      char token[TSDB_COL_NAME_LEN] = {0};
      setTokenAndResColumnName(pItem, s.name, token, sizeof(s.name) - 1);
2396

2397 2398 2399 2400 2401
      SColumn c = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, index.type, &columnSchema);

      SSourceParam param = {0};
      addIntoSourceParam(&param, pNode, &c);

2402 2403
      char funcName[FUNCTIONS_NAME_MAX_LENGTH] = {0};
      extractFunctionName(funcName, pItem);
2404

2405
      SExprInfo* pExpr = doAddOneExprInfo(pQueryInfo, funcName, &param, numOfOutput, pTableMetaInfo, &s, resInfo.intermediateBytes, token, finalResult);
2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420
      if (functionId == FUNCTION_LEASTSQR) { // set the leastsquares parameters
        char val[8] = {0};
        if (taosVariantDump(&pParamElem[1].pNode->value, val, TSDB_DATA_TYPE_DOUBLE, true) < 0) {
          return TSDB_CODE_TSC_INVALID_OPERATION;
        }

        addExprInfoParam(&pExpr->base, val, TSDB_DATA_TYPE_DOUBLE, DOUBLE_BYTES);

        memset(val, 0, tListLen(val));
        if (taosVariantDump(&pParamElem[2].pNode->value, val, TSDB_DATA_TYPE_DOUBLE, true) < 0) {
          return TSDB_CODE_TSC_INVALID_OPERATION;
        }

        addExprInfoParam(&pExpr->base, val, TSDB_DATA_TYPE_DOUBLE, DOUBLE_BYTES);
      } else if (functionId == FUNCTION_IRATE) {
2421
        addExprInfoParam(&pExpr->base, (char*) &precision, TSDB_DATA_TYPE_BIGINT, LONG_BYTES);
2422 2423 2424 2425
      } else if (functionId == FUNCTION_DERIVATIVE) {
        char val[8] = {0};

        int64_t tickPerSec = 0;
2426
        code = getTickPerSecond(&pParamElem[1].pNode->value, precision, &tickPerSec, pMsgBuf);
2427 2428
        if (code != TSDB_CODE_SUCCESS) {
          return code;
2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459
        }

        addExprInfoParam(&pExpr->base, (char*) &tickPerSec, TSDB_DATA_TYPE_BIGINT, LONG_BYTES);
        memset(val, 0, tListLen(val));

        if (taosVariantDump(&pParamElem[2].pNode->value, val, TSDB_DATA_TYPE_BIGINT, true) < 0) {
          return TSDB_CODE_TSC_INVALID_OPERATION;
        }

        if (GET_INT64_VAL(val) != 0 && GET_INT64_VAL(val) != 1) {
          return buildInvalidOperationMsg(pMsgBuf, msg11);
        }

        addExprInfoParam(&pExpr->base, val, TSDB_DATA_TYPE_BIGINT, LONG_BYTES);
      }
      return TSDB_CODE_SUCCESS;
    }

    case FUNCTION_FIRST:
    case FUNCTION_LAST:
    case FUNCTION_SPREAD:
    case FUNCTION_LAST_ROW:
    case FUNCTION_INTERP: {
      bool requireAllFields = (pItem->pNode->Expr.paramList == NULL);

      if (!requireAllFields) {
        SArray* pParamList = pItem->pNode->Expr.paramList;
        if (taosArrayGetSize(pParamList) < 1) {
          return buildInvalidOperationMsg(pMsgBuf, msg3);
        }

2460
        if (taosArrayGetSize(pParamList) > 1 && (pItem->aliasName != NULL)) {
2461 2462 2463
          return buildInvalidOperationMsg(pMsgBuf, msg8);
        }

2464
        // in first/last function, multiple columns can be add to resultset
2465 2466
        for (int32_t i = 0; i < taosArrayGetSize(pParamList); ++i) {
          tSqlExprItem* pParamElem = taosArrayGet(pParamList, i);
2467
          doHandleOneParam(pQueryInfo, pItem, pParamElem, functionId, &colIndex, finalResult, pMsgBuf);
2468
        }
2469
      } else {  // select function(*) from xxx
2470 2471 2472 2473 2474 2475 2476 2477 2478
        int32_t numOfFields = 0;

        // multicolumn selection does not support alias name
        if (pItem->aliasName != NULL && strlen(pItem->aliasName) > 0) {
          return buildInvalidOperationMsg(pMsgBuf, msg8);
        }

        for (int32_t j = 0; j < pQueryInfo->numOfTables; ++j) {
          pTableMetaInfo = getMetaInfo(pQueryInfo, j);
2479
          doAddAllColumnExprInSelectClause(pQueryInfo, pTableMetaInfo, pItem, functionId, j, &colIndex, finalResult, pMsgBuf);
2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491
          numOfFields += getNumOfColumns(pTableMetaInfo->pTableMeta);
        }
      }
      return TSDB_CODE_SUCCESS;
    }

    case FUNCTION_TOP:
    case FUNCTION_BOTTOM:
    case FUNCTION_PERCT:
    case FUNCTION_APERCT: {
      // 1. valid the number of parameters
      // no parameters or more than one parameter for function
2492 2493
      if ((code = checkForkParam(pItem->pNode, 2, pMsgBuf)) != TSDB_CODE_SUCCESS) {
        return code;
2494 2495 2496
      }

      tSqlExprItem* pParamElem = taosArrayGet(pItem->pNode->Expr.paramList, 0);
2497
      if (pParamElem->pNode->tokenId == TK_ALL) {
2498 2499 2500
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }

2501 2502
      tExprNode* pNode = NULL;
      int32_t tokenId = pParamElem->pNode->tokenId;
2503
      SColumnIndex index = COLUMN_INDEX_INITIALIZER;
2504 2505 2506 2507
      SSchema columnSchema = {0};
      code = extractFunctionParameterInfo(pQueryInfo, tokenId, &pTableMetaInfo, &columnSchema, &pNode, &index, pParamElem,pMsgBuf);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
      }

      // functions can not be applied to tags
      if (TSDB_COL_IS_TAG(index.type)) {
        return buildInvalidOperationMsg(pMsgBuf, msg6);
      }

      pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);

      // 2. valid the column type
2518
      if (!IS_NUMERIC_TYPE(columnSchema.type)) {
2519 2520 2521 2522 2523 2524 2525 2526
        return buildInvalidOperationMsg(pMsgBuf, msg1);
      }

      // 3. valid the parameters
      if (pParamElem[1].pNode->tokenId == TK_ID) {
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }

2527
      SResultDataInfo resInfo = {0};
2528 2529 2530 2531 2532 2533
      getResultDataInfo(columnSchema.type, columnSchema.bytes, functionId, 0, &resInfo, 0, false);
      if (functionId == FUNCTION_TOP || functionId == FUNCTION_BOTTOM) {
        // set the first column ts for top/bottom query
        setTsOutputExprInfo(pQueryInfo, pTableMetaInfo, colIndex, index.tableIndex);
        colIndex += 1;  // the first column is ts
      }
2534

2535
      SSchema s = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), "");
2536

2537 2538
      char token[TSDB_COL_NAME_LEN] = {0};
      setTokenAndResColumnName(pItem, s.name, token, sizeof(s.name) - 1);
2539 2540 2541 2542 2543 2544

      SColumn c = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, index.type, &columnSchema);

      SSourceParam param = {0};
      addIntoSourceParam(&param, pNode, &c);

2545 2546 2547
      char funcName[FUNCTIONS_NAME_MAX_LENGTH] = {0};
      extractFunctionName(funcName, pItem);
      SExprInfo* pExpr = doAddOneExprInfo(pQueryInfo, funcName, &param, colIndex, pTableMetaInfo, &s, resInfo.intermediateBytes, token, finalResult);
2548

2549 2550 2551 2552 2553 2554
      SToken* pParamToken = &pParamElem[1].pNode->exprToken;
      pExpr->base.numOfParams += 1;

      SVariant* pVar = &pExpr->base.param[0];
      if (functionId == FUNCTION_PERCT || functionId == FUNCTION_APERCT) {
        taosVariantCreate(pVar, pParamToken->z, pParamToken->n, TSDB_DATA_TYPE_DOUBLE);
2555 2556 2557 2558 2559 2560

        /*
         * sql function transformation
         * for dp = 0, it is actually min,
         * for dp = 100, it is max,
         */
2561 2562 2563
        if (pVar->d < 0 || pVar->d > TOP_BOTTOM_QUERY_LIMIT) {
          return buildInvalidOperationMsg(pMsgBuf, msg5);
        }
2564
      } else {
2565 2566
        taosVariantCreate(pVar, pParamToken->z, pParamToken->n, TSDB_DATA_TYPE_BIGINT);
        if (pVar->i <= 0 || pVar->i > 100) {  // todo use macro
2567 2568
          return buildInvalidOperationMsg(pMsgBuf, msg12);
        }
2569
      }
2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580

      return TSDB_CODE_SUCCESS;
    }

    case FUNCTION_TID_TAG: {
      pTableMetaInfo = getMetaInfo(pQueryInfo, 0);
      if (UTIL_TABLE_IS_NORMAL_TABLE(pTableMetaInfo)) {
        return buildInvalidOperationMsg(pMsgBuf, msg7);
      }

      // no parameters or more than one parameter for function
2581 2582
      if ((code = checkForkParam(pItem->pNode, 1, pMsgBuf)) != TSDB_CODE_SUCCESS) {
        return code;
2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617
      }

      tSqlExprItem* pParamItem = taosArrayGet(pItem->pNode->Expr.paramList, 0);
      tSqlExpr* pParam = pParamItem->pNode;

      SColumnIndex index = COLUMN_INDEX_INITIALIZER;
      if (getColumnIndexByName(&pParam->columnName, pQueryInfo, &index, pMsgBuf) != TSDB_CODE_SUCCESS) {
        return buildInvalidOperationMsg(pMsgBuf, msg3);
      }

      pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);
      SSchema* pSchema = getTableTagSchema(pTableMetaInfo->pTableMeta);

      // functions can not be applied to normal columns
      int32_t numOfCols = getNumOfColumns(pTableMetaInfo->pTableMeta);
      if (index.columnIndex < numOfCols && index.columnIndex != TSDB_TBNAME_COLUMN_INDEX) {
        return buildInvalidOperationMsg(pMsgBuf, msg6);
      }

      if (index.columnIndex > 0) {
        index.columnIndex -= numOfCols;
      }

      // 2. valid the column type
      int16_t colType = 0;
      if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
        colType = TSDB_DATA_TYPE_BINARY;
      } else {
        colType = pSchema[index.columnIndex].type;
      }

      if (colType == TSDB_DATA_TYPE_BOOL) {
        return buildInvalidOperationMsg(pMsgBuf, msg1);
      }

2618
      columnListInsert(pTableMetaInfo->tagColList, pTableMetaInfo->pTableMeta->uid, &pSchema[index.columnIndex], TSDB_COL_TAG);
2619 2620
      SSchema* pTagSchema = getTableTagSchema(pTableMetaInfo->pTableMeta);

2621
      SSchema s = (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX)? *getTbnameColumnSchema(): pTagSchema[index.columnIndex];
2622

2623 2624
      SResultDataInfo resInfo = {0};
      int32_t ret = getResultDataInfo(s.type, s.bytes, FUNCTION_TID_TAG, 0, &resInfo, 0, 0);
2625 2626
      assert(ret == TSDB_CODE_SUCCESS);

2627 2628 2629 2630 2631 2632
      SSchema result = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), s.name);
      SColumn c = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, index.type, &result);

      SSourceParam param = {0};
      addIntoSourceParam(&param, NULL, &c);

2633
      /*SExprInfo* pExpr = */doAddOneExprInfo(pQueryInfo, "tbid", &param, 0, pTableMetaInfo, &result, 0, s.name, true);
2634 2635 2636 2637 2638
      return TSDB_CODE_SUCCESS;
    }

    case FUNCTION_BLKINFO: {
      // no parameters or more than one parameter for function
2639 2640
      if ((code = checkForkParam(pItem->pNode, 0, pMsgBuf))!= TSDB_CODE_SUCCESS) {
        return code;
2641 2642
      }

2643
      SColumnIndex index = {.tableIndex = 0, .columnIndex = 0, .type = TSDB_COL_NORMAL};
2644 2645
      pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);

2646 2647
      SResultDataInfo resInfo = {0};
      getResultDataInfo(TSDB_DATA_TYPE_INT, 4, functionId, 0, &resInfo, 0, 0);
2648

2649 2650
      SSchema s = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), "block_dist");
      SSchema colSchema = {0};
2651

2652 2653
      char token[TSDB_COL_NAME_LEN] = {0};
      setTokenAndResColumnName(pItem, s.name, token, sizeof(s.name) - 1);
2654 2655 2656 2657 2658 2659

      SColumn c = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, index.type, &colSchema);

      SSourceParam param = {0};
      addIntoSourceParam(&param, NULL, &c);

H
Haojun Liao 已提交
2660
      SExprInfo* pExpr = doAddOneExprInfo(pQueryInfo, "block_dist", &param, colIndex, pTableMetaInfo, &s, resInfo.intermediateBytes, token, finalResult);
2661 2662 2663

      int64_t rowSize = pTableMetaInfo->pTableMeta->tableInfo.rowSize;
      addExprInfoParam(&pExpr->base, (char*) &rowSize, TSDB_DATA_TYPE_BIGINT, 8);
2664 2665 2666
      return TSDB_CODE_SUCCESS;
    }

2667 2668 2669 2670 2671 2672 2673 2674 2675
    case FUNCTION_COV: {
      // 1. valid the number of parameters
      // no parameters or more than one parameter for function
      if ((code = checkForkParam(pItem->pNode, 2, pMsgBuf)) != TSDB_CODE_SUCCESS) {
        return code;
      }

      tSqlExprItem* p1 = taosArrayGet(pItem->pNode->Expr.paramList, 0);
      tSqlExprItem* p2 = taosArrayGet(pItem->pNode->Expr.paramList, 1);
2676

2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721
      int32_t p1Type = p1->pNode->tokenId, p2Type = p2->pNode->tokenId;
      if (p1Type != TK_ID || p2Type != TK_ID) {
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }

      // validate the first parameter
      tExprNode* pNode1 = NULL;
      int32_t tokenId1 = p1->pNode->tokenId;
      SColumnIndex index1 = COLUMN_INDEX_INITIALIZER;
      SSchema columnSchema1 = {0};

      code = extractFunctionParameterInfo(pQueryInfo, tokenId1, &pTableMetaInfo, &columnSchema1, &pNode1, &index1, p1, pMsgBuf);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      // validate the second parameter
      tExprNode* pNode2 = NULL;
      int32_t tokenId2 = p1->pNode->tokenId;
      SColumnIndex index2 = COLUMN_INDEX_INITIALIZER;
      SSchema columnSchema2 = {0};
      code = extractFunctionParameterInfo(pQueryInfo, tokenId2, &pTableMetaInfo, &columnSchema2, &pNode2, &index2, p1, pMsgBuf);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      int32_t srcType1 = columnSchema1.type, srcType2 = columnSchema2.type;
      if (IS_VAR_DATA_TYPE(srcType1) || IS_VAR_DATA_TYPE(columnSchema2.type) || srcType1 == TSDB_DATA_TYPE_TIMESTAMP ||
      srcType1 == TSDB_DATA_TYPE_BOOL || srcType2 == TSDB_DATA_TYPE_TIMESTAMP || srcType2 == TSDB_DATA_TYPE_BOOL) {
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }

      SResultDataInfo resInfo = {.type = TSDB_DATA_TYPE_DOUBLE, .bytes = sizeof(double), .intermediateBytes = 0};
      SSchema s = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), "");

      char token[TSDB_COL_NAME_LEN] = {0};
      setTokenAndResColumnName(pItem, s.name, token, sizeof(s.name) - 1);

      SColumn c1 = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, index1.type, &columnSchema1);
      SColumn c2 = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, index2.type, &columnSchema2);

      SSourceParam param = {0};
      addIntoSourceParam(&param, pNode1, &c1);
      addIntoSourceParam(&param, pNode2, &c2);

2722 2723 2724 2725
      char funcName[FUNCTIONS_NAME_MAX_LENGTH] = {0};
      extractFunctionName(funcName, pItem);

      doAddOneExprInfo(pQueryInfo, funcName, &param, colIndex, pTableMetaInfo, &s, resInfo.intermediateBytes, token, finalResult);
2726 2727
      return TSDB_CODE_SUCCESS;
    }
2728

2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
    default: {
//      pUdfInfo = isValidUdf(pQueryInfo->pUdfInfo, pItem->pNode->Expr.operand.z, pItem->pNode->Expr.operand.n);
//      if (pUdfInfo == NULL) {
//        return buildInvalidOperationMsg(pMsgBuf, msg9);
//      }

      tSqlExprItem* pParamElem = taosArrayGet(pItem->pNode->Expr.paramList, 0);;
      if (pParamElem->pNode->tokenId != TK_ID) {
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }

      SColumnIndex index = COLUMN_INDEX_INITIALIZER;
      if (getColumnIndexByName(&pParamElem->pNode->columnName, pQueryInfo, &index, pMsgBuf) != TSDB_CODE_SUCCESS) {
        return buildInvalidOperationMsg(pMsgBuf, msg3);
      }

      if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
        return buildInvalidOperationMsg(pMsgBuf, msg6);
      }

      pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);

      // functions can not be applied to tags
      if (index.columnIndex >= getNumOfColumns(pTableMetaInfo->pTableMeta)) {
        return buildInvalidOperationMsg(pMsgBuf, msg6);
      }

2756 2757
      SResultDataInfo resInfo = {0};
      getResultDataInfo(TSDB_DATA_TYPE_INT, 4, functionId, 0, &resInfo, 0, false/*, pUdfInfo*/);
2758

2759 2760
      SSchema s = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), "");
      SSchema* colSchema = getOneColumnSchema(pTableMetaInfo->pTableMeta, index.tableIndex);
2761

2762 2763
      char token[TSDB_COL_NAME_LEN] = {0};
      setTokenAndResColumnName(pItem, s.name, token, sizeof(s.name) - 1);
2764 2765 2766 2767 2768 2769

      SColumn c = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, index.type, colSchema);

      SSourceParam param = {0};
      addIntoSourceParam(&param, NULL, &c);

2770 2771 2772
      char funcName[FUNCTIONS_NAME_MAX_LENGTH] = {0};
      extractFunctionName(funcName, pItem);
      doAddOneExprInfo(pQueryInfo, funcName, &param, colIndex, pTableMetaInfo, &s, resInfo.intermediateBytes, token, finalResult);
2773 2774 2775 2776 2777 2778 2779
      return TSDB_CODE_SUCCESS;
    }
  }

  return TSDB_CODE_TSC_INVALID_OPERATION;
}

2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
static int32_t validateExprLeafColumnNode(SQueryStmtInfo *pQueryInfo, SToken* pColumnName, SArray* pList, SMsgBuf* pMsgBuf) {
  SColumnIndex index = COLUMN_INDEX_INITIALIZER;
  if (getColumnIndexByName(pColumnName, pQueryInfo, &index, pMsgBuf) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

  // if column is timestamp not support arithmetic, so return invalid sql
  STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);
  STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;

  SSchema* pSchema = getOneColumnSchema(pTableMeta, index.columnIndex);
  if (pSchema->type == TSDB_DATA_TYPE_TIMESTAMP) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

2795
  SColumn c = createColumn(pTableMeta->uid, pTableMetaInfo->aliasName, index.type, pSchema);
2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813
  taosArrayPush(pList, &c);

  return TSDB_CODE_SUCCESS;
}

static int32_t validateExprLeafFunctionNode(SQueryStmtInfo* pQueryInfo, tSqlExpr* pExpr, SMsgBuf* pMsgBuf) {
  tSqlExprItem item = {.pNode = pExpr, .aliasName = NULL};

  // sql function list in selection clause.
  // Append the sqlExpr into exprList of pQueryInfo structure sequentially
  bool scalar = false;
  item.functionId = qIsBuiltinFunction(pExpr->Expr.operand.z, pExpr->Expr.operand.n, &scalar);
  if (item.functionId < 0) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

  int32_t outputIndex = (int32_t)getNumOfExprs(pQueryInfo);

2814 2815
  if (scalar) {
    printf("scalar function found!\n");
2816
//    if (addScalarExprAndResColumn(pQueryInfo, outputIndex, &item, pMsgBuf) != TSDB_CODE_SUCCESS) {
2817 2818 2819 2820 2821 2822
//      return TSDB_CODE_TSC_INVALID_OPERATION;
//    }
  } else {
    if (addAggExprAndResColumn(pQueryInfo, outputIndex, &item, false, pMsgBuf) != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }
2823

2824 2825 2826
    // It is invalid in case of more than one sqlExpr, such as first(ts, k) - last(ts, k)
    int32_t inc = (int32_t)getNumOfExprs(pQueryInfo) - outputIndex;
    if (inc > 1) {
2827 2828
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }
2829 2830 2831 2832 2833 2834 2835 2836 2837

    // Not supported data type in expression
    for (int32_t i = 0; i < inc; ++i) {
      SExprInfo* p1 = getExprInfo(pQueryInfo, i + outputIndex);
      int16_t    t = p1->base.resSchema.type;
      if (t == TSDB_DATA_TYPE_TIMESTAMP) {
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }
    }
2838 2839 2840 2841 2842
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
2843
static int32_t validateScalarFunctionParamNum(tSqlExpr* pSqlExpr, int32_t functionId, SMsgBuf* pMsgBuf) {
2844
  int32_t code = TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2845
  switch (functionId) {
2846
    case FUNCTION_CEIL: {
H
Haojun Liao 已提交
2847
      code = checkForkParam(pSqlExpr, 1, pMsgBuf);
2848 2849 2850
      break;
    }
    case FUNCTION_LENGTH: {
H
Haojun Liao 已提交
2851
      code = checkForkParam(pSqlExpr, 1, pMsgBuf);
2852 2853 2854 2855 2856 2857 2858
      break;
    }
  }

  return code;
}

2859
// todo merge with the addScalarExprAndResColumn
H
Haojun Liao 已提交
2860
int32_t doAddOneProjectCol(SQueryStmtInfo* pQueryInfo, int32_t outputColIndex, SSchema* pSchema, const char* aliasName,
2861
                        int32_t colId, SMsgBuf* pMsgBuf) {
2862 2863
  const char* name = (aliasName == NULL)? pSchema->name:aliasName;
  SSchema s = createSchema(pSchema->type, pSchema->bytes, colId, name);
2864

2865
  SArray* pColumnList = taosArrayInit(4, sizeof(SColumn));
H
Haojun Liao 已提交
2866
  SToken colNameToken = {.z = pSchema->name, .n = strlen(pSchema->name)};
2867

2868 2869 2870 2871
  tSqlExpr sqlNode = {0};
  sqlNode.type = SQL_NODE_TABLE_COLUMN;
  sqlNode.columnName = colNameToken;

2872 2873 2874
  tExprNode* pNode = NULL;
  bool       keepTableCols = true;
  int32_t    ret = sqlExprToExprNode(&pNode, &sqlNode, pQueryInfo, pColumnList, &keepTableCols, pMsgBuf);
2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885
  if (ret != TSDB_CODE_SUCCESS) {
    tExprTreeDestroy(pNode, NULL);
    return buildInvalidOperationMsg(pMsgBuf, "invalid expression in select clause");
  }

  SExprInfo* pExpr = createBinaryExprInfo(pNode, &s);
  tstrncpy(pExpr->base.resSchema.name, name, tListLen(pExpr->base.resSchema.name));
  tstrncpy(pExpr->base.token, name, tListLen(pExpr->base.token));

  SArray*    pExprList = getCurrentExprList(pQueryInfo);
  addExprInfo(pExprList, outputColIndex, pExpr, pQueryInfo->exprListLevelIndex);
2886

2887 2888 2889 2890 2891 2892 2893 2894 2895
  // extract columns according to the tExprNode tree
  size_t num = taosArrayGetSize(pColumnList);
  pExpr->base.pColumns = calloc(num, sizeof(SColumn));
  for (int32_t i = 0; i < num; ++i) {
    SColumn* pCol = taosArrayGet(pColumnList, i);
    pExpr->base.pColumns[i] = *pCol;
  }

  pExpr->base.numOfCols = num;
2896 2897 2898 2899 2900 2901

  if (pQueryInfo->exprListLevelIndex == 0) {
    int32_t exists = getNumOfFields(&pQueryInfo->fieldsInfo);
    addResColumnInfo(pQueryInfo, exists, &pExpr->base.resSchema, pExpr);
  }

2902
  pQueryInfo->info.projectionQuery = true;
2903
  return TSDB_CODE_SUCCESS;
2904 2905
}

H
Haojun Liao 已提交
2906
static int32_t doAddMultipleProjectExprAndResColumns(SQueryStmtInfo* pQueryInfo, SColumnIndex* pIndex, int32_t startPos, SMsgBuf* pMsgBuf) {
2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917
  STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, pIndex->tableIndex);

  STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;
  STableComInfo tinfo = getTableInfo(pTableMeta);

  int32_t numOfTotalColumns = tinfo.numOfColumns;
  if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
    numOfTotalColumns += tinfo.numOfTags;
  }

  for (int32_t j = 0; j < numOfTotalColumns; ++j) {
2918
    SSchema* pSchema = getOneColumnSchema(pTableMetaInfo->pTableMeta, j);
H
Haojun Liao 已提交
2919
    doAddOneProjectCol(pQueryInfo, startPos + j, pSchema, NULL, getNewResColId(), pMsgBuf);
2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956
  }

  return numOfTotalColumns;
}

// User input constant value as a new result column
static SColumnIndex createConstantColumnIndex(int32_t* colId) {
  SColumnIndex index = COLUMN_INDEX_INITIALIZER;
  index.columnIndex = ((*colId)--);
  index.tableIndex = 0;
  index.type = TSDB_COL_UDC;
  return index;
}

static SSchema createConstantColumnSchema(SVariant* pVal, const SToken* exprStr, const char* name) {
  SSchema s = {0};

  s.type  = pVal->nType;
  if (IS_VAR_DATA_TYPE(s.type)) {
    s.bytes = (int16_t)(pVal->nLen + VARSTR_HEADER_SIZE);
  } else {
    s.bytes = tDataTypes[pVal->nType].bytes;
  }

  s.colId = TSDB_UD_COLUMN_INDEX;

  if (name != NULL) {
    tstrncpy(s.name, name, sizeof(s.name));
  } else {
    size_t tlen = MIN(sizeof(s.name), exprStr->n + 1);
    tstrncpy(s.name, exprStr->z, tlen);
    strdequote(s.name);
  }

  return s;
}

2957
static int32_t handleTbnameProjection(SQueryStmtInfo* pQueryInfo, tSqlExprItem* pItem, SColumnIndex* pIndex, int32_t startPos, bool outerQuery, SMsgBuf* pMsgBuf) {
2958
  const char* msg1 = "tbname not allowed in outer query";
2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976

  SSchema colSchema = {0};
  if (outerQuery) {  // todo??
    STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, pIndex->tableIndex);

    bool     existed = false;
    SSchema* pSchema = pTableMetaInfo->pTableMeta->schema;

    int32_t numOfCols = getNumOfColumns(pTableMetaInfo->pTableMeta);
    for (int32_t i = 0; i < numOfCols; ++i) {
      if (strncasecmp(pSchema[i].name, TSQL_TBNAME_L, tListLen(pSchema[i].name)) == 0) {
        existed = true;
        pIndex->columnIndex = i;
        break;
      }
    }

    if (!existed) {
2977
      return buildInvalidOperationMsg(pMsgBuf, msg1);
2978 2979 2980 2981 2982 2983 2984
    }

    colSchema = pSchema[pIndex->columnIndex];
  } else {
    colSchema = *getTbnameColumnSchema();
  }

H
Haojun Liao 已提交
2985
  return doAddOneProjectCol(pQueryInfo, startPos, &colSchema, pItem->aliasName, getNewResColId(), pMsgBuf);
2986 2987
}

2988 2989 2990 2991
int32_t addProjectionExprAndResColumn(SQueryStmtInfo* pQueryInfo, tSqlExprItem* pItem, bool outerQuery, SMsgBuf* pMsgBuf) {
  const char* msg1 = "tag for normal table query is not allowed";
  const char* msg2 = "invalid column name";

2992 2993 2994 2995
  if (checkForAliasName(pMsgBuf, pItem->aliasName) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

2996
  int32_t startPos = (int32_t)getNumOfExprs(pQueryInfo);
2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009
  int32_t tokenId = pItem->pNode->tokenId;
  if (tokenId == TK_ALL) {  // project on all fields
    TSDB_QUERY_SET_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_PROJECTION_QUERY);

    SColumnIndex index = COLUMN_INDEX_INITIALIZER;
    if (getTableIndexByName(&pItem->pNode->columnName, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
      return buildInvalidOperationMsg(pMsgBuf, msg2);
    }

    // all columns are required
    if (index.tableIndex == COLUMN_INDEX_INITIAL_VAL) {  // all table columns are required.
      for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
        index.tableIndex = i;
H
Haojun Liao 已提交
3010
        int32_t inc = doAddMultipleProjectExprAndResColumns(pQueryInfo, &index, startPos, pMsgBuf);
3011
        startPos += inc;
3012 3013
      }
    } else {
H
Haojun Liao 已提交
3014
      doAddMultipleProjectExprAndResColumns(pQueryInfo, &index, startPos, pMsgBuf);
3015 3016
    }

3017
    // add the primary timestamp column even though it is not required by user
3018
    STableMeta* pTableMeta = getMetaInfo(pQueryInfo, index.tableIndex)->pTableMeta;
3019
    if (pTableMeta->tableType != TSDB_TEMP_TABLE) {
3020
      insertPrimaryTsColumn(pQueryInfo->colList, pTableMeta->schema[0].name, pTableMeta->uid);
3021
    }
3022
  } else if (tokenId == TK_STRING || tokenId == TK_INTEGER || tokenId == TK_FLOAT) {  //constant value column
3023 3024
    SColumnIndex index = createConstantColumnIndex(&pQueryInfo->udColumnId);
    SSchema colSchema = createConstantColumnSchema(&pItem->pNode->value, &pItem->pNode->exprToken, pItem->aliasName);
3025

3026 3027
    char token[TSDB_COL_NAME_LEN] = {0};
    tstrncpy(token, pItem->pNode->exprToken.z, MIN(TSDB_COL_NAME_LEN, TSDB_COL_NAME_LEN));
3028

3029 3030 3031 3032 3033 3034
    STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);
    SColumn c = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, index.type, &colSchema);

    SSourceParam param = {0};
    addIntoSourceParam(&param, NULL, &c);

3035
    SExprInfo* pExpr = doAddOneExprInfo(pQueryInfo, "project", &param, startPos, pTableMetaInfo, &colSchema, 0, token, true);
3036 3037 3038
    // NOTE: the first parameter is reserved for the tag column id during join query process.
    pExpr->base.numOfParams = 2;
    taosVariantAssign(&pExpr->base.param[1], &pItem->pNode->value);
3039
  } else if (tokenId == TK_ID) {  // column name
3040 3041 3042 3043 3044 3045
    SColumnIndex index = COLUMN_INDEX_INITIALIZER;
    if (getColumnIndexByName(&pItem->pNode->columnName, pQueryInfo, &index, pMsgBuf) != TSDB_CODE_SUCCESS) {
      return buildInvalidOperationMsg(pMsgBuf, msg2);
    }

    if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
3046
      handleTbnameProjection(pQueryInfo, pItem, &index, startPos, outerQuery, pMsgBuf);
3047 3048 3049 3050 3051 3052
    } else {
      STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);
      if (TSDB_COL_IS_TAG(index.type) && UTIL_TABLE_IS_NORMAL_TABLE(pTableMetaInfo)) {
        return buildInvalidOperationMsg(pMsgBuf, msg1);
      }

3053
      SSchema* pSchema = getOneColumnSchema(pTableMetaInfo->pTableMeta, index.columnIndex);
H
Haojun Liao 已提交
3054
      doAddOneProjectCol(pQueryInfo, startPos, pSchema, pItem->aliasName, getNewResColId(), pMsgBuf);
3055
    }
3056 3057 3058 3059

    // add the primary timestamp column even though it is not required by user
    STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);
    if (!UTIL_TABLE_IS_TMP_TABLE(pTableMetaInfo)) {
3060 3061
      STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;
      insertPrimaryTsColumn(pQueryInfo->colList, pTableMeta->schema[0].name, pTableMeta->uid);
3062 3063 3064
    }
  } else {
    return TSDB_CODE_TSC_INVALID_OPERATION;
3065 3066
  }

3067 3068 3069
  return TSDB_CODE_SUCCESS;
}

3070
static int32_t validateExprLeafNode(tSqlExpr* pExpr, SQueryStmtInfo* pQueryInfo, SArray* pList, int32_t* type, SMsgBuf* pMsgBuf) {
3071 3072 3073 3074 3075
  if (pExpr->type == SQL_NODE_TABLE_COLUMN) {
    if (*type == NON_ARITHMEIC_EXPR) {
      *type = NORMAL_ARITHMETIC;
    } else if (*type == AGG_ARIGHTMEIC) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
3076
    }
3077

3078 3079 3080
    int32_t code = validateExprLeafColumnNode(pQueryInfo, &pExpr->columnName, pList, pMsgBuf);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
3081
    }
3082 3083 3084 3085 3086 3087 3088 3089 3090 3091
  } else if ((pExpr->tokenId == TK_FLOAT && (isnan(pExpr->value.d) || isinf(pExpr->value.d))) ||
             pExpr->tokenId == TK_NULL) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  } else if (pExpr->type == SQL_NODE_SQLFUNCTION) {
    if (*type == NON_ARITHMEIC_EXPR) {
      *type = AGG_ARIGHTMEIC;
    } else if (*type == NORMAL_ARITHMETIC) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

3092 3093 3094
    int32_t code = validateExprLeafFunctionNode(pQueryInfo, pExpr, pMsgBuf);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
3095 3096 3097
    }
  }

3098 3099
  return TSDB_CODE_SUCCESS;
}
3100

3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128
static uint64_t findTmpSourceColumnInNextLevel(SQueryStmtInfo* pQueryInfo, tExprNode *pExpr) {
  // This function must be a aggregate function, so it must be in the next level
  pQueryInfo->exprListLevelIndex += 1;

  // set the input column data byte and type.
  SArray* pExprList = getCurrentExprList(pQueryInfo);

  bool found = false;
  uint64_t uid = 0;

  size_t size = taosArrayGetSize(pExprList);
  for (int32_t i = 0; i < size; ++i) {
    SExprInfo* p1 = taosArrayGetP(pExprList, i);

    if (strcmp((pExpr)->pSchema->name, p1->base.resSchema.name) == 0) {
      memcpy((pExpr)->pSchema, &p1->base.resSchema, sizeof(SSchema));
      found = true;
      uid = p1->base.pColumns->uid;
      break;
    }
  }

  assert(found);
  pQueryInfo->exprListLevelIndex -= 1;

  return uid;
}

3129 3130 3131 3132 3133 3134
static tExprNode* doCreateColumnNode(SQueryStmtInfo* pQueryInfo, SColumnIndex* pIndex, bool keepTableCols, SArray* pCols) {
  STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, pIndex->tableIndex);
  STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;

  tExprNode* pExpr = calloc(1, sizeof(tExprNode));

3135 3136
  pExpr->nodeType = TEXPR_COL_NODE;
  pExpr->pSchema  = calloc(1, sizeof(SSchema));
3137 3138 3139 3140 3141 3142 3143 3144

  SSchema* pSchema = NULL;
  if (pIndex->columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
    pSchema = getTbnameColumnSchema();
  } else {
    pSchema = getOneColumnSchema(pTableMeta, pIndex->columnIndex);
  }

3145 3146
  *(SSchema*)(pExpr->pSchema) = *pSchema;

3147
  if (keepTableCols && TSDB_COL_IS_NORMAL_COL(pIndex->type)) {
3148 3149 3150 3151
    SColumn c = createColumn(pTableMeta->uid, pTableMetaInfo->aliasName, pIndex->type, pExpr->pSchema);
    taosArrayPush(pCols, &c);
  }

3152 3153 3154 3155 3156 3157 3158 3159
  if (TSDB_COL_IS_NORMAL_COL(pIndex->type)) {
    columnListInsert(pQueryInfo->colList, pTableMeta->uid, pSchema, TSDB_COL_NORMAL);
    SSchema* pTsSchema = getOneColumnSchema(pTableMeta, 0);
    insertPrimaryTsColumn(pQueryInfo->colList, pTsSchema->name, pTableMeta->uid);
  } else {
    columnListInsert(pTableMetaInfo->tagColList, pTableMeta->uid, pSchema, TSDB_COL_TAG);
  }

3160 3161 3162
  return pExpr;
}

3163
static SExprInfo* createColumnNodeFromAggFunc(SSchema* pSchema) {
3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179
  tExprNode* pExprNode = calloc(1, sizeof(tExprNode));

  pExprNode->nodeType = TEXPR_COL_NODE;
  pExprNode->pSchema  = calloc(1, sizeof(SSchema));
  *(SSchema*)(pExprNode->pSchema) = *pSchema;

  SExprInfo* pExpr = calloc(1, sizeof(SExprInfo));
  if (pExpr == NULL) {
    return NULL;
  }

  pExpr->pExpr = pExprNode;
  memcpy(&pExpr->base.resSchema, pSchema, sizeof(SSchema));
  return pExpr;
}

3180 3181
static int32_t validateSqlExpr(const tSqlExpr* pSqlExpr, SQueryStmtInfo *pQueryInfo, SMsgBuf* pMsgBuf);

3182
static int32_t doProcessFunctionLeafNodeParam(SQueryStmtInfo* pQueryInfo, int32_t* num, tExprNode*** p, SArray* pCols,
3183 3184 3185 3186
                                              bool* keepTableCols, const tSqlExpr* pSqlExpr, SMsgBuf* pMsgBuf) {
  SArray* pParamList = pSqlExpr->Expr.paramList;
  if (pParamList != NULL) {
    *num = taosArrayGetSize(pParamList);
3187
    (*p) = calloc((*num), POINTER_BYTES);
3188 3189 3190 3191 3192 3193 3194 3195 3196

    for (int32_t i = 0; i < (*num); ++i) {
      tSqlExprItem* pItem = taosArrayGet(pParamList, i);

      int32_t ret = validateSqlExpr(pItem->pNode, pQueryInfo, pMsgBuf);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }

3197
      int32_t code = sqlExprToExprNode(&(*p)[i], pItem->pNode, pQueryInfo, pCols, keepTableCols, pMsgBuf);
3198 3199 3200 3201 3202 3203 3204 3205 3206 3207
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
    }
  } else { // handle the case: count(*) + 22
    if (strncasecmp(pSqlExpr->Expr.operand.z, "count", pSqlExpr->Expr.operand.n) != 0) {
      return buildInvalidOperationMsg(pMsgBuf, "invalid expression");
    }

    *num = 1;
3208
    (*p) = calloc(*num, POINTER_BYTES);
3209 3210

    SColumnIndex index = {.type = TSDB_COL_NORMAL, .tableIndex = 0, .columnIndex = 0};
3211
    (*p)[0] = doCreateColumnNode(pQueryInfo, &index, *keepTableCols, pCols);
3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246
  }

  return TSDB_CODE_SUCCESS;
}

static int32_t doValidateExpr(SQueryStmtInfo *pQueryInfo, tSqlExpr* pFuncNode, tSqlExpr* pTableColumnNode, SMsgBuf* pMsgBuf) {
  char token[FUNCTIONS_NAME_MAX_LENGTH] = {0};
  strncpy(token, pFuncNode->Expr.operand.z, pFuncNode->Expr.operand.n);
  bool isAgg = qIsAggregateFunction(token);

  // count(*) + column is a invalid expression.
  if (isAgg) {
    return buildInvalidOperationMsg(pMsgBuf, "invalid expression");
  }
  return TSDB_CODE_SUCCESS;
}

int32_t validateSqlExpr(const tSqlExpr* pSqlExpr, SQueryStmtInfo *pQueryInfo, SMsgBuf* pMsgBuf) {
  assert(pSqlExpr);

  if (pSqlExpr->type == SQL_NODE_EXPR) {
    int32_t valid = validateSqlExpr(pSqlExpr->pLeft, pQueryInfo, pMsgBuf);
    if (valid != TSDB_CODE_SUCCESS) {
      return valid;
    }

    valid = validateSqlExpr(pSqlExpr->pRight, pQueryInfo, pMsgBuf);
    if (valid != TSDB_CODE_SUCCESS) {
      return valid;
    }

    tSqlExpr* pLeft = pSqlExpr->pLeft, *pRight = pSqlExpr->pRight;
    if (pLeft->type == SQL_NODE_SQLFUNCTION && pRight->type == SQL_NODE_SQLFUNCTION) {

      char token[FUNCTIONS_NAME_MAX_LENGTH] = {0};
3247
      strncpy(token, pLeft->Expr.operand.z, pLeft->Expr.operand.n);
3248 3249
      bool agg1 = qIsAggregateFunction(token);

3250
      strncpy(token, pRight->Expr.operand.z, pRight->Expr.operand.n);
3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270
      bool agg2 = qIsAggregateFunction(token);

      if (agg1 != agg2) {
        return buildInvalidOperationMsg(pMsgBuf, "invalid expression");
      }
    }

    if (pLeft->type == SQL_NODE_SQLFUNCTION && pRight->type == SQL_NODE_TABLE_COLUMN) {
      int32_t code = doValidateExpr(pQueryInfo, pLeft, pRight, pMsgBuf);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
    } else if (pRight->type == SQL_NODE_SQLFUNCTION && pLeft->type == SQL_NODE_TABLE_COLUMN) {
      int32_t code = doValidateExpr(pQueryInfo, pRight, pLeft, pMsgBuf);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
    }

    int32_t tokenId = pSqlExpr->tokenId;
H
Haojun Liao 已提交
3271 3272
    if (pRight->type == SQL_NODE_VALUE && (pRight->value.nType == TSDB_DATA_TYPE_DOUBLE || pRight->value.nType == TSDB_DATA_TYPE_INT) &&
    pRight->value.d == 0 && tokenId == TK_DIVIDE) {
3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289
      return buildInvalidOperationMsg(pMsgBuf, "invalid expression (divided by 0)");
    }

    if (tokenId == TK_DIVIDE || tokenId == TK_TIMES || tokenId == TK_MINUS || tokenId == TK_PLUS || tokenId == TK_MODULES) {
      if ((pRight->type == SQL_NODE_VALUE && pRight->value.nType == TSDB_DATA_TYPE_BINARY) ||
          (pLeft->type == SQL_NODE_VALUE && pLeft->value.nType == TSDB_DATA_TYPE_BINARY)) {
        return buildInvalidOperationMsg(pMsgBuf, "invalid expression (string in arithmetic expression)");
      }
    }

  } else if (pSqlExpr->type == SQL_NODE_TABLE_COLUMN) {
    SColumnIndex index = COLUMN_INDEX_INITIALIZER;

    int32_t ret = getColumnIndexByName(&pSqlExpr->columnName, pQueryInfo, &index, pMsgBuf);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
H
Haojun Liao 已提交
3290 3291 3292 3293 3294 3295 3296 3297 3298
  } else if (pSqlExpr->type == SQL_NODE_SQLFUNCTION) {
    bool    scalar = false;
    int32_t functionId = qIsBuiltinFunction(pSqlExpr->Expr.operand.z, pSqlExpr->Expr.operand.n, &scalar);
    if (functionId < 0) {
      return buildInvalidOperationMsg(pMsgBuf, "invalid function name");
    }

    // do check the parameter number for scalar function
    if (scalar) {
3299
      int32_t ret = validateScalarFunctionParamNum((tSqlExpr*) pSqlExpr, functionId, pMsgBuf);
H
Haojun Liao 已提交
3300 3301 3302 3303
      if (ret != TSDB_CODE_SUCCESS) {
        return buildInvalidOperationMsg(pMsgBuf, "invalid number of function parameters");
      }
    }
3304 3305 3306 3307 3308 3309
  }

  return TSDB_CODE_SUCCESS;
}

int32_t sqlExprToExprNode(tExprNode **pExpr, const tSqlExpr* pSqlExpr, SQueryStmtInfo* pQueryInfo, SArray* pCols, bool* keepTableCols, SMsgBuf* pMsgBuf) {
3310 3311 3312
  tExprNode* pLeft = NULL;
  tExprNode* pRight= NULL;

3313 3314 3315
  SColumnIndex index = COLUMN_INDEX_INITIALIZER;
  if (pSqlExpr->type == SQL_NODE_EXPR) {
    if (pSqlExpr->pLeft != NULL) {
3316
      int32_t ret = sqlExprToExprNode(&pLeft, pSqlExpr->pLeft, pQueryInfo, pCols, keepTableCols, pMsgBuf);
3317 3318 3319
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }
3320 3321
    }

3322
    if (pSqlExpr->pRight != NULL) {
3323
      int32_t ret = sqlExprToExprNode(&pRight, pSqlExpr->pRight, pQueryInfo, pCols, keepTableCols, pMsgBuf);
3324 3325 3326 3327
      if (ret != TSDB_CODE_SUCCESS) {
        tExprTreeDestroy(pLeft, NULL);
        return ret;
      }
3328 3329
    }

3330 3331 3332
    if (pSqlExpr->pLeft == NULL && pSqlExpr->pRight == NULL && pSqlExpr->tokenId == 0) {
      *pExpr = calloc(1, sizeof(tExprNode));
      return TSDB_CODE_SUCCESS;
3333
    }
3334
 } else if (pSqlExpr->type == SQL_NODE_SQLFUNCTION) {
3335 3336 3337 3338 3339
    bool    scalar = false;
    int32_t functionId = qIsBuiltinFunction(pSqlExpr->Expr.operand.z, pSqlExpr->Expr.operand.n, &scalar);
    if (functionId < 0) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }
3340

3341
    if (!scalar) {
3342
      pQueryInfo->exprListLevelIndex += 1;
3343
    }
3344

3345
    *keepTableCols = false;
3346

3347 3348
    int32_t num = 0;
    tExprNode** p = NULL;
3349
    int32_t code = doProcessFunctionLeafNodeParam(pQueryInfo, &num, &p, pCols, keepTableCols, pSqlExpr, pMsgBuf);
3350 3351 3352
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
3353

3354
    int32_t outputIndex = (int32_t)getNumOfExprs(pQueryInfo);
3355

3356 3357
    if (scalar) {
      printf("scalar function found! %s\n", pSqlExpr->exprToken.z);
3358

3359 3360 3361
      // Expression on the results of aggregation functions
      *pExpr = calloc(1, sizeof(tExprNode));
      (*pExpr)->nodeType = TEXPR_FUNCTION_NODE;
3362

3363 3364 3365 3366 3367 3368 3369 3370 3371
      (*pExpr)->_function.pChild = p;
      (*pExpr)->_function.num = num;
      strncpy((*pExpr)->_function.functionName, pSqlExpr->Expr.operand.z, pSqlExpr->Expr.operand.n);
      return TSDB_CODE_SUCCESS;
    } else {
      printf("agg function found, %s\n", pSqlExpr->exprToken.z);
      tSqlExprItem item = {.pNode = (tSqlExpr*)pSqlExpr, .aliasName = NULL, .functionId = functionId};
      if (addAggExprAndResColumn(pQueryInfo, outputIndex, &item, false, pMsgBuf) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_TSC_INVALID_OPERATION;
3372
      }
3373 3374 3375

      pQueryInfo->exprListLevelIndex -= 1;
      // convert the aggregate function to be the input data columns for the outer function.
3376
    }
3377
  }
3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402

  if (pSqlExpr->pLeft == NULL) {  // it is the leaf node
    assert(pSqlExpr->pRight == NULL);

    if (pSqlExpr->type == SQL_NODE_VALUE) {
      int32_t ret = TSDB_CODE_SUCCESS;
      *pExpr = calloc(1, sizeof(tExprNode));
      (*pExpr)->nodeType = TEXPR_VALUE_NODE;
      (*pExpr)->pVal = calloc(1, sizeof(SVariant));
      taosVariantAssign((*pExpr)->pVal, &pSqlExpr->value);

      STableMeta* pTableMeta = getMetaInfo(pQueryInfo, 0)->pTableMeta;
      if (pCols != NULL && taosArrayGetSize(pCols) > 0) {
        SColIndex* idx = taosArrayGet(pCols, 0);
        SSchema* pSchema = getOneColumnSchema(pTableMeta, idx->colIndex);

        // convert time by precision
        if (pSchema != NULL && TSDB_DATA_TYPE_TIMESTAMP == pSchema->type && TSDB_DATA_TYPE_BINARY == (*pExpr)->pVal->nType) {
#if 0
          ret = setColumnFilterInfoForTimestamp(pCmd, pQueryInfo, (*pExpr)->pVal);
#endif
        }
      }
      return ret;
    } else if (pSqlExpr->type == SQL_NODE_SQLFUNCTION) {
3403
      // Expression on the results of aggregation functions
3404 3405 3406 3407 3408
      *pExpr = calloc(1, sizeof(tExprNode));
      (*pExpr)->nodeType = TEXPR_COL_NODE;
      (*pExpr)->pSchema = calloc(1, sizeof(SSchema));
      strncpy((*pExpr)->pSchema->name, pSqlExpr->exprToken.z, pSqlExpr->exprToken.n);

3409 3410 3411
      // it must be the aggregate function
      assert(qIsAggregateFunction((*pExpr)->pSchema->name));

3412 3413 3414
      uint64_t uid = findTmpSourceColumnInNextLevel(pQueryInfo, *pExpr);
      if (!(*keepTableCols)) {
        SColumn c = createColumn(uid, NULL, TSDB_COL_TMP, (*pExpr)->pSchema);
3415 3416 3417
        taosArrayPush(pCols, &c);
      }
    } else if (pSqlExpr->type == SQL_NODE_TABLE_COLUMN) { // column name, normal column expression
3418 3419 3420 3421 3422
      int32_t ret = getColumnIndexByName(&pSqlExpr->columnName, pQueryInfo, &index, pMsgBuf);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }

3423
      *pExpr = doCreateColumnNode(pQueryInfo, &index, *keepTableCols, pCols);
3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459
      return TSDB_CODE_SUCCESS;
    } else if (pSqlExpr->tokenId == TK_SET) {
      int32_t colType = -1;
      STableMeta* pTableMeta = getMetaInfo(pQueryInfo, pQueryInfo->curTableIdx)->pTableMeta;
      if (pCols != NULL) {
        size_t colSize = taosArrayGetSize(pCols);

        if (colSize > 0) {
          SColIndex* idx = taosArrayGet(pCols, colSize - 1);
          SSchema* pSchema = getOneColumnSchema(pTableMeta, idx->colIndex);
          if (pSchema != NULL) {
            colType = pSchema->type;
          }
        }
      }

      SVariant *pVal;
      if (colType >= TSDB_DATA_TYPE_TINYINT && colType <= TSDB_DATA_TYPE_BIGINT) {
        colType = TSDB_DATA_TYPE_BIGINT;
      } else if (colType == TSDB_DATA_TYPE_FLOAT || colType == TSDB_DATA_TYPE_DOUBLE) {
        colType = TSDB_DATA_TYPE_DOUBLE;
      }
      STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, pQueryInfo->curTableIdx);
      STableComInfo tinfo = getTableInfo(pTableMetaInfo->pTableMeta);
#if 0
      if (serializeExprListToVariant(pSqlExpr->Expr.paramList, &pVal, colType, tinfo.precision) == false) {
        return buildInvalidOperationMsg(pMsgBuf, "not support filter expression");
      }
#endif
      *pExpr = calloc(1, sizeof(tExprNode));
      (*pExpr)->nodeType = TEXPR_VALUE_NODE;
      (*pExpr)->pVal = pVal;
    } else {
      return buildInvalidOperationMsg(pMsgBuf, "not support filter expression");
    }
  } else {
H
Haojun Liao 已提交
3460
    *pExpr = (tExprNode*)calloc(1, sizeof(tExprNode));
3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473
    (*pExpr)->nodeType = TEXPR_BINARYEXPR_NODE;

    (*pExpr)->_node.pLeft = pLeft;
    (*pExpr)->_node.pRight = pRight;

    SToken t = {.type = pSqlExpr->tokenId};
    (*pExpr)->_node.optr = convertRelationalOperator(&t);

    assert((*pExpr)->_node.optr != 0);
  }
  return TSDB_CODE_SUCCESS;
}

3474
static int32_t addScalarExprAndResColumn(SQueryStmtInfo* pQueryInfo, int32_t exprIndex, tSqlExprItem* pItem, SMsgBuf* pMsgBuf) {
3475
  SArray* pColumnList = taosArrayInit(4, sizeof(SColumn));
3476
  SSchema s = createSchema(TSDB_DATA_TYPE_DOUBLE, sizeof(double), getNewResColId(), "");
3477

3478 3479 3480 3481 3482
  int32_t ret = validateSqlExpr(pItem->pNode, pQueryInfo, pMsgBuf);
  if (ret != TSDB_CODE_SUCCESS) {
    return ret;
  }

3483
  tExprNode* pNode = NULL;
3484
  bool       keepTableCols = true;
3485
  ret = sqlExprToExprNode(&pNode, pItem->pNode, pQueryInfo, pColumnList, &keepTableCols, pMsgBuf);
3486 3487 3488 3489
  if (ret != TSDB_CODE_SUCCESS) {
    tExprTreeDestroy(pNode, NULL);
    return buildInvalidOperationMsg(pMsgBuf, "invalid expression in select clause");
  }
3490

3491 3492 3493
  SExprInfo* pExpr = createBinaryExprInfo(pNode, &s);
  setTokenAndResColumnName(pItem, pExpr->base.resSchema.name, pExpr->base.token, TSDB_COL_NAME_LEN);

3494 3495
  SArray*    pExprList = getCurrentExprList(pQueryInfo);
  addExprInfo(pExprList, exprIndex, pExpr, pQueryInfo->exprListLevelIndex);
3496

3497 3498 3499 3500 3501 3502 3503
  // extract columns according to the tExprNode tree
  size_t num = taosArrayGetSize(pColumnList);
  pExpr->base.pColumns = calloc(num, sizeof(SColumn));
  for (int32_t i = 0; i < num; ++i) {
    SColumn* pCol = taosArrayGet(pColumnList, i);
    pExpr->base.pColumns[i] = *pCol;
  }
3504

3505
  pExpr->base.numOfCols = num;
3506

3507 3508 3509 3510 3511 3512 3513 3514 3515
  pExpr->base.numOfParams = 1;
  SBufferWriter bw = tbufInitWriter(NULL, false);
  //    TRY(0) {
  exprTreeToBinary(&bw, pExpr->pExpr);
  //    } CATCH(code) {
  //      tbufCloseWriter(&bw);
  //      UNUSED(code);
  //       TODO: other error handling
  //    } END_TRY
3516

3517 3518 3519 3520
  SSqlExpr* pSqlExpr = &pExpr->base;
  pSqlExpr->param[0].nLen = (int16_t)tbufTell(&bw);
  pSqlExpr->param[0].pz = tbufGetData(&bw, true);
  pSqlExpr->param[0].nType = TSDB_DATA_TYPE_BINARY;
3521

3522
  tbufCloseWriter(&bw);
3523

H
Haojun Liao 已提交
3524 3525 3526 3527 3528
  if (pQueryInfo->exprListLevelIndex == 0) {
    int32_t exists = getNumOfFields(&pQueryInfo->fieldsInfo);
    addResColumnInfo(pQueryInfo, exists, &pExpr->base.resSchema, pExpr);
  }

3529
  //    tbufCloseWriter(&bw); // TODO there is a memory leak
3530

3531
  taosArrayDestroy(pColumnList);
3532 3533 3534 3535 3536 3537 3538 3539 3540
  return TSDB_CODE_SUCCESS;
}

int32_t validateSelectNodeList(SQueryStmtInfo* pQueryInfo, SArray* pSelNodeList, bool outerQuery, SMsgBuf* pMsgBuf) {
  assert(pSelNodeList != NULL);

  const char* msg1 = "too many items in selection clause";
  const char* msg2 = "functions or others can not be mixed up";
  const char* msg3 = "not support query expression";
H
Haojun Liao 已提交
3541
  const char* msg4 = "distinct should be in the first place in select clause";
3542 3543 3544 3545 3546 3547 3548
  const char* msg5 = "invalid function name";

  // too many result columns not support order by in query
  if (taosArrayGetSize(pSelNodeList) > TSDB_MAX_COLUMNS) {
    return buildInvalidOperationMsg(pMsgBuf, msg1);
  }

3549 3550
  int32_t code = TSDB_CODE_SUCCESS;
  size_t  numOfExpr = taosArrayGetSize(pSelNodeList);
3551 3552

  for (int32_t i = 0; i < numOfExpr; ++i) {
3553
    int32_t outputIndex = (int32_t) getNumOfExprs(pQueryInfo);
3554 3555 3556 3557
    tSqlExprItem* pItem = taosArrayGet(pSelNodeList, i);
    int32_t type = pItem->pNode->type;

    if (pItem->distinct) {
3558
      if (i != 0 || type == SQL_NODE_SQLFUNCTION || type == SQL_NODE_EXPR) {
3559 3560 3561
        return buildInvalidOperationMsg(pMsgBuf, msg4);
      }

H
Haojun Liao 已提交
3562
      pQueryInfo->info.distinct = true;
3563 3564 3565
    }

    if (type == SQL_NODE_SQLFUNCTION) {
3566
      bool scalarFunc = false;
3567
      pItem->functionId = qIsBuiltinFunction(pItem->pNode->Expr.operand.z, pItem->pNode->Expr.operand.n, &scalarFunc);
H
Haojun Liao 已提交
3568 3569 3570 3571
      if (pItem->functionId == FUNCTION_INVALID_ID) { // temporarily disable the udf
//        int32_t functionId = FUNCTION_INVALID_ID;
//        bool valid = qIsValidUdf(pQueryInfo->pUdfInfo, pItem->pNode->Expr.operand.z, pItem->pNode->Expr.operand.n, &functionId);
//        if (!valid) {
3572
          return buildInvalidOperationMsg(pMsgBuf, msg5);
H
Haojun Liao 已提交
3573
//        }
3574

H
Haojun Liao 已提交
3575
//        pItem->functionId = functionId;
3576 3577
      }

3578
      if (scalarFunc) { // scalar function
3579
        if ((code = addScalarExprAndResColumn(pQueryInfo, outputIndex, pItem, pMsgBuf)) != TSDB_CODE_SUCCESS) {
3580 3581 3582 3583 3584 3585 3586
          return code;
        }
      } else { // aggregate function
        // sql function in selection clause, append sql function info in pSqlCmd structure sequentially
        if ((code = addAggExprAndResColumn(pQueryInfo, outputIndex, pItem, true, pMsgBuf)) != TSDB_CODE_SUCCESS) {
          return code;
        }
3587 3588 3589
      }
    } else if (type == SQL_NODE_TABLE_COLUMN || type == SQL_NODE_VALUE) {
      // use the dynamic array list to decide if the function is valid or not
3590
      // select table_name1.field_name1, table_name2.field_name2 from table_name1, table_name2
3591 3592
      if ((code = addProjectionExprAndResColumn(pQueryInfo, pItem, outerQuery, pMsgBuf)) != TSDB_CODE_SUCCESS) {
        return code;
3593 3594
      }
    } else if (type == SQL_NODE_EXPR) {
3595
      if ((code = addScalarExprAndResColumn(pQueryInfo, i, pItem, pMsgBuf)) != TSDB_CODE_SUCCESS) {
3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607
        return code;
      }
    } else {
      return buildInvalidOperationMsg(pMsgBuf, msg3);
    }
  }

  return TSDB_CODE_SUCCESS;
}

int32_t evaluateSqlNode(SSqlNode* pNode, int32_t tsPrecision, SMsgBuf* pMsgBuf) {
  assert(pNode != NULL && pMsgBuf != NULL && pMsgBuf->len > 0);
3608

3609
  // Evaluate expression in where clause
3610 3611 3612 3613 3614 3615
  if (pNode->pWhere != NULL) {
    int32_t code = evaluateSqlNodeImpl(pNode->pWhere, tsPrecision);
    if (code != TSDB_CODE_SUCCESS) {
      strncpy(pMsgBuf->buf, "invalid time expression in sql", pMsgBuf->len);
      return code;
    }
3616 3617
  }

3618
  // Evaluate the expression in select clause
3619 3620 3621
  size_t size = taosArrayGetSize(pNode->pSelNodeList);
  for(int32_t i = 0; i < size; ++i) {
    tSqlExprItem* pItem = taosArrayGet(pNode->pSelNodeList, i);
3622
    int32_t code = evaluateSqlNodeImpl(pItem->pNode, tsPrecision);
3623 3624 3625 3626 3627
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

3628
  return TSDB_CODE_SUCCESS;
3629
}
H
Haojun Liao 已提交
3630

D
dapan 已提交
3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657
int32_t setTableVgroupList(SParseBasicCtx *pCtx, SName* name, SVgroupsInfo **pVgList) {
  SArray* vgroupList = NULL;
  int32_t code = catalogGetTableDistVgroup(pCtx->pCatalog, pCtx->pTransporter, &pCtx->mgmtEpSet, name, &vgroupList);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
  
  int32_t vgroupNum = taosArrayGetSize(vgroupList);

  SVgroupsInfo *vgList = calloc(1, sizeof(SVgroupsInfo) + sizeof(SVgroupMsg) * vgroupNum);
  
  vgList->numOfVgroups = vgroupNum;
  
  for (int32_t i = 0; i < vgroupNum; ++i) {
    SVgroupInfo *vg = taosArrayGet(vgroupList, i);
    vgList->vgroups[i].vgId = vg->vgId;
    vgList->vgroups[i].numOfEps = vg->numOfEps;
    memcpy(vgList->vgroups[i].epAddr, vg->epAddr, sizeof(vgList->vgroups[i].epAddr));
  }

  *pVgList = vgList;

  taosArrayDestroy(vgroupList);

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
3658 3659
int32_t qParserValidateSqlNode(SParseBasicCtx *pCtx, SSqlInfo* pInfo, SQueryStmtInfo* pQueryInfo, char* msgBuf, int32_t msgBufLen) {
  assert(pCtx != NULL && pInfo != NULL);
3660
  int32_t code = 0;
3661

H
Haojun Liao 已提交
3662 3663
  SMsgBuf  m = {.buf = msgBuf, .len = msgBufLen};
  SMsgBuf* pMsgBuf = &m;
3664

3665
  switch (pInfo->type) {
3666
#if 0
3667 3668 3669 3670 3671 3672 3673 3674 3675
    case TSDB_SQL_DROP_TABLE:
    case TSDB_SQL_DROP_USER:
    case TSDB_SQL_DROP_ACCT:
    case TSDB_SQL_DROP_DNODE:
    case TSDB_SQL_DROP_DB: {
      const char* msg1 = "param name too long";
      const char* msg2 = "invalid name";

      SToken* pzName = taosArrayGet(pInfo->pMiscInfo->a, 0);
3676
      if ((pInfo->type != TSDB_SQL_DROP_DNODE) && (parserValidateIdToken(pzName) != TSDB_CODE_SUCCESS)) {
3677
        return buildInvalidOperationMsg(pMsgBuf, msg2);
3678 3679 3680 3681 3682 3683
      }

      if (pInfo->type == TSDB_SQL_DROP_DB) {
        assert(taosArrayGetSize(pInfo->pMiscInfo->a) == 1);
        code = tNameSetDbName(&pTableMetaInfo->name, getAccountId(pSql), pzName);
        if (code != TSDB_CODE_SUCCESS) {
3684
          return buildInvalidOperationMsg(pMsgBuf, msg2);
3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700
        }

      } else if (pInfo->type == TSDB_SQL_DROP_TABLE) {
        assert(taosArrayGetSize(pInfo->pMiscInfo->a) == 1);

        code = tscSetTableFullName(&pTableMetaInfo->name, pzName, pSql);
        if(code != TSDB_CODE_SUCCESS) {
          return code;
        }
      } else if (pInfo->type == TSDB_SQL_DROP_DNODE) {
        if (pzName->type == TK_STRING) {
          pzName->n = strdequote(pzName->z);
        }
        strncpy(pCmd->payload, pzName->z, pzName->n);
      } else {  // drop user/account
        if (pzName->n >= TSDB_USER_LEN) {
3701
          return buildInvalidOperationMsg(pMsgBuf, msg3);
3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728
        }

        strncpy(pCmd->payload, pzName->z, pzName->n);
      }

      break;
    }

    case TSDB_SQL_RESET_CACHE: {
      return TSDB_CODE_SUCCESS;
    }

    case TSDB_SQL_CREATE_FUNCTION:
    case TSDB_SQL_DROP_FUNCTION:  {
      code = handleUserDefinedFunc(pSql, pInfo);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      break;
    }

    case TSDB_SQL_DESCRIBE_TABLE: {
      const char* msg1 = "invalid table name";

      SToken* pToken = taosArrayGet(pInfo->pMiscInfo->a, 0);
      if (tscValidateName(pToken) != TSDB_CODE_SUCCESS) {
3729
        return buildInvalidOperationMsg(pMsgBuf, msg1);
3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744
      }
      // additional msg has been attached already
      code = tscSetTableFullName(&pTableMetaInfo->name, pToken, pSql);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      return tscGetTableMeta(pSql, pTableMetaInfo);
    }
    case TSDB_SQL_SHOW_CREATE_STABLE:
    case TSDB_SQL_SHOW_CREATE_TABLE: {
      const char* msg1 = "invalid table name";

      SToken* pToken = taosArrayGet(pInfo->pMiscInfo->a, 0);
      if (tscValidateName(pToken) != TSDB_CODE_SUCCESS) {
3745
        return buildInvalidOperationMsg(pMsgBuf, msg1);
3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759
      }

      code = tscSetTableFullName(&pTableMetaInfo->name, pToken, pSql);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      return tscGetTableMeta(pSql, pTableMetaInfo);
    }
    case TSDB_SQL_SHOW_CREATE_DATABASE: {
      const char* msg1 = "invalid database name";

      SToken* pToken = taosArrayGet(pInfo->pMiscInfo->a, 0);
      if (tscValidateName(pToken) != TSDB_CODE_SUCCESS) {
3760
        return buildInvalidOperationMsg(pMsgBuf, msg1);
3761 3762 3763
      }

      if (pToken->n > TSDB_DB_NAME_LEN) {
3764
        return buildInvalidOperationMsg(pMsgBuf, msg1);
3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776
      }
      return tNameSetDbName(&pTableMetaInfo->name, getAccountId(pSql), pToken);
    }
    case TSDB_SQL_CFG_DNODE: {
      const char* msg2 = "invalid configure options or values, such as resetlog / debugFlag 135 / balance 'vnode:2-dnode:2' / monitor 1 ";
      const char* msg3 = "invalid dnode ep";

      /* validate the ip address */
      SMiscInfo* pMiscInfo = pInfo->pMiscInfo;

      /* validate the parameter names and options */
      if (validateDNodeConfig(pMiscInfo) != TSDB_CODE_SUCCESS) {
3777
        return buildInvalidOperationMsg(pMsgBuf, msg2);
3778 3779 3780 3781
      }

      char* pMsg = pCmd->payload;

S
Shengliang Guan 已提交
3782
      SMCfgDnodeReq* pCfg = (SMCfgDnodeReq*)pMsg;
3783 3784 3785 3786 3787 3788 3789 3790

      SToken* t0 = taosArrayGet(pMiscInfo->a, 0);
      SToken* t1 = taosArrayGet(pMiscInfo->a, 1);

      t0->n = strdequote(t0->z);
      strncpy(pCfg->ep, t0->z, t0->n);

      if (validateEp(pCfg->ep) != TSDB_CODE_SUCCESS) {
3791
        return buildInvalidOperationMsg(pMsgBuf, msg3);
3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811
      }

      strncpy(pCfg->config, t1->z, t1->n);

      if (taosArrayGetSize(pMiscInfo->a) == 3) {
        SToken* t2 = taosArrayGet(pMiscInfo->a, 2);

        pCfg->config[t1->n] = ' ';  // add sep
        strncpy(&pCfg->config[t1->n + 1], t2->z, t2->n);
      }

      break;
    }

    case TSDB_SQL_CFG_LOCAL: {
      SMiscInfo  *pMiscInfo = pInfo->pMiscInfo;
      const char *msg = "invalid configure options or values";

      // validate the parameter names and options
      if (validateLocalConfig(pMiscInfo) != TSDB_CODE_SUCCESS) {
3812
        return buildInvalidOperationMsg(pMsgBuf, msg);
3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842
      }

      int32_t numOfToken = (int32_t) taosArrayGetSize(pMiscInfo->a);
      assert(numOfToken >= 1 && numOfToken <= 2);

      SToken* t = taosArrayGet(pMiscInfo->a, 0);
      strncpy(pCmd->payload, t->z, t->n);
      if (numOfToken == 2) {
        SToken* t1 = taosArrayGet(pMiscInfo->a, 1);
        pCmd->payload[t->n] = ' ';  // add sep
        strncpy(&pCmd->payload[t->n + 1], t1->z, t1->n);
      }
      return TSDB_CODE_SUCCESS;
    }

    case TSDB_SQL_SELECT: {
      const char * msg1 = "no nested query supported in union clause";
      code = loadAllTableMeta(pSql, pInfo);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      pQueryInfo = tscGetQueryInfo(pCmd);

      size_t size = taosArrayGetSize(pInfo->list);
      for (int32_t i = 0; i < size; ++i) {
        SSqlNode* pSqlNode = taosArrayGetP(pInfo->list, i);

        tscTrace("0x%"PRIx64" start to parse the %dth subclause, total:%"PRIzu, pSql->self, i, size);

3843
        if (size > 1 && pSqlNode->from && pSqlNode->from->type == SQL_FROM_NODE_SUBQUERY) {
3844
          return buildInvalidOperationMsg(pMsgBuf, msg1);
3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877
        }

//        normalizeSqlNode(pSqlNode); // normalize the column name in each function
        if ((code = validateSqlNode(pSql, pSqlNode, pQueryInfo)) != TSDB_CODE_SUCCESS) {
          return code;
        }

        tscPrintSelNodeList(pSql, i);

        if ((i + 1) < size && pQueryInfo->sibling == NULL) {
          if ((code = tscAddQueryInfo(pCmd)) != TSDB_CODE_SUCCESS) {
            return code;
          }

          SArray *pUdfInfo = NULL;
          if (pQueryInfo->pUdfInfo) {
            pUdfInfo = taosArrayDup(pQueryInfo->pUdfInfo);
          }

          pQueryInfo = pCmd->active;
          pQueryInfo->pUdfInfo = pUdfInfo;
          pQueryInfo->udfCopy = true;
        }
      }

      if ((code = normalizeVarDataTypeLength(pCmd)) != TSDB_CODE_SUCCESS) {
        return code;
      }

      // set the command/global limit parameters from the first subclause to the sqlcmd object
      pCmd->active = pCmd->pQueryInfo;
      pCmd->command = pCmd->pQueryInfo->command;

3878
      STableMetaInfo* pTableMetaInfo1 = getMetaInfo(pCmd->active, 0);
3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905
      if (pTableMetaInfo1->pTableMeta != NULL) {
        pSql->res.precision = tscGetTableInfo(pTableMetaInfo1->pTableMeta).precision;
      }

      return TSDB_CODE_SUCCESS;  // do not build query message here
    }

    case TSDB_SQL_ALTER_TABLE: {
      if ((code = setAlterTableInfo(pSql, pInfo)) != TSDB_CODE_SUCCESS) {
        return code;
      }

      break;
    }

    case TSDB_SQL_KILL_QUERY:
    case TSDB_SQL_KILL_STREAM:
    case TSDB_SQL_KILL_CONNECTION: {
      if ((code = setKillInfo(pSql, pInfo, pInfo->type)) != TSDB_CODE_SUCCESS) {
        return code;
      }
      break;
    }

    case TSDB_SQL_SYNC_DB_REPLICA: {
      const char* msg1 = "invalid db name";
      SToken* pzName = taosArrayGet(pInfo->pMiscInfo->a, 0);
H
Haojun Liao 已提交
3906

3907 3908 3909
      assert(taosArrayGetSize(pInfo->pMiscInfo->a) == 1);
      code = tNameSetDbName(&pTableMetaInfo->name, getAccountId(pSql), pzName);
      if (code != TSDB_CODE_SUCCESS) {
3910
        return buildInvalidOperationMsg(pMsgBuf, msg1);
3911 3912 3913 3914 3915 3916
      }
      break;
    }
    case TSDB_SQL_COMPACT_VNODE:{
      const char* msg = "invalid compact";
      if (setCompactVnodeInfo(pSql, pInfo) != TSDB_CODE_SUCCESS) {
3917
        return buildInvalidOperationMsg(pMsgBuf, msg);
3918 3919 3920 3921
      }
      break;
    }
    default:
3922
      return buildInvalidOperationMsg(pMsgBuf, "not support sql expression");
3923
  }
H
Haojun Liao 已提交
3924 3925
#endif
  }
3926

H
Haojun Liao 已提交
3927 3928
  SCatalogReq req  = {0};
  SMetaData   data = {0};
H
Haojun Liao 已提交
3929

3930
  // TODO: check if the qnode info has been cached already
D
dapan1121 已提交
3931
  req.qNodeRequired = true;
H
Haojun Liao 已提交
3932
  code = qParserExtractRequestedMetaInfo(pInfo, &req, pCtx, msgBuf, msgBufLen);
3933 3934 3935
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
3936 3937

  // load the meta data from catalog
H
Haojun Liao 已提交
3938 3939 3940 3941 3942
//  code = catalogGetAllMeta(pCtx->pCatalog, pCtx->pTransporter, &pCtx->mgmtEpSet, &req, &data);
  STableMeta* pmt = NULL;

  SName* name = taosArrayGet(req.pTableName, 0);
  code = catalogGetTableMeta(pCtx->pCatalog, pCtx->pTransporter, &pCtx->mgmtEpSet, name, &pmt);
3943 3944 3945
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
D
dapan 已提交
3946
  
H
Haojun Liao 已提交
3947 3948 3949 3950 3951 3952 3953 3954 3955
  data.pTableMeta = taosArrayInit(1, POINTER_BYTES);
  taosArrayPush(data.pTableMeta, &pmt);

  pQueryInfo->pTableMetaInfo = calloc(1, POINTER_BYTES);
  pQueryInfo->pTableMetaInfo[0] = calloc(1, sizeof(STableMetaInfo));
  pQueryInfo->pTableMetaInfo[0]->pTableMeta = pmt;
  pQueryInfo->pTableMetaInfo[0]->name = *name;
  pQueryInfo->numOfTables = 1;

D
dapan 已提交
3956 3957 3958 3959 3960 3961
  code = setTableVgroupList(pCtx, name, &pQueryInfo->pTableMetaInfo[0]->vgroupList);
  if (code != TSDB_CODE_SUCCESS) {
    taosArrayDestroy(data.pTableMeta);
    return code;
  }

3962
  // evaluate the sqlnode
3963 3964 3965
  STableMeta* pTableMeta = (STableMeta*) taosArrayGetP(data.pTableMeta, 0);
  assert(pTableMeta != NULL);

3966 3967
  SMsgBuf buf = {.buf = msgBuf, .len = msgBufLen};

3968
  size_t len = taosArrayGetSize(pInfo->sub.node);
3969
  for(int32_t i = 0; i < len; ++i) {
3970
    SSqlNode* p = taosArrayGetP(pInfo->sub.node, i);
3971
    code = evaluateSqlNode(p, pTableMeta->tableInfo.precision, &buf);
3972 3973 3974 3975
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }
3976

3977
  for(int32_t i = 0; i < len; ++i) {
3978
    SSqlNode* p = taosArrayGetP(pInfo->sub.node, i);
3979 3980 3981
    validateSqlNode(p, pQueryInfo, &buf);
  }

3982
  return code;
3983
}