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

28 29 30 31
#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))

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

34 35 36 37
// -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 }

38
static int32_t validateSelectNodeList(SQueryStmtInfo* pQueryInfo, SArray* pSelNodeList, bool outerQuery, SMsgBuf* pMsgBuf);
39 40
static int32_t extractFunctionParameterInfo(SQueryStmtInfo* pQueryInfo, int32_t tokenId, STableMetaInfo** pTableMetaInfo, SSchema* columnSchema,
                                            tExprNode** pNode, SColumnIndex* pIndex, tSqlExprItem* pParamElem, SMsgBuf* pMsgBuf);
41

42
void setTokenAndResColumnName(tSqlExprItem* pItem, char* resColumnName, char* rawName, int32_t nameLength) {
43 44 45 46 47 48
  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) {
49 50
    assert(strlen(pItem->aliasName) < nameLength);
    tstrncpy(resColumnName, pItem->aliasName, len);
51 52 53 54
  } else {
    strncpy(resColumnName, rawName, len);
  }
}
55

56
static int32_t evaluateSqlNodeImpl(tSqlExpr* pExpr, int32_t tsPrecision) {
57 58
  int32_t code = 0;
  if (pExpr->type == SQL_NODE_EXPR) {
59
    code = evaluateSqlNodeImpl(pExpr->pLeft, tsPrecision);
60 61 62 63
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

64
    code = evaluateSqlNodeImpl(pExpr->pRight, tsPrecision);
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
    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) {
85
      pExpr->value.i     = taosGetTimestamp(tsPrecision);
86 87 88 89 90
      pExpr->value.nType = TSDB_DATA_TYPE_BIGINT;
      pExpr->tokenId     = TK_TIMESTAMP;
    } else if (pExpr->tokenId == TK_VARIABLE) {
      char    unit = 0;
      SToken* pToken = &pExpr->exprToken;
91
      int32_t ret = parseAbsoluteDuration(pToken->z, pToken->n, &pExpr->value.i, &unit, tsPrecision);
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
      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.
110 111
  } else if (pExpr->type == SQL_NODE_SQLFUNCTION) {
    SArray* pParam = pExpr->Expr.paramList;
H
Haojun Liao 已提交
112 113 114 115 116 117

    if (pParam != NULL) {
      for (int32_t i = 0; i < taosArrayGetSize(pParam); ++i) {
        tSqlExprItem* pItem = taosArrayGet(pParam, i);
        evaluateSqlNodeImpl(pItem->pNode, tsPrecision);
      }
118
    }
119 120 121 122 123
  }

  return  TSDB_CODE_SUCCESS;
}

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
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);
}

145
void destroyColumnList(SArray* pColumnList) {
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
  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);

167
  destroyColumnList(pTableMetaInfo->tagColList);
168 169 170 171 172 173
  pTableMetaInfo->tagColList = NULL;

  free(pTableMetaInfo);
}

static STableMeta* extractTempTableMetaFromSubquery(SQueryStmtInfo* pUpstream) {
H
Haojun Liao 已提交
174
  STableMetaInfo* pUpstreamTableMetaInfo = getMetaInfo(pUpstream, 0);
175 176 177 178 179 180 181 182 183 184 185 186

  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 已提交
187 188 189 190 191 192 193 194
    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;
195 196 197 198 199 200
  }

  info->numOfColumns = n;
  return meta;
}

201 202 203
SQueryStmtInfo *createQueryInfo() {
  SQueryStmtInfo* pQueryInfo = calloc(1, sizeof(SQueryStmtInfo));

204
  pQueryInfo->fieldsInfo.internalField = taosArrayInit(4, sizeof(SInternalField));
205 206 207 208 209 210 211 212 213 214
  pQueryInfo->exprList       = taosArrayInit(4, POINTER_BYTES);
  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;
  pQueryInfo->pUpstream      = taosArrayInit(4, POINTER_BYTES);
  pQueryInfo->window         = TSWINDOW_INITIALIZER;
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266

  return pQueryInfo;
}

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

  dropAllExprInfo(pQueryInfo->exprList);
  pQueryInfo->exprList = NULL;

  if (pQueryInfo->exprList1 != NULL) {
    dropAllExprInfo(pQueryInfo->exprList1);
    pQueryInfo->exprList1 = 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);

  taosArrayDestroy(pQueryInfo->pUpstream);
  pQueryInfo->pUpstream = NULL;
  pQueryInfo->bufLen = 0;
}

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

    size_t numOfUpstream = taosArrayGetSize(pQueryInfo->pUpstream);
    for (int32_t i = 0; i < numOfUpstream; ++i) {
      SQueryStmtInfo* pUpQueryInfo = taosArrayGetP(pQueryInfo->pUpstream, i);
      destroyQueryInfoImpl(pUpQueryInfo);
      clearAllTableMetaInfo(pUpQueryInfo, false, 0);
      tfree(pUpQueryInfo);
    }

    destroyQueryInfoImpl(pQueryInfo);
    clearAllTableMetaInfo(pQueryInfo, false, 0);
    tfree(pQueryInfo);
    pQueryInfo = p;
  }
267 268
}

269
static int32_t doValidateSubquery(SSqlNode* pSqlNode, int32_t index, SQueryStmtInfo* pQueryInfo, SMsgBuf* pMsgBuf) {
270 271 272 273 274
  SRelElementPair* subInfo = taosArrayGet(pSqlNode->from->list, index);

  // union all is not support currently
  SSqlNode* p = taosArrayGetP(subInfo->pSubquery, 0);
  if (taosArrayGetSize(subInfo->pSubquery) >= 2) {
275
    return buildInvalidOperationMsg(pMsgBuf, "not support union in subquery");
276 277
  }

278
  SQueryStmtInfo* pSub = createQueryInfo();
279 280 281 282 283 284 285 286

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

  pSub->pUdfInfo = pUdfInfo;
  pSub->pDownstream = pQueryInfo;
287
  int32_t code = validateSqlNode(p, pSub, pMsgBuf);
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
  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);
303
      return buildInvalidOperationMsg(pMsgBuf, "subquery alias name too long");
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
    }

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

  taosArrayPush(pQueryInfo->pUpstream, &pSub);

  // 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) {
330
    columnListInsert(pQueryInfo->colList, i + startOffset, pMeta->uid, &pMeta->schema[i]);
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
  }

  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) {
349
    STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, i);
350 351 352
    char* name = pTableMetaInfo->aliasName;
    if (strncasecmp(name, pTableToken->z, pTableToken->n) == 0 && strlen(name) == pTableToken->n) {
      pIndex->tableIndex = i;
353
      return TSDB_CODE_SUCCESS;
354 355 356
    }
  }

357
  return TSDB_CODE_TSC_INVALID_OPERATION;
358 359 360 361 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
}

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

390
static int16_t doGetColumnIndex(SQueryStmtInfo* pQueryInfo, int32_t index, const SToken* pToken, int16_t* type) {
391 392 393
  STableMeta* pTableMeta = getMetaInfo(pQueryInfo, index)->pTableMeta;

  int32_t  numOfCols = getNumOfColumns(pTableMeta) + getNumOfTags(pTableMeta);
394
  SSchema* pSchema = getTableColumnSchema(pTableMeta);
395 396 397

  int16_t columnIndex = COLUMN_INDEX_INITIAL_VAL;

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

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

409
  *type = (columnIndex >= getNumOfColumns(pTableMeta))? TSDB_COL_TAG:TSDB_COL_NORMAL;
410 411 412 413 414 415 416 417 418 419 420
  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);
}

421
int32_t doGetColumnIndexByName(SToken* pToken, SQueryStmtInfo* pQueryInfo, SColumnIndex* pIndex, SMsgBuf* pMsgBuf) {
422 423 424
  const char* msg0 = "ambiguous column name";
  const char* msg1 = "invalid column name";

425 426
  pIndex->type = TSDB_COL_NORMAL;

427 428
  if (isTablenameToken(pToken)) {
    pIndex->columnIndex = TSDB_TBNAME_COLUMN_INDEX;
429
    pIndex->type = TSDB_COL_TAG;
430 431
  } else if (strlen(DEFAULT_PRIMARY_TIMESTAMP_COL_NAME) == pToken->n &&
             strncasecmp(pToken->z, DEFAULT_PRIMARY_TIMESTAMP_COL_NAME, pToken->n) == 0) {
432
    pIndex->columnIndex = PRIMARYKEY_TIMESTAMP_COL_ID; // just make runtime happy, need fix java test case InsertSpecialCharacterJniTest
433
  } else if (pToken->n == 0) {
434
    pIndex->columnIndex = PRIMARYKEY_TIMESTAMP_COL_ID; // just make runtime happy, need fix java test case InsertSpecialCharacterJniTest
435 436 437 438
  } 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) {
439
        int16_t colIndex = doGetColumnIndex(pQueryInfo, i, pToken, &pIndex->type);
440 441 442

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

    if (pIndex->columnIndex == COLUMN_INDEX_INITIAL_VAL) {
455
      return buildInvalidOperationMsg(pMsgBuf, msg1);
456 457 458 459 460 461 462 463 464 465
    }
  }

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

466
int32_t getColumnIndexByName(const SToken* pToken, SQueryStmtInfo* pQueryInfo, SColumnIndex* pIndex, SMsgBuf* pMsgBuf) {
467 468 469 470 471 472 473 474 475
  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;
  }

476
  return doGetColumnIndexByName(&tmpToken, pQueryInfo, pIndex, pMsgBuf);
477 478
}

479
int32_t validateGroupbyNode(SQueryStmtInfo* pQueryInfo, SArray* pList, SMsgBuf* pMsgBuf) {
480 481 482 483 484 485
  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 已提交
486
  const char* msg7 = "normal column and tags can not be mixed up in group by clause";
487 488
  const char* msg8 = "normal column can only locate at the end of group by clause";

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

495 496 497 498 499 500 501
  // todo : handle two tables situation
  STableMetaInfo* pTableMetaInfo = NULL;
  if (pList == NULL) {
    return TSDB_CODE_SUCCESS;
  }

  if (pQueryInfo->numOfTables > 1) {
502
    return buildInvalidOperationMsg(pMsgBuf, msg4);
503 504
  }

505 506
  size_t num = taosArrayGetSize(pList);
  if (num > TSDB_MAX_TAGS) {
507
    return buildInvalidOperationMsg(pMsgBuf, msg1);
508 509
  }

510 511 512
  int32_t  numOfGroupbyCols = 0;
  SSchema *pSchema          = NULL;
  int32_t  tableIndex       = COLUMN_INDEX_INITIAL_VAL;
H
Haojun Liao 已提交
513
  bool groupbyTag           = false;
514 515

  for (int32_t i = 0; i < num; ++i) {
516 517
    SListItem * pItem = taosArrayGet(pList, i);
    SVariant* pVar = &pItem->pVar;
518 519

    SColumnIndex index = COLUMN_INDEX_INITIALIZER;
520
    SToken token = {pVar->nLen, pVar->nType, pVar->pz};
521 522
    if (getColumnIndexByName(&token, pQueryInfo, &index, pMsgBuf) != TSDB_CODE_SUCCESS) {
      return buildInvalidOperationMsg(pMsgBuf, msg2);
523 524
    }

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

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

    if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
      pSchema = getTbnameColumnSchema();
    } else {
538
      pSchema = getOneColumnSchema(pTableMeta, index.columnIndex);
539 540
    }

541
    bool groupTag = TSDB_COL_IS_TAG(index.type);
542 543
    if (groupTag) {
      if (!UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
544
        return buildInvalidOperationMsg(pMsgBuf, msg6);
545 546
      }

H
Haojun Liao 已提交
547 548
      groupbyTag = true;

549 550
      int32_t relIndex = index.columnIndex;
      if (index.columnIndex != TSDB_TBNAME_COLUMN_INDEX) {
551
        relIndex -= getNumOfColumns(pTableMeta);
552 553 554 555 556 557 558
      }

      SColIndex colIndex = { .colIndex = relIndex, .flag = TSDB_COL_TAG, .colId = pSchema->colId, };
      strncpy(colIndex.name, pSchema->name, tListLen(colIndex.name));
      taosArrayPush(pGroupExpr->columnInfo, &colIndex);

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

566
      columnListInsert(pQueryInfo->colList, index.columnIndex, pTableMeta->uid, pSchema);
567 568 569 570 571

      SColIndex colIndex = { .colIndex = index.columnIndex, .flag = TSDB_COL_NORMAL, .colId = pSchema->colId };
      strncpy(colIndex.name, pSchema->name, tListLen(colIndex.name));

      taosArrayPush(pGroupExpr->columnInfo, &colIndex);
572 573 574

      numOfGroupbyCols++;
      pQueryInfo->info.groupbyColumn = true;
575 576 577
    }
  }

H
Haojun Liao 已提交
578
  if (numOfGroupbyCols > 0 && groupbyTag) {
579
    return buildInvalidOperationMsg(pMsgBuf, msg7);
580 581
  }

H
Haojun Liao 已提交
582 583
  // todo ???
  // 1. the normal column in the group by clause can only located at the end position
584 585 586
  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) {
587
      return buildInvalidOperationMsg(pMsgBuf, msg8);
588 589 590
    }
  }

591 592
  pGroupExpr->orderType  = TSDB_ORDER_ASC;
  pGroupExpr->tableIndex = tableIndex;
593 594 595
  return TSDB_CODE_SUCCESS;
}

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

599
  for (int32_t i = 0; i < getNumOfExprs(pQueryInfo); ++i) {
600 601 602
    SExprInfo* pExpr = getExprInfo(pQueryInfo, i);
    assert(pExpr->pExpr->nodeType == TEXPR_UNARYEXPR_NODE);

H
Haojun Liao 已提交
603 604 605
    int32_t f = getExprFunctionId(pExpr);
    if (f == FUNCTION_PERCT || f == FUNCTION_INTERP) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
606 607 608
    }

    if (f == FUNCTION_BLKINFO && taosArrayGetSize(pQueryInfo->pUpstream) > 0) {
H
Haojun Liao 已提交
609
      return buildInvalidOperationMsg(pMsgBuf, msg1);
610 611
    }

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

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

627 628 629 630 631 632
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 已提交
633 634
  SInterval* pInterval = &pQueryInfo->interval;

635
  if (t->n == 0) {
H
Haojun Liao 已提交
636 637
    pInterval->offsetUnit = pInterval->intervalUnit;
    pInterval->offset = 0;
638 639 640
    return TSDB_CODE_SUCCESS;
  }

H
Haojun Liao 已提交
641
  if (parseNatualDuration(t->z, t->n, &pInterval->offset, &pInterval->offsetUnit, precision) != TSDB_CODE_SUCCESS) {
642 643 644
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

H
Haojun Liao 已提交
645
  if (pInterval->offset < 0) {
646 647 648
    return buildInvalidOperationMsg(pMsgBuf, msg1);
  }

H
Haojun Liao 已提交
649 650 651
  if (!TIME_IS_VAR_DURATION(pInterval->offsetUnit)) {
    if (!TIME_IS_VAR_DURATION(pInterval->intervalUnit)) {
      if (pInterval->offset > pInterval->interval) {
652 653 654
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }
    }
H
Haojun Liao 已提交
655 656
  } else if (pInterval->offsetUnit == pInterval->intervalUnit) {
    if (pInterval->offset >= pInterval->interval) {
657 658
      return buildInvalidOperationMsg(pMsgBuf, msg2);
    }
H
Haojun Liao 已提交
659
  } else if (pInterval->intervalUnit == 'n' && pInterval->offsetUnit == 'y') {
660
    return buildInvalidOperationMsg(pMsgBuf, msg3);
H
Haojun Liao 已提交
661 662
  } else if (pInterval->intervalUnit == 'y' && pInterval->offsetUnit == 'n') {
    if (pInterval->interval * 12 <= pQueryInfo->interval.offset) {
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 704 705 706 707 708 709
      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;
}

710 711
// validate the interval info
int32_t validateIntervalNode(SQueryStmtInfo *pQueryInfo, SSqlNode* pSqlNode, SMsgBuf* pMsgBuf) {
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 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
  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;
    }
  }

  // orderby column not set yet, set it to be the primary timestamp column
  if (pQueryInfo->order.orderColId == INT32_MIN) {
    pQueryInfo->order.orderColId = PRIMARYKEY_TIMESTAMP_COL_ID;
  }

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

  // It is a time window query
  pQueryInfo->info.timewindow = true;
  return TSDB_CODE_SUCCESS;
  // disable it temporarily
//  bool interpQuery = tscIsPointInterpQuery(pQueryInfo);
//  if ((pSqlNode->interval.token == TK_EVERY && (!interpQuery)) || (pSqlNode->interval.token == TK_INTERVAL && interpQuery)) {
//    return buildInvalidOperationMsg(pMsgBuf, msg4);
//  }
768 769
}

770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
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";

  // 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) {
    return buildInvalidOperationMsg(pMsgBuf, msg3);
  }

  pQueryInfo->sessionWindow.primaryColId = PRIMARYKEY_TIMESTAMP_COL_ID;
  return TSDB_CODE_SUCCESS;
812 813 814
}

// parse the window_state
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
int32_t validateStateWindowNode(SQueryStmtInfo *pQueryInfo, SWindowStateVal* pWindowState, SMsgBuf* pMsgBuf) {
  const char* msg1 = "invalid column name";
  const char* msg2 = "invalid column type";
  const char* msg3 = "not support state_window with group by ";
  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);
  }

  if (pGroupExpr->columnInfo == NULL) {
    pGroupExpr->columnInfo = taosArrayInit(4, sizeof(SColIndex));
  }

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

  columnListInsert(pQueryInfo->colList, index.columnIndex, pTableMeta->uid, pSchema);
  SColIndex colIndex = { .colIndex = index.columnIndex, .flag = TSDB_COL_NORMAL, .colId = pSchema->colId };

  //TODO use group by routine? state window query not support stable query.
  taosArrayPush(pGroupExpr->columnInfo, &colIndex);
  pGroupExpr->orderType = TSDB_ORDER_ASC;
  pQueryInfo->info.stateWindow = true;

  return TSDB_CODE_SUCCESS;
866 867 868 869 870 871 872 873
}

// 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) {
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 920 921 922 923 924 925 926 927 928
  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);
    }
  }
929 930
}

931 932
static void setTsOutputExprInfo(SQueryStmtInfo* pQueryInfo, STableMetaInfo* pTableMetaInfo, int32_t outputIndex, int32_t tableIndex);

933
int32_t validateOrderbyNode(SQueryStmtInfo *pQueryInfo, SSqlNode* pSqlNode, SMsgBuf* pMsgBuf) {
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
  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;
  }

  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);
  if (UTIL_TABLE_IS_NORMAL_TABLE(pTableMetaInfo) || UTIL_TABLE_IS_TMP_TABLE(pTableMetaInfo)) {
    if (size > 1) {
      return buildInvalidOperationMsg(pMsgBuf, msg3);
    }
  } else {
    if (size > 2) {
      return buildInvalidOperationMsg(pMsgBuf, msg2);
    }
  }

  // handle the first part of order by
  SVariant* pVar = taosArrayGet(pSortOrder, 0);
  SSchema s = {0};
  if (pVar->nType == TSDB_DATA_TYPE_BINARY) {
    SColumnIndex index = COLUMN_INDEX_INITIALIZER;
    SToken columnName = {pVar->nLen, pVar->nType, pVar->pz};
    if (getColumnIndexByName(&columnName, pQueryInfo, &index, pMsgBuf) != TSDB_CODE_SUCCESS) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }

    s = *(SSchema*) getOneColumnSchema(pTableMetaInfo->pTableMeta, index.columnIndex);
  } else { // order by [1|2|3]
975
    if (pVar->i > getNumOfFields(&pQueryInfo->fieldsInfo)) {
976 977 978
      return buildInvalidOperationMsg(pMsgBuf, msg4);
    }

979
    SExprInfo* pExprInfo = getExprInfo(pQueryInfo, pVar->i);
980 981 982 983 984 985 986 987 988 989 990 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 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
    s = pExprInfo->base.resSchema;
  }

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

  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
        if (pExpr->base.colInfo.colIndex != index.columnIndex && index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_ID) {
          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;
1134
          for (int32_t i = 0; i < getNumOfExprs(pQueryInfo); ++i) {
1135 1136 1137 1138 1139 1140 1141 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 1222 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
            SExprInfo* pExpr = getExprInfo(pQueryInfo, i);
            if (getExprFunctionId(pExpr) == FUNCTION_PRJ && pExpr->base.colInfo.colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
              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);

        if (pExpr->base.colInfo.colIndex != index.columnIndex && index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_ID) {
          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 已提交
1250
static int32_t checkFillQueryRange(SQueryStmtInfo* pQueryInfo, SMsgBuf* pMsgBuf) {
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
  const char* msg3 = "start(end) time of time range required or time range too large";

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

  bool initialWindows = TSWINDOW_IS_EQUAL(pQueryInfo->window, TSWINDOW_INITIALIZER);
  if (initialWindows) {
    return buildInvalidOperationMsg(pMsgBuf, msg3);
  }

  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) {
      return buildInvalidOperationMsg(pMsgBuf, msg3);
    }
  }

  return TSDB_CODE_SUCCESS;
1275 1276 1277
}

int32_t validateFillNode(SQueryStmtInfo *pQueryInfo, SSqlNode* pSqlNode, SMsgBuf* pMsgBuf) {
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
  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 已提交
1296
  if (checkFillQueryRange(pQueryInfo, pMsgBuf) != TSDB_CODE_SUCCESS) {
1297 1298 1299 1300 1301 1302 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
    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;
1385 1386 1387
}

int32_t validateSqlNode(SSqlNode* pSqlNode, SQueryStmtInfo* pQueryInfo, SMsgBuf* pMsgBuf) {
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
  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 已提交
1406 1407
   * select 1+2;
   * select now();
1408 1409 1410 1411
   */
  if (pSqlNode->from == NULL) {
    assert(pSqlNode->fillType == NULL && pSqlNode->pGroupby == NULL && pSqlNode->pWhere == NULL &&
           pSqlNode->pSortOrder == NULL);
1412 1413
    assert(0);
//    return doLocalQueryProcess(pCmd, pQueryInfo, pSqlNode);
1414 1415 1416 1417 1418 1419 1420 1421 1422
  }

  if (pSqlNode->from->type == SQL_NODE_FROM_SUBQUERY) {
    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) {
      SRelElementPair* subInfo = taosArrayGet(pSqlNode->from->list, i);
1423
      code = doValidateSubquery(pSqlNode, i, pQueryInfo, pMsgBuf);
1424 1425 1426 1427 1428 1429
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
    }

    // parse the group by clause in the first place
1430
    if (validateGroupbyNode(pQueryInfo, pSqlNode->pGroupby, pMsgBuf) != TSDB_CODE_SUCCESS) {
1431 1432 1433
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

1434
    if (validateSelectNodeList(pQueryInfo, pSqlNode->pSelNodeList, true, pMsgBuf) != TSDB_CODE_SUCCESS) {
1435 1436 1437
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

H
Haojun Liao 已提交
1438
    code = checkForUnsupportedQuery(pQueryInfo, pMsgBuf);
1439

1440
    STableMeta* pTableMeta = getMetaInfo(pQueryInfo, 0)->pTableMeta;
1441
    SSchema*    pSchema = getOneColumnSchema(pTableMeta, 0);
1442
    int32_t precision = pTableMeta->tableInfo.precision;
1443

H
Haojun Liao 已提交
1444
#if 0
1445
    if (pSchema->type != TSDB_DATA_TYPE_TIMESTAMP) {
1446
      int32_t numOfExprs = (int32_t)getNumOfExprs(pQueryInfo);
1447 1448

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

1451 1452 1453
        int32_t f = pExpr->pExpr->_node.functionId;
        if (f == FUNCTION_DERIVATIVE || f == FUNCTION_TWA || f == FUNCTION_IRATE) {
          return buildInvalidOperationMsg(pMsgBuf, msg7);
1454 1455 1456
        }
      }
    }
H
Haojun Liao 已提交
1457
#endif
1458 1459 1460

    // validate the query filter condition info
    if (pSqlNode->pWhere != NULL) {
1461
      if (validateWhereNode(pQueryInfo, pSqlNode->pWhere, pMsgBuf) != TSDB_CODE_SUCCESS) {
1462 1463 1464 1465
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }
    } else {
      if (pQueryInfo->numOfTables > 1) {
1466
        return buildInvalidOperationMsg(pMsgBuf, msg8);
1467 1468 1469 1470
      }
    }

    // validate the interval info
1471
    if (validateIntervalNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1472 1473
      return TSDB_CODE_TSC_INVALID_OPERATION;
    } else {
1474
      if (validateSessionNode(pQueryInfo, &pSqlNode->sessionVal, precision, pMsgBuf) != TSDB_CODE_SUCCESS) {
1475 1476 1477 1478
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }

      // parse the window_state
1479
      if (validateStateWindowNode(pQueryInfo, &pSqlNode->windowstateVal, pMsgBuf) != TSDB_CODE_SUCCESS) {
1480 1481 1482 1483 1484 1485
        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);
1486
    if (validateHavingNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1487 1488 1489
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

1490
    if ((code = validateLimitNode(pQueryInfo, pSqlNode, pMsgBuf)) != TSDB_CODE_SUCCESS) {
1491 1492 1493 1494
      return code;
    }

    // set order by info
1495
    if (validateOrderbyNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1496 1497 1498
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

1499
    if ((code = validateFillNode(pQueryInfo, pSqlNode, pMsgBuf)) != TSDB_CODE_SUCCESS) {
1500 1501 1502 1503
      return code;
    }
  } else {
    pQueryInfo->command = TSDB_SQL_SELECT;
1504
    if (taosArrayGetSize(pSqlNode->from->list) > TSDB_MAX_JOIN_TABLE_NUM) {
1505
      return buildInvalidOperationMsg(pMsgBuf, msg2);
1506 1507
    }

1508
    STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, 0);
1509
    pQueryInfo->info.stableQuery = UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo);
1510

1511
    int32_t precision = pTableMetaInfo->pTableMeta->tableInfo.precision;
1512 1513

    // parse the group by clause in the first place
1514
    if (validateGroupbyNode(pQueryInfo, pSqlNode->pGroupby, pMsgBuf) != TSDB_CODE_SUCCESS) {
1515 1516
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }
1517

1518 1519
    // set where info
    if (pSqlNode->pWhere != NULL) {
1520
      if (validateWhereNode(pQueryInfo, pSqlNode->pWhere, pMsgBuf) != TSDB_CODE_SUCCESS) {
1521 1522 1523 1524
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }
    } else {
      if (taosArrayGetSize(pSqlNode->from->list) > 1) { // Cross join not allowed yet
1525
        return buildInvalidOperationMsg(pMsgBuf, "cross join not supported yet");
1526 1527 1528
      }
    }

H
Haojun Liao 已提交
1529
    if (validateSelectNodeList(pQueryInfo, pSqlNode->pSelNodeList, false, pMsgBuf) != TSDB_CODE_SUCCESS) {
1530 1531 1532 1533
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    // parse the window_state
1534
    if (validateStateWindowNode(pQueryInfo, &pSqlNode->windowstateVal, pMsgBuf) != TSDB_CODE_SUCCESS) {
1535 1536 1537 1538
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    // set order by info
1539
    if (validateOrderbyNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1540 1541 1542 1543
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    // set interval value
1544
    if (validateIntervalNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1545 1546 1547 1548
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    // parse the having clause in the first place
1549
    if (validateHavingNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1550 1551 1552 1553 1554 1555 1556
      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
     */
1557
    if (validateSessionNode(pQueryInfo, &pSqlNode->sessionVal, precision, pMsgBuf) != TSDB_CODE_SUCCESS) {
1558 1559 1560 1561 1562 1563 1564 1565 1566
      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;
    }

1567
    if ((code = validateLimitNode(pQueryInfo, pSqlNode, pMsgBuf)) != TSDB_CODE_SUCCESS) {
1568 1569 1570
      return code;
    }

1571
    if ((code = validateFillNode(pQueryInfo, pSqlNode, pMsgBuf)) != TSDB_CODE_SUCCESS) {
1572 1573 1574 1575 1576 1577 1578
      return code;
    }
  }

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

1579 1580 1581
int32_t checkForInvalidExpr(SQueryStmtInfo* pQueryInfo, SMsgBuf* pMsgBuf) {
  assert(pQueryInfo != NULL && pMsgBuf != NULL);

H
Haojun Liao 已提交
1582 1583 1584 1585 1586
  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";
1587 1588
  const char* msg6 = "not support distinct mixed with join";
  const char* msg7 = "not support distinct mixed with groupby";
H
Haojun Liao 已提交
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606
  const char* msg8 = "_block_dist not support subquery, only support stable/table";

  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
    int32_t colId = pQueryInfo->order.orderColId;
    if (pQueryInfo->info.timewindow && colId != PRIMARYKEY_TIMESTAMP_COL_ID) {
      return buildInvalidOperationMsg(pMsgBuf, msg2);
    }

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

H
Haojun Liao 已提交
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 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
  /*
   * 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);
      int32_t    functionId = getExprFunctionId(pExpr);
      if (functionId == FUNCTION_COUNT && TSDB_COL_IS_TAG(pExpr->base.colInfo.flag)) {
        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) {
1658 1659
      return buildInvalidOperationMsg(pMsgBuf, msg6);
    }
1660

1661 1662 1663
    if (taosArrayGetSize(pQueryInfo->groupbyExpr.columnInfo) != 0) {
      return buildInvalidOperationMsg(pMsgBuf, msg7);
    }
1664
  }
H
Haojun Liao 已提交
1665 1666 1667 1668 1669 1670

  /*
   * 7. invalid sql:
   * nested subquery not support block_dist query
   * select block_dist() from (select * from table_name)
   */
1671
}
1672

1673
static int32_t resColId = 5000;
1674
int32_t getNewResColId() {
1675 1676
  return resColId++;
}
1677

1678
int32_t addResColumnInfo(SQueryStmtInfo* pQueryInfo, int32_t outputIndex, SSchema* pSchema, SExprInfo* pSqlExpr) {
1679 1680 1681 1682
  SInternalField* pInfo = insertFieldInfo(&pQueryInfo->fieldsInfo, outputIndex, pSchema);
  pInfo->pExpr = pSqlExpr;
  return TSDB_CODE_SUCCESS;
}
1683

1684 1685 1686 1687 1688 1689 1690
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);
1691

1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709
    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);
  }
}

1710
SExprInfo* doAddOneExprInfo(SQueryStmtInfo* pQueryInfo, int32_t outputColIndex, int16_t functionId, SColumnIndex* pIndex,
1711
                           SSchema* pColSchema, SSchema* pResultSchema, tExprNode* pExprNode, int32_t interSize, const char* token, bool finalResult) {
1712 1713
  STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, pIndex->tableIndex);

1714
  SExprInfo* pExpr = createExprInfo(pTableMetaInfo, functionId, pIndex, pExprNode, pResultSchema, interSize);
1715 1716
  addExprInfo(pQueryInfo, outputColIndex, pExpr);

1717
  tstrncpy(pExpr->base.token, token, sizeof(pExpr->base.token));
1718
  uint64_t uid = pTableMetaInfo->pTableMeta->uid;
1719

1720
  SArray* p = TSDB_COL_IS_TAG(pIndex->type)?pTableMetaInfo->tagColList:pQueryInfo->colList;
1721
  columnListInsert(p, pIndex->columnIndex, uid, pColSchema);
1722

1723 1724 1725 1726
  pExpr->base.colInfo.flag = pIndex->type;
  if (TSDB_COL_IS_NORMAL_COL(pIndex->type)) {
    insertPrimaryTsColumn(pQueryInfo->colList, uid);
  }
1727

1728
  if (finalResult) {
1729
    addResColumnInfo(pQueryInfo, outputColIndex, pColSchema, pExpr);
1730 1731
  }

1732
  return pExpr;
1733 1734
}

1735
static int32_t addOneExprInfo(SQueryStmtInfo* pQueryInfo, tSqlExprItem* pItem, int32_t functionId, int32_t outputIndex, SSchema* pSchema, SColumnIndex* pColIndex, tExprNode* pNode, bool finalResult, SMsgBuf* pMsgBuf) {
1736 1737 1738 1739 1740 1741 1742
  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);
    }
  }

1743 1744 1745
  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);
1746

1747 1748
  SResultDataInfo resInfo = {0};
  getResultDataInfo(pSchema->type, pSchema->bytes, functionId, 0, &resInfo, 0, false);
1749

1750
  SSchema resultSchema = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), name);
1751
  doAddOneExprInfo(pQueryInfo, outputIndex, functionId, pColIndex, pSchema, &resultSchema, pNode, resInfo.intermediateBytes, name, finalResult);
1752 1753 1754
  return TSDB_CODE_SUCCESS;
}

1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
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;
}

static int32_t validateComplexExpr(tSqlExpr* pExpr, SQueryStmtInfo* pQueryInfo, SArray* pColList, int32_t* type, SMsgBuf* pMsgBuf);
static int32_t sqlExprToExprNode(tExprNode **pExpr, const tSqlExpr* pSqlExpr, SQueryStmtInfo* pQueryInfo, SArray* pCols, uint64_t *uid, SMsgBuf* pMsgBuf);

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) {
1789
  SColumnIndex indexTS = {.tableIndex = tableIndex, .columnIndex = PRIMARYKEY_TIMESTAMP_COL_ID, .type = TSDB_COL_NORMAL};
1790 1791 1792
  SSchema s = createSchema(TSDB_DATA_TYPE_TIMESTAMP, TSDB_KEYSIZE, getNewResColId(), "ts");

  SExprInfo* pExpr = createExprInfo(pTableMetaInfo, FUNCTION_TS_DUMMY, &indexTS, NULL, &s, TSDB_KEYSIZE);
H
Haojun Liao 已提交
1793 1794
  strncpy(pExpr->base.token, "ts", tListLen(pExpr->base.token));

1795 1796 1797 1798 1799 1800 1801
  addExprInfo(pQueryInfo, outputIndex, pExpr);

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

1802 1803 1804
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";
1805

1806 1807 1808 1809 1810 1811
  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 {
1812 1813 1814 1815 1816 1817
    tSqlExprItem* pParamElem = taosArrayGet(pParamList, 0);

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

    // select count(table.*), select count(1), count(2)
1818
    if (tokenId == TK_ALL || tokenId == TK_INTEGER || tokenId == TK_FLOAT) {
1819 1820 1821
      // check if the table name is valid or not
      SToken tmpToken = pParamElem->pNode->columnName;
      if (getTableIndexByName(&tmpToken, pQueryInfo, index) != TSDB_CODE_SUCCESS) {
1822
        return buildInvalidOperationMsg(pMsgBuf, msg2);
1823 1824
      }

1825 1826 1827
      *index = (SColumnIndex) {0, PRIMARYKEY_TIMESTAMP_COL_ID, false};
      *columnSchema = *(SSchema*) getOneColumnSchema(pTableMeta, index->columnIndex);
    } else if (pToken->z != NULL && pToken->n > 0) {
1828 1829
      // count the number of table created according to the super table
      if (getColumnIndexByName(pToken, pQueryInfo, index, pMsgBuf) != TSDB_CODE_SUCCESS) {
1830 1831 1832 1833 1834 1835 1836 1837 1838
        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);
1839 1840 1841 1842 1843 1844 1845 1846 1847
      }
    }
  }

  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) {
1848 1849
  STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;
  for (int32_t i = 0; i < getNumOfColumns(pTableMeta); ++i) {
1850 1851
    SColumnIndex index = {.tableIndex = tableIndex, .columnIndex = i, .type = TSDB_COL_NORMAL};

1852 1853
    SSchema* pSchema = getOneColumnSchema(pTableMeta, i);
    if (addOneExprInfo(pQueryInfo, pItem, functionId, *colIndex, pSchema, &index, NULL, finalResult, pMsgBuf) != 0) {
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
      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};

1884 1885
    int32_t code = extractFunctionParameterInfo(pQueryInfo, tokenId, &pTableMetaInfo, &columnSchema, &pNode, &index, pParamElem, pMsgBuf);
    if (code != TSDB_CODE_SUCCESS) {
1886 1887 1888 1889
      return buildInvalidOperationMsg(pMsgBuf, msg3);
    }

    // functions can not be applied to tags
1890
    if (TSDB_COL_IS_TAG(index.type) && (functionId == FUNCTION_INTERP || functionId == FUNCTION_SPREAD)) {
1891 1892 1893
      return buildInvalidOperationMsg(pMsgBuf, msg6);
    }

1894
    if (addOneExprInfo(pQueryInfo, pItem, functionId, (*outputIndex)++, &columnSchema, &index, pNode, finalResult, pMsgBuf) != 0) {
1895 1896 1897 1898 1899
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }
  }
}

1900 1901
static int32_t multiColumnListInsert(SQueryStmtInfo* pQueryInfo, SArray* pColumnList, SMsgBuf* pMsgBuf);

1902 1903 1904 1905 1906
int32_t extractFunctionParameterInfo(SQueryStmtInfo* pQueryInfo, int32_t tokenId, STableMetaInfo** pTableMetaInfo, SSchema* columnSchema,
                              tExprNode** pNode, SColumnIndex* pIndex, tSqlExprItem* pParamElem, SMsgBuf* pMsgBuf) {
  const char* msg1 = "not support column types";
  const char* msg2 = "invalid parameters";
  const char* msg3 = "illegal column name";
1907 1908 1909
  const char* msg4 = "nested function is not supported";
  const char* msg5 = "functions applied to tags are not allowed";

1910 1911 1912 1913 1914 1915 1916
  if (tokenId == TK_ALL || tokenId == TK_ID) {  // simple parameter
    if ((getColumnIndexByName(&pParamElem->pNode->columnName, pQueryInfo, pIndex, pMsgBuf) != TSDB_CODE_SUCCESS)) {
      return buildInvalidOperationMsg(pMsgBuf, msg3);
    }

    // functions can not be applied to tags
    if (TSDB_COL_IS_TAG(pIndex->type)) {
1917
      return buildInvalidOperationMsg(pMsgBuf, msg5);
1918 1919 1920 1921 1922 1923
    }

    *pTableMetaInfo = getMetaInfo(pQueryInfo, pIndex->tableIndex);

    // 2. check if sql function can be applied on this column data type
    *columnSchema = *(SSchema*) getOneColumnSchema((*pTableMetaInfo)->pTableMeta, pIndex->columnIndex);
1924
  } else if (tokenId == TK_PLUS || tokenId == TK_MINUS || tokenId == TK_STAR || tokenId == TK_REM || tokenId == TK_DIVIDE || tokenId == TK_CONCAT) {
1925 1926 1927 1928 1929 1930 1931
    int32_t arithmeticType = NON_ARITHMEIC_EXPR;
    SArray* pColumnList = taosArrayInit(4, sizeof(SColumnIndex));
    if (validateComplexExpr(pParamElem->pNode, pQueryInfo, pColumnList, &arithmeticType, pMsgBuf) != TSDB_CODE_SUCCESS) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }

    if (arithmeticType != NORMAL_ARITHMETIC) {
1932
      return buildInvalidOperationMsg(pMsgBuf, msg4);
1933 1934 1935 1936 1937
    }

    *pTableMetaInfo = getMetaInfo(pQueryInfo, 0);  // todo get the first table meta.
    *columnSchema = createSchema(TSDB_DATA_TYPE_DOUBLE, sizeof(double), getNewResColId(), "");

1938 1939 1940 1941
    SToken* pExprToken = &pParamElem->pNode->exprToken;
    int32_t len = MIN(TSDB_COL_NAME_LEN, pExprToken->n + 1);
    tstrncpy(columnSchema->name, pExprToken->z, len);

1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
    SArray* colList = taosArrayInit(10, sizeof(SColIndex));
    int32_t ret = sqlExprToExprNode(pNode, pParamElem->pNode, pQueryInfo, colList, NULL, pMsgBuf);
    if (ret != TSDB_CODE_SUCCESS) {
      taosArrayDestroy(colList);
      tExprTreeDestroy(*pNode, NULL);
      return buildInvalidOperationMsg(pMsgBuf, msg2);
    }

    pIndex->tableIndex = 0;
    multiColumnListInsert(pQueryInfo, pColumnList, pMsgBuf);
1952 1953
    taosArrayDestroy(colList);
    taosArrayDestroy(pColumnList);
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
  } else {
    assert(0);
  }
  
  return TSDB_CODE_SUCCESS;
}

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

  if (k == 0) {
    if (pSqlExpr->Expr.paramList != NULL && taosArrayGetSize(pSqlExpr->Expr.paramList) != 0) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }
  } else {
    if (pSqlExpr->Expr.paramList == NULL || taosArrayGetSize(pSqlExpr->Expr.paramList) != k) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }
  }
  return TSDB_CODE_SUCCESS;
}

1976 1977 1978
int32_t addExprAndResColumn(SQueryStmtInfo* pQueryInfo, int32_t colIndex, tSqlExprItem* pItem, bool finalResult, SMsgBuf* pMsgBuf) {
  STableMetaInfo* pTableMetaInfo = NULL;
  int32_t functionId = pItem->functionId;
1979
  int32_t code = TSDB_CODE_SUCCESS;
1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992

  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]";
1993 1994 1995 1996 1997
  const char* msg13 = "nested function is not supported";

  if (checkForAliasName(pMsgBuf, pItem->aliasName) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }
1998 1999 2000 2001 2002

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

2007
      tExprNode* pNode = NULL;
2008
      SColumnIndex index = COLUMN_INDEX_INITIALIZER;
2009 2010 2011
      SSchema columnSchema = {0};

      code = setColumnIndex(pQueryInfo, pParamList, &index, &columnSchema, &pNode, pMsgBuf);
2012 2013
      if (code != TSDB_CODE_SUCCESS) {
        return code;
2014 2015 2016
      }

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

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

2022
      int32_t outputIndex = getNumOfFields(&pQueryInfo->fieldsInfo);
2023
      doAddOneExprInfo(pQueryInfo, outputIndex, functionId, &index, &columnSchema, &s, pNode, size, token, finalResult);
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
      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);

2050 2051
      tExprNode* pNode = NULL;
      int32_t tokenId = pParamElem->pNode->tokenId;
2052
      SColumnIndex index = COLUMN_INDEX_INITIALIZER;
2053
      SSchema columnSchema = {0};
2054

2055 2056 2057 2058 2059 2060
      code = extractFunctionParameterInfo(pQueryInfo, tokenId, &pTableMetaInfo, &columnSchema, &pNode, &index, pParamElem,pMsgBuf);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
      
      if (tokenId == TK_ALL || tokenId == TK_ID) {
2061 2062 2063 2064 2065
        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);
        }
2066 2067
      }

2068 2069
      int32_t precision = pTableMetaInfo->pTableMeta->tableInfo.precision;

2070 2071
      SResultDataInfo resInfo = {0};
      if (getResultDataInfo(columnSchema.type, columnSchema.bytes, functionId, 0, &resInfo, 0, false) != TSDB_CODE_SUCCESS) {
2072 2073
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }
2074 2075 2076 2077

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

2082 2083 2084 2085
      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);
2086

2087
      SExprInfo* pExpr = doAddOneExprInfo(pQueryInfo, numOfOutput, functionId, &index, &columnSchema, &s, pNode, resInfo.intermediateBytes, token, finalResult);
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103

      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) {
2104
        addExprInfoParam(&pExpr->base, (char*) &precision, TSDB_DATA_TYPE_BIGINT, LONG_BYTES);
2105 2106 2107 2108
      } else if (functionId == FUNCTION_DERIVATIVE) {
        char val[8] = {0};

        int64_t tickPerSec = 0;
2109
        code = getTickPerSecond(&pParamElem[1].pNode->value, precision, &tickPerSec, pMsgBuf);
2110 2111
        if (code != TSDB_CODE_SUCCESS) {
          return code;
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
        }

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

2143
        if (taosArrayGetSize(pParamList) > 1 && (pItem->aliasName != NULL)) {
2144 2145 2146
          return buildInvalidOperationMsg(pMsgBuf, msg8);
        }

2147
        // in first/last function, multiple columns can be add to resultset
2148 2149
        for (int32_t i = 0; i < taosArrayGetSize(pParamList); ++i) {
          tSqlExprItem* pParamElem = taosArrayGet(pParamList, i);
2150
          doHandleOneParam(pQueryInfo, pItem, pParamElem, functionId, &colIndex, finalResult, pMsgBuf);
2151
        }
2152
      } else {  // select function(*) from xxx
2153 2154 2155 2156 2157 2158 2159 2160 2161
        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);
2162
          doAddAllColumnExprInSelectClause(pQueryInfo, pTableMetaInfo, pItem, functionId, j, &colIndex, finalResult, pMsgBuf);
2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
          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
2175 2176
      if ((code = checkForkParam(pItem->pNode, 2, pMsgBuf)) != TSDB_CODE_SUCCESS) {
        return code;
2177 2178 2179
      }

      tSqlExprItem* pParamElem = taosArrayGet(pItem->pNode->Expr.paramList, 0);
2180
      if (pParamElem->pNode->tokenId == TK_ALL) {
2181 2182 2183
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }

2184 2185
      tExprNode* pNode = NULL;
      int32_t tokenId = pParamElem->pNode->tokenId;
2186
      SColumnIndex index = COLUMN_INDEX_INITIALIZER;
2187 2188 2189 2190
      SSchema columnSchema = {0};
      code = extractFunctionParameterInfo(pQueryInfo, tokenId, &pTableMetaInfo, &columnSchema, &pNode, &index, pParamElem,pMsgBuf);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
      }

      // 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
2201
      if (!IS_NUMERIC_TYPE(columnSchema.type)) {
2202 2203 2204 2205 2206 2207 2208 2209
        return buildInvalidOperationMsg(pMsgBuf, msg1);
      }

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

2210
      SResultDataInfo resInfo = {0};
2211 2212 2213 2214 2215 2216
      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
      }
2217

2218
      SSchema s = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), "");
2219

2220 2221 2222
      char token[TSDB_COL_NAME_LEN] = {0};
      setTokenAndResColumnName(pItem, s.name, token, sizeof(s.name) - 1);
      SExprInfo* pExpr = doAddOneExprInfo(pQueryInfo, colIndex, functionId, &index, &columnSchema, &s, pNode, resInfo.intermediateBytes, token, finalResult);
2223

2224 2225 2226 2227 2228 2229
      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);
2230 2231 2232 2233 2234 2235

        /*
         * sql function transformation
         * for dp = 0, it is actually min,
         * for dp = 100, it is max,
         */
2236 2237 2238
        if (pVar->d < 0 || pVar->d > TOP_BOTTOM_QUERY_LIMIT) {
          return buildInvalidOperationMsg(pMsgBuf, msg5);
        }
2239
      } else {
2240 2241
        taosVariantCreate(pVar, pParamToken->z, pParamToken->n, TSDB_DATA_TYPE_BIGINT);
        if (pVar->i <= 0 || pVar->i > 100) {  // todo use macro
2242 2243
          return buildInvalidOperationMsg(pMsgBuf, msg12);
        }
2244
      }
2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255

      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
2256 2257
      if ((code = checkForkParam(pItem->pNode, 1, pMsgBuf)) != TSDB_CODE_SUCCESS) {
        return code;
2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302
      }

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

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

      SSchema s = {0};
      if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
        s = *getTbnameColumnSchema();
      } else {
        s = pTagSchema[index.columnIndex];
      }

2303 2304
      SResultDataInfo resInfo = {0};
      int32_t ret = getResultDataInfo(s.type, s.bytes, FUNCTION_TID_TAG, 0, &resInfo, 0, 0);
2305 2306
      assert(ret == TSDB_CODE_SUCCESS);

2307 2308
      s.type  = (uint8_t)resInfo.type;
      s.bytes = resInfo.bytes;
2309 2310
      s.colId = getNewResColId();
      TSDB_QUERY_SET_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_TAG_FILTER_QUERY);
2311
      
2312
      doAddOneExprInfo(pQueryInfo, 0, FUNCTION_TID_TAG, &index, &s, &s, NULL, 0, s.name, true);
2313 2314 2315 2316 2317
      return TSDB_CODE_SUCCESS;
    }

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

2322
      SColumnIndex index = {.tableIndex = 0, .columnIndex = 0, .type = TSDB_COL_NORMAL};
2323 2324
      pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);

2325 2326
      SResultDataInfo resInfo = {0};
      getResultDataInfo(TSDB_DATA_TYPE_INT, 4, functionId, 0, &resInfo, 0, 0);
2327

2328 2329
      SSchema s = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), "block_dist");
      SSchema colSchema = {0};
2330

2331 2332
      char token[TSDB_COL_NAME_LEN] = {0};
      setTokenAndResColumnName(pItem, s.name, token, sizeof(s.name) - 1);
2333
      SExprInfo* pExpr = doAddOneExprInfo(pQueryInfo, colIndex, functionId, &index, &colSchema, &s, NULL, resInfo.intermediateBytes, token, finalResult);
2334 2335 2336

      int64_t rowSize = pTableMetaInfo->pTableMeta->tableInfo.rowSize;
      addExprInfoParam(&pExpr->base, (char*) &rowSize, TSDB_DATA_TYPE_BIGINT, 8);
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
      return TSDB_CODE_SUCCESS;
    }

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

2367 2368
      SResultDataInfo resInfo = {0};
      getResultDataInfo(TSDB_DATA_TYPE_INT, 4, functionId, 0, &resInfo, 0, false/*, pUdfInfo*/);
2369

2370 2371
      SSchema s = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), "");
      SSchema* colSchema = getOneColumnSchema(pTableMetaInfo->pTableMeta, index.tableIndex);
2372

2373 2374
      char token[TSDB_COL_NAME_LEN] = {0};
      setTokenAndResColumnName(pItem, s.name, token, sizeof(s.name) - 1);
2375
      doAddOneExprInfo(pQueryInfo, colIndex, functionId, &index, colSchema, &s, NULL, resInfo.intermediateBytes, token, finalResult);
2376 2377 2378 2379 2380 2381 2382 2383
      return TSDB_CODE_SUCCESS;
    }
  }

  return TSDB_CODE_TSC_INVALID_OPERATION;
}

SExprInfo* doAddProjectCol(SQueryStmtInfo* pQueryInfo, int32_t outputColIndex, SColumnIndex* pColIndex, const char* aliasName, int32_t colId) {
2384
  STableMeta* pTableMeta = getMetaInfo(pQueryInfo, pColIndex->tableIndex)->pTableMeta;
2385 2386 2387 2388

  SSchema* pSchema = getOneColumnSchema(pTableMeta, pColIndex->columnIndex);
  SColumnIndex index = *pColIndex;

2389 2390 2391
  int16_t functionId = 0;
  if (TSDB_COL_IS_TAG(index.type)) {
    int32_t numOfCols = getNumOfColumns(pTableMeta);
2392
    index.columnIndex = pColIndex->columnIndex - numOfCols;
2393
    functionId = FUNCTION_TAGPRJ;
2394 2395
  } else {
    index.columnIndex = pColIndex->columnIndex;
2396
    functionId = FUNCTION_PRJ;
2397 2398
  }

2399 2400
  const char* name = (aliasName == NULL)? pSchema->name:aliasName;
  SSchema s = createSchema(pSchema->type, pSchema->bytes, colId, name);
2401
  return doAddOneExprInfo(pQueryInfo, outputColIndex, functionId, &index, pSchema, &s, NULL, 0, pSchema->name, true);
2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 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
}

static int32_t doAddProjectionExprAndResColumn(SQueryStmtInfo* pQueryInfo, SColumnIndex* pIndex, int32_t startPos) {
  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) {
    pIndex->columnIndex = j;
    doAddProjectCol(pQueryInfo, startPos + j, pIndex, NULL, getNewResColId());
  }

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

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";
  const char* msg3 = "tbname not allowed in outer query";

2460 2461 2462 2463
  if (checkForAliasName(pMsgBuf, pItem->aliasName) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

2464
  int32_t startPos = (int32_t)getNumOfExprs(pQueryInfo);
2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479
  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;
        int32_t inc = doAddProjectionExprAndResColumn(pQueryInfo, &index, startPos);
        startPos += inc;
2480 2481
      }
    } else {
2482
      doAddProjectionExprAndResColumn(pQueryInfo, &index, startPos);
2483 2484
    }

2485 2486 2487 2488 2489 2490 2491 2492
    // add the primary timestamp column even though it is not required by user
    STableMeta* pTableMeta = pQueryInfo->pTableMetaInfo[index.tableIndex]->pTableMeta;
    if (pTableMeta->tableType != TSDB_TEMP_TABLE) {
      insertPrimaryTsColumn(pQueryInfo->colList, pTableMeta->uid);
    }
  } else if (tokenId == TK_STRING || tokenId == TK_INTEGER || tokenId == TK_FLOAT) {  // simple column projection query
    SColumnIndex index = createConstantColumnIndex(&pQueryInfo->udColumnId);
    SSchema colSchema = createConstantColumnSchema(&pItem->pNode->value, &pItem->pNode->exprToken, pItem->aliasName);
2493

2494 2495 2496
    char token[TSDB_COL_NAME_LEN] = {0};
    tstrncpy(token, pItem->pNode->exprToken.z, MIN(TSDB_COL_NAME_LEN, TSDB_COL_NAME_LEN));
    SExprInfo* pExpr = doAddOneExprInfo(pQueryInfo, startPos, FUNCTION_PRJ, &index, &colSchema, &colSchema, NULL, 0, token, true);
2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507

    // 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);
  } else if (tokenId == TK_ID) {
    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) {
2508 2509 2510 2511
      SSchema colSchema = {0};
      int32_t functionId = 0;

      if (outerQuery) {  // todo??
2512 2513
        STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);

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

2517
        int32_t numOfCols = getNumOfColumns(pTableMetaInfo->pTableMeta);
2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529
        for (int32_t i = 0; i < numOfCols; ++i) {
          if (strncasecmp(pSchema[i].name, TSQL_TBNAME_L, tListLen(pSchema[i].name)) == 0) {
            existed = true;
            index.columnIndex = i;
            break;
          }
        }

        if (!existed) {
          return buildInvalidOperationMsg(pMsgBuf, msg3);
        }

2530 2531
        colSchema = pSchema[index.columnIndex];
        functionId = FUNCTION_PRJ;
2532
      } else {
2533 2534
        colSchema = *getTbnameColumnSchema();
        functionId = FUNCTION_TAGPRJ;
2535
      }
2536

2537 2538 2539
      SSchema resultSchema = colSchema;
      resultSchema.colId = getNewResColId();

2540
      char rawName[TSDB_COL_NAME_LEN] = {0};
2541 2542
      setTokenAndResColumnName(pItem, resultSchema.name, rawName, sizeof(colSchema.name) - 1);

2543
      doAddOneExprInfo(pQueryInfo, startPos, functionId, &index, &colSchema, &resultSchema, NULL, 0, rawName, true);
2544 2545 2546 2547 2548 2549 2550
    } else {
      STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);
      if (TSDB_COL_IS_TAG(index.type) && UTIL_TABLE_IS_NORMAL_TABLE(pTableMetaInfo)) {
        return buildInvalidOperationMsg(pMsgBuf, msg1);
      }

      doAddProjectCol(pQueryInfo, startPos, &index, pItem->aliasName, getNewResColId());
2551
    }
2552 2553 2554 2555 2556 2557 2558 2559

    // 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)) {
      insertPrimaryTsColumn(pQueryInfo->colList, pTableMetaInfo->pTableMeta->uid);
    }
  } else {
    return TSDB_CODE_TSC_INVALID_OPERATION;
2560 2561
  }

2562 2563 2564 2565 2566 2567 2568 2569 2570 2571
  return TSDB_CODE_SUCCESS;
}

static int32_t validateExprLeafNode(tSqlExpr* pExpr, SQueryStmtInfo* pQueryInfo, SArray* pList, int32_t* type, uint64_t* uid,
    SMsgBuf* pMsgBuf) {
  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;
2572
    }
2573 2574 2575 2576

    SColumnIndex index = COLUMN_INDEX_INITIALIZER;
    if (getColumnIndexByName(&pExpr->columnName, pQueryInfo, &index, pMsgBuf) != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
2577
    }
2578 2579 2580 2581 2582 2583 2584 2585

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

    SSchema* pSchema = getOneColumnSchema(pTableMeta, index.columnIndex);
    if ((pSchema->type == TSDB_DATA_TYPE_TIMESTAMP) || (pSchema->type == TSDB_DATA_TYPE_BOOL) ||
        (pSchema->type == TSDB_DATA_TYPE_BINARY) || (pSchema->type == TSDB_DATA_TYPE_NCHAR)) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
2586
    }
2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607

    taosArrayPush(pList, &index);
  } 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;
    }

    tSqlExprItem item = {.pNode = pExpr, .aliasName = NULL};

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

2608
    int32_t outputIndex = (int32_t)getNumOfExprs(pQueryInfo);
2609 2610 2611 2612 2613
    if (addExprAndResColumn(pQueryInfo, outputIndex, &item, false, pMsgBuf) != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    // It is invalid in case of more than one sqlExpr, such as first(ts, k) - last(ts, k)
2614
    int32_t inc = (int32_t) getNumOfExprs(pQueryInfo) - outputIndex;
2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
    if (inc > 1) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    // Not supported data type in arithmetic expression
    uint64_t id = -1;
    for(int32_t i = 0; i < inc; ++i) {
      SExprInfo* p1 = getExprInfo(pQueryInfo, i + outputIndex);

      int16_t t = p1->base.resSchema.type;
      if (IS_VAR_DATA_TYPE(t) || t == TSDB_DATA_TYPE_BOOL || t == TSDB_DATA_TYPE_TIMESTAMP) {
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }

      if (i == 0) {
        id = p1->base.uid;
        continue;
      }

      if (id != p1->base.uid) {
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }
2637 2638
    }

2639
    *uid = id;
2640 2641
  }

2642 2643
  return TSDB_CODE_SUCCESS;
}
2644

2645
int32_t validateComplexExpr(tSqlExpr* pExpr, SQueryStmtInfo* pQueryInfo, SArray* pColList, int32_t* type, SMsgBuf* pMsgBuf) {
2646 2647
  if (pExpr == NULL) {
    return TSDB_CODE_SUCCESS;
2648 2649
  }

2650 2651 2652 2653 2654
  tSqlExpr* pLeft = pExpr->pLeft;
  uint64_t uidLeft = 0;
  uint64_t uidRight = 0;

  if (pLeft->type == SQL_NODE_EXPR) {
2655
    int32_t ret = validateComplexExpr(pLeft, pQueryInfo, pColList, type, pMsgBuf);
2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
  } else {
    int32_t ret = validateExprLeafNode(pLeft, pQueryInfo, pColList, type, &uidLeft, pMsgBuf);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
  }

  tSqlExpr* pRight = pExpr->pRight;
  if (pRight->type == SQL_NODE_EXPR) {
2668
    int32_t ret = validateComplexExpr(pRight, pQueryInfo, pColList, type, pMsgBuf);
2669 2670 2671 2672 2673 2674 2675 2676
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
  } else {
    int32_t ret = validateExprLeafNode(pRight, pQueryInfo, pColList, type, &uidRight, pMsgBuf);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
2677 2678 2679 2680 2681
  }

  return TSDB_CODE_SUCCESS;
}

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 2722 2723 2724 2725 2726 2727 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 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772
int32_t  sqlExprToExprNode(tExprNode **pExpr, const tSqlExpr* pSqlExpr, SQueryStmtInfo* pQueryInfo, SArray* pCols, uint64_t *uid, SMsgBuf* pMsgBuf) {
  tExprNode* pLeft = NULL;
  tExprNode* pRight= NULL;

  SColumnIndex index = COLUMN_INDEX_INITIALIZER;
  if (pSqlExpr->pLeft != NULL) {
    int32_t ret = sqlExprToExprNode(&pLeft, pSqlExpr->pLeft, pQueryInfo, pCols, uid, pMsgBuf);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
  }

  if (pSqlExpr->pRight != NULL) {
    int32_t ret = sqlExprToExprNode(&pRight, pSqlExpr->pRight, pQueryInfo, pCols, uid, pMsgBuf);
    if (ret != TSDB_CODE_SUCCESS) {
      tExprTreeDestroy(pLeft, NULL);
      return ret;
    }
  }

  if (pSqlExpr->pLeft == NULL && pSqlExpr->pRight == NULL && pSqlExpr->tokenId == 0) {
    *pExpr = calloc(1, sizeof(tExprNode));
    return TSDB_CODE_SUCCESS;
  }

  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) {
      // arithmetic expression on the results of aggregation functions
      *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);

      // set the input column data byte and type.
      size_t size = taosArrayGetSize(pQueryInfo->exprList);

      for (int32_t i = 0; i < size; ++i) {
        SExprInfo* p1 = taosArrayGetP(pQueryInfo->exprList, i);

        if (strcmp((*pExpr)->pSchema->name, p1->base.resSchema.name) == 0) {
          memcpy((*pExpr)->pSchema, &p1->base.resSchema, sizeof(SSchema));
          if (uid != NULL) {
            *uid = p1->base.uid;
          }

          break;
        }
      }
    } else if (pSqlExpr->type == SQL_NODE_TABLE_COLUMN) { // column name, normal column arithmetic expression
      int32_t ret = getColumnIndexByName(&pSqlExpr->columnName, pQueryInfo, &index, pMsgBuf);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }

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

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

      SSchema* pSchema = getOneColumnSchema(pTableMeta, index.columnIndex);
      *(*pExpr)->pSchema = *pSchema;

      if (pCols != NULL) {  // record the involved columns
        SColIndex colIndex = {0};
        tstrncpy(colIndex.name, pSchema->name, sizeof(colIndex.name));
        colIndex.colId = pSchema->colId;
        colIndex.colIndex = index.columnIndex;
2773
        colIndex.flag = index.type;
2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828

        taosArrayPush(pCols, &colIndex);
      }

      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 {
    *pExpr = (tExprNode *)calloc(1, sizeof(tExprNode));
    (*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);

    // check for dividing by 0
    if ((*pExpr)->_node.optr == TSDB_BINARY_OP_DIVIDE) {
      if (pRight->nodeType == TEXPR_VALUE_NODE) {
2829
        if (pRight->pVal->nType == TSDB_DATA_TYPE_INT && pRight->pVal->i == 0) {
2830
          return buildInvalidOperationMsg(pMsgBuf, "invalid expr (divide by 0)");
2831
        } else if (pRight->pVal->nType == TSDB_DATA_TYPE_FLOAT && pRight->pVal->d == 0) {
2832
          return buildInvalidOperationMsg(pMsgBuf, "invalid expr (divide by 0)");
2833 2834 2835 2836 2837 2838 2839 2840
        }
      }
    }

    // NOTE: binary|nchar data allows the >|< type filter
    if ((*pExpr)->_node.optr != TSDB_RELATION_EQUAL && (*pExpr)->_node.optr != TSDB_RELATION_NOT_EQUAL) {
      if (pRight != NULL && pRight->nodeType == TEXPR_VALUE_NODE) {
        if (pRight->pVal->nType == TSDB_DATA_TYPE_BOOL && pLeft->pSchema->type == TSDB_DATA_TYPE_BOOL) {
2841
          return buildInvalidOperationMsg(pMsgBuf, "invalid operator for bool");
2842 2843 2844 2845 2846 2847 2848 2849
        }
      }
    }
  }

  return TSDB_CODE_SUCCESS;
}

2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871
static int32_t multiColumnListInsert(SQueryStmtInfo* pQueryInfo, SArray* pColumnList, SMsgBuf* pMsgBuf) {
  const char* msg3 = "tag columns can not be used in arithmetic expression";

  SColumnIndex* p1 = taosArrayGet(pColumnList, 0);
  STableMeta* pTableMeta = getMetaInfo(pQueryInfo, p1->tableIndex)->pTableMeta;

  size_t numOfNode = taosArrayGetSize(pColumnList);
  for(int32_t k = 0; k < numOfNode; ++k) {
    SColumnIndex* pIndex = taosArrayGet(pColumnList, k);
    if (TSDB_COL_IS_TAG(pIndex->type)) {
      return buildInvalidOperationMsg(pMsgBuf, msg3);
    }

    SSchema* ps = getOneColumnSchema(pTableMeta, pIndex->columnIndex);
    columnListInsert(pQueryInfo->colList, pIndex->columnIndex, pTableMeta->uid, ps);
  }

  insertPrimaryTsColumn(pQueryInfo->colList, pTableMeta->uid);
  return TSDB_CODE_SUCCESS;
}

static int32_t createComplexExpr(SQueryStmtInfo* pQueryInfo, int32_t exprIndex, tSqlExprItem* pItem, SMsgBuf* pMsgBuf) {
2872 2873 2874 2875 2876 2877
  const char* msg1 = "invalid column name, illegal column type, or columns in arithmetic expression from two tables";
  const char* msg2 = "invalid arithmetic expression in select clause";
  const char* msg3 = "tag columns can not be used in arithmetic expression";

  int32_t arithmeticType = NON_ARITHMEIC_EXPR;
  SArray* pColumnList = taosArrayInit(4, sizeof(SColumnIndex));
2878
  if (validateComplexExpr(pItem->pNode, pQueryInfo, pColumnList, &arithmeticType, pMsgBuf) != TSDB_CODE_SUCCESS) {
2879 2880 2881 2882 2883
    return buildInvalidOperationMsg(pMsgBuf, msg1);
  }

  if (arithmeticType == NORMAL_ARITHMETIC) {
    // expr string is set as the parameter of function
2884
    SSchema s = createSchema(TSDB_DATA_TYPE_DOUBLE, sizeof(double), getNewResColId(), "");
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894

    tExprNode* pNode = NULL;
    SArray* colList = taosArrayInit(10, sizeof(SColIndex));
    int32_t ret = sqlExprToExprNode(&pNode, pItem->pNode, pQueryInfo, colList, NULL, pMsgBuf);
    if (ret != TSDB_CODE_SUCCESS) {
      taosArrayDestroy(colList);
      tExprTreeDestroy(pNode, NULL);
      return buildInvalidOperationMsg(pMsgBuf, msg2);
    }

2895 2896 2897
    SExprInfo* pExpr = createBinaryExprInfo(pNode, &s);
    addExprInfo(pQueryInfo, exprIndex, pExpr);
    setTokenAndResColumnName(pItem, pExpr->base.resSchema.name, pExpr->base.token, TSDB_COL_NAME_LEN);
2898

2899 2900 2901 2902 2903 2904
    // check for if there is a tag in the arithmetic express
    int32_t code = multiColumnListInsert(pQueryInfo, pColumnList, pMsgBuf);
    if (code != TSDB_CODE_SUCCESS) {
      taosArrayDestroy(colList);
      tExprTreeDestroy(pNode, NULL);
      return code;
2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916
    }

    SBufferWriter bw = tbufInitWriter(NULL, false);

//    TRY(0) {
      exprTreeToBinary(&bw, pNode);
//    } CATCH(code) {
//      tbufCloseWriter(&bw);
//      UNUSED(code);
//       TODO: other error handling
//    } END_TRY

2917
    int32_t len = tbufTell(&bw);
2918 2919 2920 2921
    char* c = tbufGetData(&bw, false);

    // set the serialized binary string as the parameter of arithmetic expression
    addExprInfoParam(&pExpr->base, c, TSDB_DATA_TYPE_BINARY, (int32_t)len);
2922
    addResColumnInfo(pQueryInfo, exprIndex, &pExpr->base.resSchema, pExpr);
2923 2924 2925 2926 2927 2928

    tbufCloseWriter(&bw);
    taosArrayDestroy(colList);
  } else {
    SColumnIndex  columnIndex = {0};

2929 2930
    SSchema s = createSchema(TSDB_DATA_TYPE_DOUBLE, sizeof(double), getNewResColId(), "");
    addResColumnInfo(pQueryInfo, exprIndex, &s, NULL);
2931

2932 2933
    tExprNode* pNode = NULL;
    int32_t ret = sqlExprToExprNode(&pNode, pItem->pNode, pQueryInfo, NULL, NULL, pMsgBuf);
2934
    if (ret != TSDB_CODE_SUCCESS) {
2935
      tExprTreeDestroy(pNode, NULL);
2936 2937 2938
      return buildInvalidOperationMsg(pMsgBuf, "invalid expression in select clause");
    }

2939 2940 2941
    SExprInfo* pExpr = createBinaryExprInfo(pNode, &s);
    addExprInfo(pQueryInfo, exprIndex, pExpr);
    setTokenAndResColumnName(pItem, pExpr->base.resSchema.name, pExpr->base.token, TSDB_COL_NAME_LEN);
2942

2943
    pExpr->base.numOfParams = 1;
2944

2945
    SBufferWriter bw = tbufInitWriter(NULL, false);
2946
//    TRY(0) {
2947
      exprTreeToBinary(&bw, pExpr->pExpr);
2948 2949 2950 2951 2952 2953
//    } CATCH(code) {
//      tbufCloseWriter(&bw);
//      UNUSED(code);
//       TODO: other error handling
//    } END_TRY

2954
    SSqlExpr* pSqlExpr = &pExpr->base;
2955 2956 2957 2958
    pSqlExpr->param[0].nLen = (int16_t) tbufTell(&bw);
    pSqlExpr->param[0].pz   = tbufGetData(&bw, true);
    pSqlExpr->param[0].nType = TSDB_DATA_TYPE_BINARY;

2959 2960
    tbufCloseWriter(&bw);

2961 2962 2963
//    tbufCloseWriter(&bw); // TODO there is a memory leak
  }

2964
  taosArrayDestroy(pColumnList);
2965 2966 2967 2968 2969 2970 2971 2972 2973
  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 已提交
2974
  const char* msg4 = "distinct should be in the first place in select clause";
2975 2976 2977 2978 2979 2980 2981 2982 2983 2984
  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);
  }

  size_t numOfExpr = taosArrayGetSize(pSelNodeList);

  for (int32_t i = 0; i < numOfExpr; ++i) {
2985
    int32_t outputIndex = (int32_t)getNumOfExprs(pQueryInfo);
2986 2987 2988 2989
    tSqlExprItem* pItem = taosArrayGet(pSelNodeList, i);
    int32_t type = pItem->pNode->type;

    if (pItem->distinct) {
H
Haojun Liao 已提交
2990
      if (i != 0/* || type == SQL_NODE_SQLFUNCTION || type == SQL_NODE_EXPR*/) {
2991 2992 2993
        return buildInvalidOperationMsg(pMsgBuf, msg4);
      }

H
Haojun Liao 已提交
2994
      pQueryInfo->info.distinct = true;
2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019
    }

    if (type == SQL_NODE_SQLFUNCTION) {
      pItem->functionId = qIsBuiltinFunction(pItem->pNode->Expr.operand.z, pItem->pNode->Expr.operand.n);
      if (pItem->functionId == FUNCTION_INVALID_ID) {
        int32_t functionId = FUNCTION_INVALID_ID;
        bool valid = qIsValidUdf(pQueryInfo->pUdfInfo, pItem->pNode->Expr.operand.z, pItem->pNode->Expr.operand.n, &functionId);
        if (!valid) {
          return buildInvalidOperationMsg(pMsgBuf, msg5);
        }

        pItem->functionId = functionId;
      }

      // sql function in selection clause, append sql function info in pSqlCmd structure sequentially
      if (addExprAndResColumn(pQueryInfo, outputIndex, pItem, true, pMsgBuf) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }
    } 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
      // select table_name1.field_name1, table_name2.field_name2  from table_name1, table_name2
      if (addProjectionExprAndResColumn(pQueryInfo, pItem, outerQuery, pMsgBuf) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }
    } else if (type == SQL_NODE_EXPR) {
3020
      int32_t code = createComplexExpr(pQueryInfo, i, pItem, pMsgBuf);
3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033
      if (code != TSDB_CODE_SUCCESS) {
        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);
3034

3035
  // Evaluate expression in where clause
3036 3037 3038 3039 3040 3041
  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;
    }
3042 3043
  }

3044
  // Evaluate the expression in select clause
3045 3046 3047
  size_t size = taosArrayGetSize(pNode->pSelNodeList);
  for(int32_t i = 0; i < size; ++i) {
    tSqlExprItem* pItem = taosArrayGet(pNode->pSelNodeList, i);
3048
    int32_t code = evaluateSqlNodeImpl(pItem->pNode, tsPrecision);
3049 3050 3051 3052 3053
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

3054
  return TSDB_CODE_SUCCESS;
3055
}
H
Haojun Liao 已提交
3056

3057
int32_t qParserValidateSqlNode(struct SCatalog* pCatalog, SSqlInfo* pInfo, SQueryStmtInfo* pQueryInfo, int64_t id, char* msgBuf, int32_t msgBufLen) {
H
Haojun Liao 已提交
3058
  //1. if it is a query, get the meta info and continue.
3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071
  assert(pCatalog != NULL && pInfo != NULL);
  int32_t code = 0;
#if 0
  switch (pInfo->type) {
    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);
3072
      if ((pInfo->type != TSDB_SQL_DROP_DNODE) && (parserValidateIdToken(pzName) != TSDB_CODE_SUCCESS)) {
3073
        return setInvalidOperatorMsg(pMsgBuf, msg2);
3074 3075 3076 3077 3078 3079
      }

      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) {
3080
          return setInvalidOperatorMsg(pMsgBuf, msg2);
3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096
        }

      } 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) {
3097
          return setInvalidOperatorMsg(pMsgBuf, msg3);
3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110
        }

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

      break;
    }

    case TSDB_SQL_USE_DB: {
      const char* msg = "invalid db name";
      SToken* pToken = taosArrayGet(pInfo->pMiscInfo->a, 0);

      if (tscValidateName(pToken) != TSDB_CODE_SUCCESS) {
3111
        return setInvalidOperatorMsg(pMsgBuf, msg);
3112 3113 3114 3115
      }

      int32_t ret = tNameSetDbName(&pTableMetaInfo->name, getAccountId(pSql), pToken);
      if (ret != TSDB_CODE_SUCCESS) {
3116
        return setInvalidOperatorMsg(pMsgBuf, msg);
3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150
      }

      break;
    }

    case TSDB_SQL_RESET_CACHE: {
      return TSDB_CODE_SUCCESS;
    }

    case TSDB_SQL_SHOW: {
      if (setShowInfo(pSql, pInfo) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }

      break;
    }

    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_ALTER_DB:
    case TSDB_SQL_CREATE_DB: {
      const char* msg1 = "invalid db name";
      const char* msg2 = "name too long";

      SCreateDbInfo* pCreateDB = &(pInfo->pMiscInfo->dbOpt);
      if (pCreateDB->dbname.n >= TSDB_DB_NAME_LEN) {
3151
        return setInvalidOperatorMsg(pMsgBuf, msg2);
3152 3153 3154 3155 3156 3157
      }

      char buf[TSDB_DB_NAME_LEN] = {0};
      SToken token = taosTokenDup(&pCreateDB->dbname, buf, tListLen(buf));

      if (tscValidateName(&token) != TSDB_CODE_SUCCESS) {
3158
        return setInvalidOperatorMsg(pMsgBuf, msg1);
3159 3160 3161 3162
      }

      int32_t ret = tNameSetDbName(&pTableMetaInfo->name, getAccountId(pSql), &token);
      if (ret != TSDB_CODE_SUCCESS) {
3163
        return setInvalidOperatorMsg(pMsgBuf, msg2);
3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176
      }

      if (parseCreateDBOptions(pCmd, pCreateDB) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }

      break;
    }

    case TSDB_SQL_CREATE_DNODE: {
      const char* msg = "invalid host name (ip address)";

      if (taosArrayGetSize(pInfo->pMiscInfo->a) > 1) {
3177
        return setInvalidOperatorMsg(pMsgBuf, msg);
3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200
      }

      SToken* id = taosArrayGet(pInfo->pMiscInfo->a, 0);
      if (id->type == TK_STRING) {
        id->n = strdequote(id->z);
      }
      break;
    }

    case TSDB_SQL_CREATE_ACCT:
    case TSDB_SQL_ALTER_ACCT: {
      const char* msg1 = "invalid state option, available options[no, r, w, all]";
      const char* msg2 = "invalid user/account name";
      const char* msg3 = "name too long";

      SToken* pName = &pInfo->pMiscInfo->user.user;
      SToken* pPwd = &pInfo->pMiscInfo->user.passwd;

      if (handlePassword(pCmd, pPwd) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }

      if (pName->n >= TSDB_USER_LEN) {
3201
        return setInvalidOperatorMsg(pMsgBuf, msg3);
3202 3203 3204
      }

      if (tscValidateName(pName) != TSDB_CODE_SUCCESS) {
3205
        return setInvalidOperatorMsg(pMsgBuf, msg2);
3206 3207 3208 3209 3210 3211 3212 3213 3214
      }

      SCreateAcctInfo* pAcctOpt = &pInfo->pMiscInfo->acctOpt;
      if (pAcctOpt->stat.n > 0) {
        if (pAcctOpt->stat.z[0] == 'r' && pAcctOpt->stat.n == 1) {
        } else if (pAcctOpt->stat.z[0] == 'w' && pAcctOpt->stat.n == 1) {
        } else if (strncmp(pAcctOpt->stat.z, "all", 3) == 0 && pAcctOpt->stat.n == 3) {
        } else if (strncmp(pAcctOpt->stat.z, "no", 2) == 0 && pAcctOpt->stat.n == 2) {
        } else {
3215
          return setInvalidOperatorMsg(pMsgBuf, msg1);
3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226
        }
      }

      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) {
3227
        return setInvalidOperatorMsg(pMsgBuf, msg1);
3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242
      }
      // 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) {
3243
        return setInvalidOperatorMsg(pMsgBuf, msg1);
3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257
      }

      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) {
3258
        return setInvalidOperatorMsg(pMsgBuf, msg1);
3259 3260 3261
      }

      if (pToken->n > TSDB_DB_NAME_LEN) {
3262
        return setInvalidOperatorMsg(pMsgBuf, msg1);
3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274
      }
      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) {
3275
        return setInvalidOperatorMsg(pMsgBuf, msg2);
3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288
      }

      char* pMsg = pCmd->payload;

      SCfgDnodeMsg* pCfg = (SCfgDnodeMsg*)pMsg;

      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) {
3289
        return setInvalidOperatorMsg(pMsgBuf, msg3);
3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317
      }

      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_CREATE_USER:
    case TSDB_SQL_ALTER_USER: {
      const char* msg2 = "invalid user/account name";
      const char* msg3 = "name too long";
      const char* msg5 = "invalid user rights";
      const char* msg7 = "not support options";

      pCmd->command = pInfo->type;

      SUserInfo* pUser = &pInfo->pMiscInfo->user;
      SToken* pName = &pUser->user;
      SToken* pPwd = &pUser->passwd;

      if (pName->n >= TSDB_USER_LEN) {
3318
        return setInvalidOperatorMsg(pMsgBuf, msg3);
3319 3320 3321
      }

      if (tscValidateName(pName) != TSDB_CODE_SUCCESS) {
3322
        return setInvalidOperatorMsg(pMsgBuf, msg2);
3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345
      }

      if (pCmd->command == TSDB_SQL_CREATE_USER) {
        if (handlePassword(pCmd, pPwd) != TSDB_CODE_SUCCESS) {
          return TSDB_CODE_TSC_INVALID_OPERATION;
        }
      } else {
        if (pUser->type == TSDB_ALTER_USER_PASSWD) {
          if (handlePassword(pCmd, pPwd) != TSDB_CODE_SUCCESS) {
            return TSDB_CODE_TSC_INVALID_OPERATION;
          }
        } else if (pUser->type == TSDB_ALTER_USER_PRIVILEGES) {
          assert(pPwd->type == TSDB_DATA_TYPE_NULL);

          SToken* pPrivilege = &pUser->privilege;

          if (strncasecmp(pPrivilege->z, "super", 5) == 0 && pPrivilege->n == 5) {
            pCmd->count = 1;
          } else if (strncasecmp(pPrivilege->z, "read", 4) == 0 && pPrivilege->n == 4) {
            pCmd->count = 2;
          } else if (strncasecmp(pPrivilege->z, "write", 5) == 0 && pPrivilege->n == 5) {
            pCmd->count = 3;
          } else {
3346
            return setInvalidOperatorMsg(pMsgBuf, msg5);
3347 3348
          }
        } else {
3349
          return setInvalidOperatorMsg(pMsgBuf, msg7);
3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361
        }
      }

      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) {
3362
        return setInvalidOperatorMsg(pMsgBuf, msg);
3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 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 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416
      }

      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_CREATE_TABLE: {
      SCreateTableSql* pCreateTable = pInfo->pCreateTableInfo;

      if (pCreateTable->type == TSQL_CREATE_TABLE || pCreateTable->type == TSQL_CREATE_STABLE) {
        if ((code = doCheckForCreateTable(pSql, 0, pInfo)) != TSDB_CODE_SUCCESS) {
          return code;
        }

      } else if (pCreateTable->type == TSQL_CREATE_TABLE_FROM_STABLE) {
        assert(pCmd->numOfCols == 0);
        if ((code = doCheckForCreateFromStable(pSql, pInfo)) != TSDB_CODE_SUCCESS) {
          return code;
        }

      } else if (pCreateTable->type == TSQL_CREATE_STREAM) {
        if ((code = doCheckForStream(pSql, pInfo)) != TSDB_CODE_SUCCESS) {
          return code;
        }
      }

      break;
    }

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

        if (size > 1 && pSqlNode->from && pSqlNode->from->type == SQL_NODE_FROM_SUBQUERY) {
3417
          return setInvalidOperatorMsg(pMsgBuf, msg1);
3418 3419 3420 3421 3422 3423 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
        }

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

3451
      STableMetaInfo* pTableMetaInfo1 = getMetaInfo(pCmd->active, 0);
3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478
      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 已提交
3479

3480 3481 3482
      assert(taosArrayGetSize(pInfo->pMiscInfo->a) == 1);
      code = tNameSetDbName(&pTableMetaInfo->name, getAccountId(pSql), pzName);
      if (code != TSDB_CODE_SUCCESS) {
3483
        return setInvalidOperatorMsg(pMsgBuf, msg1);
3484 3485 3486 3487 3488 3489
      }
      break;
    }
    case TSDB_SQL_COMPACT_VNODE:{
      const char* msg = "invalid compact";
      if (setCompactVnodeInfo(pSql, pInfo) != TSDB_CODE_SUCCESS) {
3490
        return setInvalidOperatorMsg(pMsgBuf, msg);
3491 3492 3493 3494
      }
      break;
    }
    default:
3495
      return setInvalidOperatorMsg(pMsgBuf, "not support sql expression");
3496 3497
  }
#endif
H
Haojun Liao 已提交
3498

3499
  SMetaReq req = {0};
3500
  SMetaData data = {0};
H
Haojun Liao 已提交
3501

3502 3503 3504
  // TODO: check if the qnode info has been cached already
  req.qNodeEpset = true;
  code = qParserExtractRequestedMetaInfo(pInfo, &req, msgBuf, msgBufLen);
3505 3506 3507
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
3508 3509

  // load the meta data from catalog
3510 3511 3512 3513
  code = catalogGetMetaData(pCatalog, &req, &data);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
3514 3515

  // evaluate the sqlnode
3516 3517 3518
  STableMeta* pTableMeta = (STableMeta*) taosArrayGetP(data.pTableMeta, 0);
  assert(pTableMeta != NULL);

3519 3520
  SMsgBuf buf = {.buf = msgBuf, .len = msgBufLen};

3521 3522 3523
  size_t len = taosArrayGetSize(pInfo->list);
  for(int32_t i = 0; i < len; ++i) {
    SSqlNode* p = taosArrayGetP(pInfo->list, i);
3524
    code = evaluateSqlNode(p, pTableMeta->tableInfo.precision, &buf);
3525 3526 3527 3528
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }
3529

3530 3531 3532 3533 3534
  for(int32_t i = 0; i < len; ++i) {
    SSqlNode* p = taosArrayGetP(pInfo->list, i);
    validateSqlNode(p, pQueryInfo, &buf);
  }

3535 3536 3537
  SArray* functionList = extractFunctionIdList(pQueryInfo->exprList);
  extractFunctionDesc(functionList, &pQueryInfo->info);

3538 3539 3540 3541
  if ((code = checkForInvalidExpr(pQueryInfo, &buf)) != TSDB_CODE_SUCCESS) {
    return code;
  }

3542 3543
  // convert the sqlnode into queryinfo
  return code;
H
Haojun Liao 已提交
3544
}