astValidate.c 163.6 KB
Newer Older
H
Haojun Liao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

16
#include "astGenerator.h"
17
#include "function.h"
H
Haojun Liao 已提交
18
#include "parserInt.h"
19
#include "parserUtil.h"
20
#include "queryInfoUtil.h"
21 22 23 24
#include "tbuffer.h"
#include "tglobal.h"
#include "tmsgtype.h"
#include "ttime.h"
25
#include "astToMsg.h"
26

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return  TSDB_CODE_SUCCESS;
}

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

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

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

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

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

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

  taosArrayDestroy(pColumnList);
}

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

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

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

  free(pTableMetaInfo);
}

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

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

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

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

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

  info->numOfColumns = n;
  return meta;
}

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

208
  pQueryInfo->fieldsInfo.internalField = taosArrayInit(4, sizeof(SInternalField));
209 210 211 212 213 214 215 216 217
  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;
218

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

  pQueryInfo->exprListLevelIndex     = 0;

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

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

234
  dropAllExprInfo(pQueryInfo->exprList, 10);
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
  pQueryInfo->exprList = NULL;

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

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

  pQueryInfo->fillType = 0;

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

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

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

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

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

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

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

    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) {
335
    columnListInsert(pQueryInfo->colList, pMeta->uid, &pMeta->schema[i], TSDB_COL_NORMAL);
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
  }

  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) {
354
    STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, i);
355 356 357
    char* name = pTableMetaInfo->aliasName;
    if (strncasecmp(name, pTableToken->z, pTableToken->n) == 0 && strlen(name) == pTableToken->n) {
      pIndex->tableIndex = i;
358
      return TSDB_CODE_SUCCESS;
359 360 361
    }
  }

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

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

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

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

  int16_t columnIndex = COLUMN_INDEX_INITIAL_VAL;

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

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

414
  *type = (columnIndex >= getNumOfColumns(pTableMeta))? TSDB_COL_TAG:TSDB_COL_NORMAL;
415 416 417 418 419 420 421 422 423 424 425
  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);
}

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

430 431
  pIndex->type = TSDB_COL_NORMAL;

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

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

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

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

471
int32_t getColumnIndexByName(const SToken* pToken, SQueryStmtInfo* pQueryInfo, SColumnIndex* pIndex, SMsgBuf* pMsgBuf) {
472 473 474 475 476 477 478 479 480
  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;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

622 623 624 625 626 627
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 已提交
628 629
  SInterval* pInterval = &pQueryInfo->interval;

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

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

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

H
Haojun Liao 已提交
644 645 646
  if (!TIME_IS_VAR_DURATION(pInterval->offsetUnit)) {
    if (!TIME_IS_VAR_DURATION(pInterval->intervalUnit)) {
      if (pInterval->offset > pInterval->interval) {
647 648 649
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }
    }
H
Haojun Liao 已提交
650 651
  } else if (pInterval->offsetUnit == pInterval->intervalUnit) {
    if (pInterval->offset >= pInterval->interval) {
652 653
      return buildInvalidOperationMsg(pMsgBuf, msg2);
    }
H
Haojun Liao 已提交
654
  } else if (pInterval->intervalUnit == 'n' && pInterval->offsetUnit == 'y') {
655
    return buildInvalidOperationMsg(pMsgBuf, msg3);
H
Haojun Liao 已提交
656 657
  } else if (pInterval->intervalUnit == 'y' && pInterval->offsetUnit == 'n') {
    if (pInterval->interval * 12 <= pQueryInfo->interval.offset) {
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704
      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;
}

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

707 708
// validate the interval info
int32_t validateIntervalNode(SQueryStmtInfo *pQueryInfo, SSqlNode* pSqlNode, SMsgBuf* pMsgBuf) {
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
  const char* msg1 = "sliding cannot be used without interval";
  const char* msg2 = "only point interpolation query requires keyword EVERY";
  const char* msg3 = "interval value is too small";

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

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

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

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

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

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

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

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

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

764 765 766 767 768
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";
769
  const char* msg5 = "only the primary time stamp column can be used in session window";
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

  // 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) {
802
    return buildInvalidOperationMsg(pMsgBuf, msg5);
803 804
  }

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

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

// parse the window_state
815 816
int32_t validateStateWindowNode(SQueryStmtInfo *pQueryInfo, SWindowStateVal* pWindowState, SMsgBuf* pMsgBuf) {
  const char* msg1 = "invalid column name";
817 818
  const char* msg2 = "invalid column type to create state window";
  const char* msg3 = "not support state_window with group by";
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
  const char* msg4 = "function not support for super table query";
  const char* msg5 = "not support state_window on tag column";

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

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

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

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

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

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

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

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

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

// 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) {
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
  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);
    }
  }
921 922 923
}

int32_t validateOrderbyNode(SQueryStmtInfo *pQueryInfo, SSqlNode* pSqlNode, SMsgBuf* pMsgBuf) {
924 925 926 927 928 929 930 931 932
  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;
  }

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

935 936 937 938 939 940 941 942 943 944
  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);
945
  if ((UTIL_TABLE_IS_NORMAL_TABLE(pTableMetaInfo) || UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) && (pQueryInfo->info.projectionQuery)) {
946 947 948 949 950 951
    if (size > 1) {
      return buildInvalidOperationMsg(pMsgBuf, msg3);
    }
  }

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

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

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

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

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

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

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

986 987
      SOrder c = {0};
      setColumn(&c.col, pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, TSDB_COL_TMP, &pExprInfo->base.resSchema);
988
      c.order = pItem->sortOrder;
989 990 991
      taosArrayPush(pQueryInfo->order, &c);
    }
  }
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

  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
1123
        if (pExpr->base.pColumns->colIndex != index.columnIndex && index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_ID) {
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
          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;
1140
          for (int32_t i = 0; i < getNumOfExprs(pQueryInfo); ++i) {
1141
            SExprInfo* pExpr = getExprInfo(pQueryInfo, i);
1142
            if (getExprFunctionId(pExpr) == FUNCTION_PRJ && pExpr->base.pColumns->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
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
              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);

1223
        if (pExpr->base.pColumns->colIndex != index.columnIndex && index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_ID) {
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
          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 已提交
1256
static int32_t checkFillQueryRange(SQueryStmtInfo* pQueryInfo, SMsgBuf* pMsgBuf) {
1257
  const char* msg1 = "start(end) time of time range required or time range too large";
1258 1259 1260 1261 1262

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

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

  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) {
1277
      return buildInvalidOperationMsg(pMsgBuf, msg1);
1278 1279 1280 1281
    }
  }

  return TSDB_CODE_SUCCESS;
1282 1283 1284
}

int32_t validateFillNode(SQueryStmtInfo *pQueryInfo, SSqlNode* pSqlNode, SMsgBuf* pMsgBuf) {
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
  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 已提交
1303
  if (checkFillQueryRange(pQueryInfo, pMsgBuf) != TSDB_CODE_SUCCESS) {
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
    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;
1392 1393
}

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

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

1426
  if (pSqlNode->from->type == SQL_FROM_NODE_SUBQUERY) {
1427 1428 1429 1430 1431
    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) {
1432
      SRelElement* subInfo = taosArrayGet(pSqlNode->from->list, i);
1433
      code = doValidateSubquery(pSqlNode, i, pQueryInfo, pMsgBuf);
1434 1435 1436 1437 1438 1439
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
    }

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

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

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

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

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

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

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

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

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

      // parse the window_state
1489
      if (validateStateWindowNode(pQueryInfo, &pSqlNode->windowstateVal, pMsgBuf) != TSDB_CODE_SUCCESS) {
1490 1491 1492 1493 1494 1495
        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);
1496
    if (validateHavingNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1497 1498 1499
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1586 1587
  pushDownAggFuncExprInfo(pQueryInfo);
//  addColumnNodeFromLowerLevel(pQueryInfo);
1588 1589

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

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

1598 1599 1600
  return TSDB_CODE_SUCCESS;  // Does not build query message here
}

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

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

// todo extract the table column in expression

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

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

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

  return false;
}

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

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

  return true;
}

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

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

1651 1652 1653 1654 1655 1656
  return true;
}

static SExprInfo* createColumnNodeFromAggFunc(SSchema* pSchema);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

H
Haojun Liao 已提交
1742 1743 1744 1745 1746
  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";
1747 1748
  const char* msg6 = "not support distinct mixed with join";
  const char* msg7 = "not support distinct mixed with groupby";
1749 1750
  const char* msg8 = "block_dist not support subquery, only support stable/table";
  const char* msg9 = "time window aggregate can not be mixed up with group by column";
H
Haojun Liao 已提交
1751 1752 1753 1754 1755 1756

  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
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
    if (pQueryInfo->order != NULL) {
      size_t numOfOrder = taosArrayGetSize(pQueryInfo->order);
      if (numOfOrder > 1) {
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }

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

    // 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);
    }
1776 1777 1778 1779 1780 1781

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

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

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

        continue;
      }

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

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

        continue;
      }
    }
H
Haojun Liao 已提交
1811
  }
1812

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

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

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

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

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

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

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

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

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

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

1926 1927 1928 1929 1930 1931 1932
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);
1933

1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
    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);
  }
}

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

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

1960
  uint64_t uid = pTableMetaInfo->pTableMeta->uid;
1961

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

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

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

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

1981
  if (finalResult) {
1982
    addResColumnInfo(pQueryInfo, outputIndex, pResultSchema, pExpr);
1983 1984
  }

1985
  return pExpr;
1986 1987
}

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

1994
static int32_t addOneExprInfo(SQueryStmtInfo* pQueryInfo, tSqlExprItem* pItem, int32_t functionId, int32_t outputIndex, SSchema* pSchema, SColumnIndex* pColIndex, tExprNode* pNode, bool finalResult, SMsgBuf* pMsgBuf) {
1995 1996 1997 1998 1999 2000 2001
  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);
    }
  }

2002 2003 2004
  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);
2005

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

2009
  SSchema resultSchema = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), name);
2010 2011

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

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

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

2021 2022 2023
  return TSDB_CODE_SUCCESS;
}

2024 2025 2026 2027 2028 2029 2030 2031 2032
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;
}

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

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

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

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

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

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

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

2076 2077 2078
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";
2079

2080 2081 2082 2083 2084 2085
  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 {
2086 2087 2088 2089 2090 2091
    tSqlExprItem* pParamElem = taosArrayGet(pParamList, 0);

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

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

2099 2100 2101
      *index = (SColumnIndex) {0, PRIMARYKEY_TIMESTAMP_COL_ID, false};
      *columnSchema = *(SSchema*) getOneColumnSchema(pTableMeta, index->columnIndex);
    } else if (pToken->z != NULL && pToken->n > 0) {
2102 2103
      // count the number of table created according to the super table
      if (getColumnIndexByName(pToken, pQueryInfo, index, pMsgBuf) != TSDB_CODE_SUCCESS) {
2104 2105 2106 2107 2108 2109 2110 2111 2112
        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);
2113 2114 2115 2116 2117 2118 2119 2120 2121
      }
    }
  }

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

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

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

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

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

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

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

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

2189 2190
  pQueryInfo->exprListLevelIndex += 1;

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

2203 2204 2205 2206
      if (!scalarFunc) {
        return buildInvalidOperationMsg(pMsgBuf, msg6);
      }

2207 2208 2209 2210 2211
      SArray* pExprList = getCurrentExprList(pQueryInfo);
      size_t n = taosArrayGetSize(pExprList);

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

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

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

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

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

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

  pQueryInfo->exprListLevelIndex -= 1;
2255 2256 2257 2258 2259 2260
  return TSDB_CODE_SUCCESS;
}

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

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

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

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

  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]";
2296 2297 2298 2299 2300
  const char* msg13 = "nested function is not supported";

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

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

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

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

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

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

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

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

2331
      int32_t outputIndex = getNumOfFields(&pQueryInfo->fieldsInfo);
2332 2333 2334 2335

      char fname[FUNCTIONS_NAME_MAX_LENGTH] = {0};
      extractFunctionName(fname, pItem);
      doAddOneExprInfo(pQueryInfo, fname, &param, outputIndex, pTableMetaInfo, &s, size, token, finalResult);
2336 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
      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);

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

2368 2369 2370 2371 2372
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
      
      if (tokenId == TK_ALL || tokenId == TK_ID) {
2373 2374 2375 2376 2377
        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);
        }
2378 2379
      }

2380 2381
      int32_t precision = pTableMetaInfo->pTableMeta->tableInfo.precision;

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

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

2394 2395 2396 2397
      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);
2398

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

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

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

2407
      SExprInfo* pExpr = doAddOneExprInfo(pQueryInfo, funcName, &param, numOfOutput, pTableMetaInfo, &s, resInfo.intermediateBytes, token, finalResult);
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
      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) {
2423
        addExprInfoParam(&pExpr->base, (char*) &precision, TSDB_DATA_TYPE_BIGINT, LONG_BYTES);
2424 2425 2426 2427
      } else if (functionId == FUNCTION_DERIVATIVE) {
        char val[8] = {0};

        int64_t tickPerSec = 0;
2428
        code = getTickPerSecond(&pParamElem[1].pNode->value, precision, &tickPerSec, pMsgBuf);
2429 2430
        if (code != TSDB_CODE_SUCCESS) {
          return code;
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 2460 2461
        }

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

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

2466
        // in first/last function, multiple columns can be add to resultset
2467 2468
        for (int32_t i = 0; i < taosArrayGetSize(pParamList); ++i) {
          tSqlExprItem* pParamElem = taosArrayGet(pParamList, i);
2469
          doHandleOneParam(pQueryInfo, pItem, pParamElem, functionId, &colIndex, finalResult, pMsgBuf);
2470
        }
2471
      } else {  // select function(*) from xxx
2472 2473 2474 2475 2476 2477 2478 2479 2480
        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);
2481
          doAddAllColumnExprInSelectClause(pQueryInfo, pTableMetaInfo, pItem, functionId, j, &colIndex, finalResult, pMsgBuf);
2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493
          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
2494 2495
      if ((code = checkForkParam(pItem->pNode, 2, pMsgBuf)) != TSDB_CODE_SUCCESS) {
        return code;
2496 2497 2498
      }

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

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

      // 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
2520
      if (!IS_NUMERIC_TYPE(columnSchema.type)) {
2521 2522 2523 2524 2525 2526 2527 2528
        return buildInvalidOperationMsg(pMsgBuf, msg1);
      }

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

2529
      SResultDataInfo resInfo = {0};
2530 2531 2532 2533 2534 2535
      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
      }
2536

2537
      SSchema s = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), "");
2538

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

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

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

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

2551 2552 2553 2554 2555 2556
      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);
2557 2558 2559 2560 2561 2562

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

      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
2583 2584
      if ((code = checkForkParam(pItem->pNode, 1, pMsgBuf)) != TSDB_CODE_SUCCESS) {
        return code;
2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619
      }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      doAddOneExprInfo(pQueryInfo, funcName, &param, colIndex, pTableMetaInfo, &s, resInfo.intermediateBytes, token, finalResult);
2728 2729
      return TSDB_CODE_SUCCESS;
    }
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
    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);
      }

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

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

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

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

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

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

  return TSDB_CODE_TSC_INVALID_OPERATION;
}

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

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

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

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

  return TSDB_CODE_SUCCESS;
}

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

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

  int32_t outputIndex = (int32_t)getNumOfExprs(pQueryInfo);

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

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

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

  return TSDB_CODE_SUCCESS;
}

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

  return code;
}

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

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

2870 2871 2872 2873
  tSqlExpr sqlNode = {0};
  sqlNode.type = SQL_NODE_TABLE_COLUMN;
  sqlNode.columnName = colNameToken;

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

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

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

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

  pExpr->base.numOfCols = num;
2898 2899 2900 2901 2902 2903

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

2904
  pQueryInfo->info.projectionQuery = true;
2905
  return TSDB_CODE_SUCCESS;
2906 2907
}

H
Haojun Liao 已提交
2908
static int32_t doAddMultipleProjectExprAndResColumns(SQueryStmtInfo* pQueryInfo, SColumnIndex* pIndex, int32_t startPos, SMsgBuf* pMsgBuf) {
2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919
  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) {
2920
    SSchema* pSchema = getOneColumnSchema(pTableMetaInfo->pTableMeta, j);
H
Haojun Liao 已提交
2921
    doAddOneProjectCol(pQueryInfo, startPos + j, pSchema, NULL, getNewResColId(), pMsgBuf);
2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958
  }

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

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

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

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

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

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

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

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

2990 2991 2992 2993
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";

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

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

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

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

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

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

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

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

3037
    SExprInfo* pExpr = doAddOneExprInfo(pQueryInfo, "project", &param, startPos, pTableMetaInfo, &colSchema, 0, token, true);
3038 3039 3040
    // 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);
3041
  } else if (tokenId == TK_ID) {  // column name
3042 3043 3044 3045 3046 3047
    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) {
3048
      handleTbnameProjection(pQueryInfo, pItem, &index, startPos, outerQuery, pMsgBuf);
3049 3050 3051 3052 3053 3054
    } else {
      STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);
      if (TSDB_COL_IS_TAG(index.type) && UTIL_TABLE_IS_NORMAL_TABLE(pTableMetaInfo)) {
        return buildInvalidOperationMsg(pMsgBuf, msg1);
      }

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

    // 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)) {
3062 3063
      STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;
      insertPrimaryTsColumn(pQueryInfo->colList, pTableMeta->schema[0].name, pTableMeta->uid);
3064 3065 3066
    }
  } else {
    return TSDB_CODE_TSC_INVALID_OPERATION;
3067 3068
  }

3069 3070 3071
  return TSDB_CODE_SUCCESS;
}

3072
static int32_t validateExprLeafNode(tSqlExpr* pExpr, SQueryStmtInfo* pQueryInfo, SArray* pList, int32_t* type, SMsgBuf* pMsgBuf) {
3073 3074 3075 3076 3077
  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;
3078
    }
3079

3080 3081 3082
    int32_t code = validateExprLeafColumnNode(pQueryInfo, &pExpr->columnName, pList, pMsgBuf);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
3083
    }
3084 3085 3086 3087 3088 3089 3090 3091 3092 3093
  } 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;
    }

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

3100 3101
  return TSDB_CODE_SUCCESS;
}
3102

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

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

  bool found = false;
  uint64_t uid = 0;

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

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

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

  return uid;
}

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

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

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

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

3147 3148
  *(SSchema*)(pExpr->pSchema) = *pSchema;

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

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

3162 3163 3164
  return pExpr;
}

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

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

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

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

3182 3183
static int32_t validateSqlExpr(const tSqlExpr* pSqlExpr, SQueryStmtInfo *pQueryInfo, SMsgBuf* pMsgBuf);

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

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

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

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

    *num = 1;
3210
    (*p) = calloc(*num, POINTER_BYTES);
3211 3212

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

  return TSDB_CODE_SUCCESS;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return TSDB_CODE_SUCCESS;
}

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

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

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

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

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

3347
    *keepTableCols = false;
3348

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

3356
    int32_t outputIndex = (int32_t)getNumOfExprs(pQueryInfo);
3357

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

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

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

      pQueryInfo->exprListLevelIndex -= 1;
      // convert the aggregate function to be the input data columns for the outer function.
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

  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) {
3405
      // Expression on the results of aggregation functions
3406 3407 3408 3409 3410
      *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);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

3507
  pExpr->base.numOfCols = num;
3508

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

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

3524
  tbufCloseWriter(&bw);
3525

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

3531
  //    tbufCloseWriter(&bw); // TODO there is a memory leak
3532

3533
  taosArrayDestroy(pColumnList);
3534 3535 3536 3537 3538 3539 3540 3541 3542
  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 已提交
3543
  const char* msg4 = "distinct should be in the first place in select clause";
3544 3545 3546 3547 3548 3549 3550
  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);
  }

3551 3552
  int32_t code = TSDB_CODE_SUCCESS;
  size_t  numOfExpr = taosArrayGetSize(pSelNodeList);
3553 3554

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

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

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

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

H
Haojun Liao 已提交
3577
//        pItem->functionId = functionId;
3578 3579
      }

3580
      if (scalarFunc) { // scalar function
3581
        if ((code = addScalarExprAndResColumn(pQueryInfo, outputIndex, pItem, pMsgBuf)) != TSDB_CODE_SUCCESS) {
3582 3583 3584 3585 3586 3587 3588
          return code;
        }
      } else { // aggregate function
        // sql function in selection clause, append sql function info in pSqlCmd structure sequentially
        if ((code = addAggExprAndResColumn(pQueryInfo, outputIndex, pItem, true, pMsgBuf)) != TSDB_CODE_SUCCESS) {
          return code;
        }
3589 3590 3591
      }
    } 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
3592
      // select table_name1.field_name1, table_name2.field_name2 from table_name1, table_name2
3593 3594
      if ((code = addProjectionExprAndResColumn(pQueryInfo, pItem, outerQuery, pMsgBuf)) != TSDB_CODE_SUCCESS) {
        return code;
3595 3596
      }
    } else if (type == SQL_NODE_EXPR) {
3597
      if ((code = addScalarExprAndResColumn(pQueryInfo, i, pItem, pMsgBuf)) != TSDB_CODE_SUCCESS) {
3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609
        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);
3610

3611
  // Evaluate expression in where clause
3612 3613 3614 3615 3616 3617
  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;
    }
3618 3619
  }

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

3630
  return TSDB_CODE_SUCCESS;
3631
}
H
Haojun Liao 已提交
3632

3633 3634 3635
int32_t qParserValidateSqlNode(struct SCatalog* pCatalog, SSqlInfo* pInfo, SQueryStmtInfo* pQueryInfo, int64_t id, char* msgBuf, int32_t msgBufLen) {
  assert(pCatalog != NULL && pInfo != NULL);
  int32_t code = 0;
3636 3637 3638 3639

  SMsgBuf m = {.buf = msgBuf, .len = msgBufLen};
  SMsgBuf *pMsgBuf = &m;

3640
  switch (pInfo->type) {
3641
#if 0
3642 3643 3644 3645 3646 3647 3648 3649 3650
    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);
3651
      if ((pInfo->type != TSDB_SQL_DROP_DNODE) && (parserValidateIdToken(pzName) != TSDB_CODE_SUCCESS)) {
3652
        return buildInvalidOperationMsg(pMsgBuf, msg2);
3653 3654 3655 3656 3657 3658
      }

      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) {
3659
          return buildInvalidOperationMsg(pMsgBuf, msg2);
3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675
        }

      } 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) {
3676
          return buildInvalidOperationMsg(pMsgBuf, msg3);
3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689
        }

        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) {
3690
        return buildInvalidOperationMsg(pMsgBuf, msg);
3691 3692 3693 3694
      }

      int32_t ret = tNameSetDbName(&pTableMetaInfo->name, getAccountId(pSql), pToken);
      if (ret != TSDB_CODE_SUCCESS) {
3695
        return buildInvalidOperationMsg(pMsgBuf, msg);
3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718
      }

      break;
    }

    case TSDB_SQL_RESET_CACHE: {
      return TSDB_CODE_SUCCESS;
    }

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

      break;
    }

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

      if (taosArrayGetSize(pInfo->pMiscInfo->a) > 1) {
3719
        return buildInvalidOperationMsg(pMsgBuf, msg);
3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742
      }

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

      if (tscValidateName(pName) != TSDB_CODE_SUCCESS) {
3747
        return buildInvalidOperationMsg(pMsgBuf, msg2);
3748 3749 3750 3751 3752 3753 3754 3755 3756
      }

      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 {
3757
          return buildInvalidOperationMsg(pMsgBuf, msg1);
3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768
        }
      }

      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) {
3769
        return buildInvalidOperationMsg(pMsgBuf, msg1);
3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784
      }
      // 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) {
3785
        return buildInvalidOperationMsg(pMsgBuf, msg1);
3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799
      }

      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) {
3800
        return buildInvalidOperationMsg(pMsgBuf, msg1);
3801 3802 3803
      }

      if (pToken->n > TSDB_DB_NAME_LEN) {
3804
        return buildInvalidOperationMsg(pMsgBuf, msg1);
3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816
      }
      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) {
3817
        return buildInvalidOperationMsg(pMsgBuf, msg2);
3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830
      }

      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) {
3831
        return buildInvalidOperationMsg(pMsgBuf, msg3);
3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851
      }

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

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

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

      break;
    }

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

      // validate the parameter names and options
      if (validateLocalConfig(pMiscInfo) != TSDB_CODE_SUCCESS) {
3852
        return buildInvalidOperationMsg(pMsgBuf, msg);
3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905
      }

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

3906
        if (size > 1 && pSqlNode->from && pSqlNode->from->type == SQL_FROM_NODE_SUBQUERY) {
3907
          return buildInvalidOperationMsg(pMsgBuf, msg1);
3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940
        }

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

3941
      STableMetaInfo* pTableMetaInfo1 = getMetaInfo(pCmd->active, 0);
3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968
      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 已提交
3969

3970 3971 3972
      assert(taosArrayGetSize(pInfo->pMiscInfo->a) == 1);
      code = tNameSetDbName(&pTableMetaInfo->name, getAccountId(pSql), pzName);
      if (code != TSDB_CODE_SUCCESS) {
3973
        return buildInvalidOperationMsg(pMsgBuf, msg1);
3974 3975 3976 3977 3978 3979
      }
      break;
    }
    case TSDB_SQL_COMPACT_VNODE:{
      const char* msg = "invalid compact";
      if (setCompactVnodeInfo(pSql, pInfo) != TSDB_CODE_SUCCESS) {
3980
        return buildInvalidOperationMsg(pMsgBuf, msg);
3981 3982 3983
      }
      break;
    }
3984
    #endif
3985
    default:
3986
      return buildInvalidOperationMsg(pMsgBuf, "not support sql expression");
3987
  }
3988

H
Haojun Liao 已提交
3989

D
dapan1121 已提交
3990
  SCatalogReq req = {0};
3991
  SMetaData data = {0};
H
Haojun Liao 已提交
3992

3993
  // TODO: check if the qnode info has been cached already
D
dapan1121 已提交
3994
  req.qNodeRequired = true;
3995
  code = qParserExtractRequestedMetaInfo(pInfo, &req, msgBuf, msgBufLen);
3996 3997 3998
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
3999 4000

  // load the meta data from catalog
D
dapan1121 已提交
4001
  code = catalogGetAllMeta(pCatalog, NULL, NULL, &req, &data);
4002 4003 4004
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
4005 4006

  // evaluate the sqlnode
4007 4008 4009
  STableMeta* pTableMeta = (STableMeta*) taosArrayGetP(data.pTableMeta, 0);
  assert(pTableMeta != NULL);

4010 4011
  SMsgBuf buf = {.buf = msgBuf, .len = msgBufLen};

4012
  size_t len = taosArrayGetSize(pInfo->sub.node);
4013
  for(int32_t i = 0; i < len; ++i) {
4014
    SSqlNode* p = taosArrayGetP(pInfo->sub.node, i);
4015
    code = evaluateSqlNode(p, pTableMeta->tableInfo.precision, &buf);
4016 4017 4018 4019
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }
4020

4021
  for(int32_t i = 0; i < len; ++i) {
4022
    SSqlNode* p = taosArrayGetP(pInfo->sub.node, i);
4023 4024 4025
    validateSqlNode(p, pQueryInfo, &buf);
  }

4026

4027
  return code;
H
Haojun Liao 已提交
4028
}
4029

4030
// todo remove it
4031
static int32_t setShowInfo(SShowInfo* pShowInfo, SParseBasicCtx *pCtx, void** output, int32_t* outputLen, SMsgBuf* pMsgBuf) {
4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043
  const char* msg1 = "invalid name";
  const char* msg2 = "wildcard string should be less than %d characters";
  const char* msg3 = "database name too long";
  const char* msg4 = "pattern is invalid";
  const char* msg5 = "database name is empty";
  const char* msg6 = "pattern string is empty";

  /*
   * database prefix in pInfo->pMiscInfo->a[0]
   * wildcard in like clause in pInfo->pMiscInfo->a[1]
   */
  int16_t    showType = pShowInfo->showType;
4044
  if (showType == TSDB_MGMT_TABLE_STB || showType == TSDB_MGMT_TABLE_VGROUP) {
4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092
    SToken* pDbPrefixToken = &pShowInfo->prefix;
    if (pDbPrefixToken->type != 0) {
      if (pDbPrefixToken->n >= TSDB_DB_NAME_LEN) {  // db name is too long
        return buildInvalidOperationMsg(pMsgBuf, msg3);
      }

      if (pDbPrefixToken->n <= 0) {
        return buildInvalidOperationMsg(pMsgBuf, msg5);
      }

      if (parserValidateIdToken(pDbPrefixToken) != TSDB_CODE_SUCCESS) {
        return buildInvalidOperationMsg(pMsgBuf, msg1);
      }

      //      int32_t ret = tNameSetDbName(&pTableMetaInfo->name, getAccountId(pRequest->pTsc), pDbPrefixToken);
      //      if (ret != TSDB_CODE_SUCCESS) {
      //        return buildInvalidOperationMsg(pMsgBuf, msg1);
      //      }
    }

    // show table/stable like 'xxxx', set the like pattern for show tables
    SToken* pPattern = &pShowInfo->pattern;
    if (pPattern->type != 0) {
      if (pPattern->type == TK_ID && pPattern->z[0] == TS_ESCAPE_CHAR) {
        return buildInvalidOperationMsg(pMsgBuf, msg4);
      }

      pPattern->n = strdequote(pPattern->z);
      if (pPattern->n <= 0) {
        return buildInvalidOperationMsg(pMsgBuf, msg6);
      }

      if (pPattern->n > tsMaxWildCardsLen) {
        char tmp[64] = {0};
        sprintf(tmp, msg2, tsMaxWildCardsLen);
        return buildInvalidOperationMsg(pMsgBuf, tmp);
      }
    }
  } else if (showType == TSDB_MGMT_TABLE_VNODES) {
    if (pShowInfo->prefix.type == 0) {
      return buildInvalidOperationMsg(pMsgBuf, "No specified dnode ep");
    }

    if (pShowInfo->prefix.type == TK_STRING) {
      pShowInfo->prefix.n = strdequote(pShowInfo->prefix.z);
    }
  }

4093 4094
  *output = buildShowMsg(pShowInfo, pCtx->requestId, pMsgBuf->buf, pMsgBuf->len);
  *outputLen = sizeof(SShowMsg)/* + htons(pShowMsg->payloadLen)*/;
H
Haojun Liao 已提交
4095 4096 4097 4098 4099 4100
  return TSDB_CODE_SUCCESS;
}

// can only perform the parameters based on the macro definitation
static int32_t doCheckDbOptions(SCreateDbMsg* pCreate, SMsgBuf* pMsgBuf) {
  char msg[512] = {0};
4101

H
Haojun Liao 已提交
4102 4103 4104 4105
  if (pCreate->walLevel != -1 && (pCreate->walLevel < TSDB_MIN_WAL_LEVEL || pCreate->walLevel > TSDB_MAX_WAL_LEVEL)) {
    snprintf(msg, tListLen(msg), "invalid db option walLevel: %d, only 1-2 allowed", pCreate->walLevel);
    return buildInvalidOperationMsg(pMsgBuf, msg);
  }
4106

H
Haojun Liao 已提交
4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167
  if (pCreate->replications != -1 &&
      (pCreate->replications < TSDB_MIN_DB_REPLICA_OPTION || pCreate->replications > TSDB_MAX_DB_REPLICA_OPTION)) {
    snprintf(msg, tListLen(msg), "invalid db option replications: %d valid range: [%d, %d]", pCreate->replications,
             TSDB_MIN_DB_REPLICA_OPTION, TSDB_MAX_DB_REPLICA_OPTION);
    return buildInvalidOperationMsg(pMsgBuf, msg);
  }

  int32_t blocks = ntohl(pCreate->totalBlocks);
  if (blocks != -1 && (blocks < TSDB_MIN_TOTAL_BLOCKS || blocks > TSDB_MAX_TOTAL_BLOCKS)) {
    snprintf(msg, tListLen(msg), "invalid db option totalBlocks: %d valid range: [%d, %d]", blocks,
             TSDB_MIN_TOTAL_BLOCKS, TSDB_MAX_TOTAL_BLOCKS);
    return buildInvalidOperationMsg(pMsgBuf, msg);
  }

  if (pCreate->quorum != -1 &&
      (pCreate->quorum < TSDB_MIN_DB_QUORUM_OPTION || pCreate->quorum > TSDB_MAX_DB_QUORUM_OPTION)) {
    snprintf(msg, tListLen(msg), "invalid db option quorum: %d valid range: [%d, %d]", pCreate->quorum,
             TSDB_MIN_DB_QUORUM_OPTION, TSDB_MAX_DB_QUORUM_OPTION);
    return buildInvalidOperationMsg(pMsgBuf, msg);
  }

  int32_t val = htonl(pCreate->daysPerFile);
  if (val != -1 && (val < TSDB_MIN_DAYS_PER_FILE || val > TSDB_MAX_DAYS_PER_FILE)) {
    snprintf(msg, tListLen(msg), "invalid db option daysPerFile: %d valid range: [%d, %d]", val,
             TSDB_MIN_DAYS_PER_FILE, TSDB_MAX_DAYS_PER_FILE);
    return buildInvalidOperationMsg(pMsgBuf, msg);
  }

  val = htonl(pCreate->cacheBlockSize);
  if (val != -1 && (val < TSDB_MIN_CACHE_BLOCK_SIZE || val > TSDB_MAX_CACHE_BLOCK_SIZE)) {
    snprintf(msg, tListLen(msg), "invalid db option cacheBlockSize: %d valid range: [%d, %d]", val,
             TSDB_MIN_CACHE_BLOCK_SIZE, TSDB_MAX_CACHE_BLOCK_SIZE);
    return buildInvalidOperationMsg(pMsgBuf, msg);
  }

  if (pCreate->precision != TSDB_TIME_PRECISION_MILLI && pCreate->precision != TSDB_TIME_PRECISION_MICRO &&
      pCreate->precision != TSDB_TIME_PRECISION_NANO) {
    snprintf(msg, tListLen(msg), "invalid db option timePrecision: %d valid value: [%d, %d, %d]", pCreate->precision,
             TSDB_TIME_PRECISION_MILLI, TSDB_TIME_PRECISION_MICRO, TSDB_TIME_PRECISION_NANO);
    return buildInvalidOperationMsg(pMsgBuf, msg);
  }

  val = htonl(pCreate->commitTime);
  if (val != -1 && (val < TSDB_MIN_COMMIT_TIME || val > TSDB_MAX_COMMIT_TIME)) {
    snprintf(msg, tListLen(msg), "invalid db option commitTime: %d valid range: [%d, %d]", val,
             TSDB_MIN_COMMIT_TIME, TSDB_MAX_COMMIT_TIME);
    return buildInvalidOperationMsg(pMsgBuf, msg);
  }

  val = htonl(pCreate->fsyncPeriod);
  if (val != -1 && (val < TSDB_MIN_FSYNC_PERIOD || val > TSDB_MAX_FSYNC_PERIOD)) {
    snprintf(msg, tListLen(msg), "invalid db option fsyncPeriod: %d valid range: [%d, %d]", val,
             TSDB_MIN_FSYNC_PERIOD, TSDB_MAX_FSYNC_PERIOD);
    return buildInvalidOperationMsg(pMsgBuf, msg);
  }

  if (pCreate->compression != -1 &&
      (pCreate->compression < TSDB_MIN_COMP_LEVEL || pCreate->compression > TSDB_MAX_COMP_LEVEL)) {
    snprintf(msg, tListLen(msg), "invalid db option compression: %d valid range: [%d, %d]", pCreate->compression,
             TSDB_MIN_COMP_LEVEL, TSDB_MAX_COMP_LEVEL);
    return buildInvalidOperationMsg(pMsgBuf, msg);
4168 4169 4170 4171 4172
  }

  return TSDB_CODE_SUCCESS;
}

4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247
/* is contained in pFieldList or not */
static bool has(SArray* pFieldList, int32_t startIndex, const char* name) {
  size_t numOfCols = taosArrayGetSize(pFieldList);
  for (int32_t j = startIndex; j < numOfCols; ++j) {
    TAOS_FIELD* field = taosArrayGet(pFieldList, j);
    if (strncasecmp(name, field->name, sizeof(field->name) - 1) == 0) return true;
  }

  return false;
}

static int32_t validateTableColumns(SArray* pFieldList, int32_t maxRowLength, int32_t maxColumns, SMsgBuf* pMsgBuf) {
  const char* msg2 = "row length exceeds max length";
  const char* msg3 = "duplicated column names";
  const char* msg4 = "invalid data type";
  const char* msg5 = "invalid binary/nchar column length";
  const char* msg6 = "invalid column name";
  const char* msg7 = "too many columns";
  const char* msg8 = "illegal number of columns";

  size_t numOfCols = taosArrayGetSize(pFieldList);
  if (numOfCols > maxColumns) {
    return buildInvalidOperationMsg(pMsgBuf, msg7);
  }

  int32_t rowLen = 0;
  for (int32_t i = 0; i < numOfCols; ++i) {
    TAOS_FIELD* pField = taosArrayGet(pFieldList, i);
    if (!isValidDataType(pField->type)) {
      return buildInvalidOperationMsg(pMsgBuf, msg4);
    }

    if (pField->bytes == 0) {
      return buildInvalidOperationMsg(pMsgBuf, msg5);
    }

    if ((pField->type == TSDB_DATA_TYPE_BINARY && (pField->bytes <= 0 || pField->bytes > TSDB_MAX_BINARY_LEN)) ||
        (pField->type == TSDB_DATA_TYPE_NCHAR && (pField->bytes <= 0 || pField->bytes > TSDB_MAX_NCHAR_LEN))) {
      return buildInvalidOperationMsg(pMsgBuf, msg5);
    }

    SToken nameToken = {.z = pField->name, .n = strlen(pField->name), .type = TK_ID};
    if (parserValidateNameToken(&nameToken) != TSDB_CODE_SUCCESS) {
      return buildInvalidOperationMsg(pMsgBuf, msg6);
    }

    // field name must be unique
    if (has(pFieldList, i + 1, pField->name) == true) {
      return buildInvalidOperationMsg(pMsgBuf, msg3);
    }

    rowLen += pField->bytes;
  }

  // max row length must be less than TSDB_MAX_BYTES_PER_ROW
  if (rowLen > maxRowLength) {
    return buildInvalidOperationMsg(pMsgBuf, msg2);
  }

  return TSDB_CODE_SUCCESS;
}

static int32_t validateTableColumnInfo(SArray* pFieldList, SMsgBuf* pMsgBuf) {
  assert(pFieldList != NULL);

  const char* msg1 = "first column must be timestamp";
  const char* msg2 = "row length exceeds max length";
  const char* msg3 = "duplicated column names";
  const char* msg4 = "invalid data type";
  const char* msg5 = "invalid binary/nchar column length";
  const char* msg6 = "invalid column name";
  const char* msg7 = "too many columns";
  const char* msg8 = "illegal number of columns";

  // first column must be timestamp
4248
  SField* pField = taosArrayGet(pFieldList, 0);
4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275
  if (pField->type != TSDB_DATA_TYPE_TIMESTAMP) {
    return buildInvalidOperationMsg(pMsgBuf, msg1);
  }

  // number of fields no less than 2
  size_t numOfCols = taosArrayGetSize(pFieldList);
  if (numOfCols <= 1) {
    return buildInvalidOperationMsg(pMsgBuf, msg8);
  }

  return validateTableColumns(pFieldList, TSDB_MAX_BYTES_PER_ROW, TSDB_MAX_COLUMNS, pMsgBuf);
}

static int32_t validateTagParams(SArray* pTagsList, SArray* pFieldList, SMsgBuf* pMsgBuf) {
  assert(pTagsList != NULL);

  const char* msg1 = "invalid number of tag columns";
  const char* msg3 = "duplicated column names";

  // number of fields at least 1
  size_t numOfTags = taosArrayGetSize(pTagsList);
  if (numOfTags < 1) {
    return buildInvalidOperationMsg(pMsgBuf, msg1);
  }

  // field name must be unique
  for (int32_t i = 0; i < numOfTags; ++i) {
4276
    SField* p = taosArrayGet(pTagsList, i);
4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308
    if (has(pFieldList, 0, p->name) == true) {
      return buildInvalidOperationMsg(pMsgBuf, msg3);
    }
  }

  return validateTableColumns(pFieldList, TSDB_MAX_TAGS_LEN, TSDB_MAX_TAGS, pMsgBuf);
}

int32_t doCheckForCreateTable(SSqlInfo* pInfo, SMsgBuf* pMsgBuf) {
  const char* msg1 = "invalid table name";

  SCreateTableSql* pCreateTable = pInfo->pCreateTableInfo;

  SArray* pFieldList = pCreateTable->colInfo.pColumns;
  SArray* pTagList = pCreateTable->colInfo.pTagColumns;
  assert(pFieldList != NULL);

  // if sql specifies db, use it, otherwise use default db
  SToken* pzTableName = &(pCreateTable->name);

  if (parserValidateNameToken(pzTableName) != TSDB_CODE_SUCCESS) {
    return buildInvalidOperationMsg(pMsgBuf, msg1);
  }

  if (validateTableColumnInfo(pFieldList, pMsgBuf) != TSDB_CODE_SUCCESS ||
      (pTagList != NULL && validateTagParams(pTagList, pFieldList, pMsgBuf) != TSDB_CODE_SUCCESS)) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
4309
int32_t qParserValidateDclSqlNode(SSqlInfo* pInfo, SParseBasicCtx* pCtx, SDclStmtInfo* pDcl, char* msgBuf, int32_t msgBufLen) {
4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359
  int32_t code = 0;

  SMsgBuf m = {.buf = msgBuf, .len = msgBufLen};
  SMsgBuf *pMsgBuf = &m;

  switch (pInfo->type) {
    case TSDB_SQL_CREATE_USER:
    case TSDB_SQL_ALTER_USER: {
      const char* msg1 = "not support options";
      const char* msg2 = "invalid user/account name";
      const char* msg3 = "name too long";
      const char* msg4 = "invalid user rights";

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

      if (pName->n >= TSDB_USER_LEN) {
        return buildInvalidOperationMsg(pMsgBuf, msg3);
      }

      if (parserValidateIdToken(pName) != TSDB_CODE_SUCCESS) {
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }

      if (pInfo->type == TSDB_SQL_CREATE_USER) {
        if (parserValidatePassword(pPwd, pMsgBuf) != TSDB_CODE_SUCCESS) {
          return TSDB_CODE_TSC_INVALID_OPERATION;
        }
      } else {
        if (pUser->type == TSDB_ALTER_USER_PASSWD) {
          if (parserValidatePassword(pPwd, pMsgBuf) != 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, "normal", 4) == 0 && pPrivilege->n == 4) {
            //            pCmd->count = 2;
          } else {
            return buildInvalidOperationMsg(pMsgBuf, msg4);
          }
        } else {
          return buildInvalidOperationMsg(pMsgBuf, msg1);
        }
      }

X
Xiaoyu Wang 已提交
4360
      pDcl->pMsg = (char*)buildUserManipulationMsg(pInfo, &pDcl->msgLen, pCtx->requestId, msgBuf, msgBufLen);
X
Xiaoyu Wang 已提交
4361
      pDcl->msgType = (pInfo->type == TSDB_SQL_CREATE_USER)? TSDB_MSG_TYPE_CREATE_USER:TSDB_MSG_TYPE_ALTER_USER;
4362 4363
      break;
    }
H
Haojun Liao 已提交
4364

4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396
    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 (parserValidatePassword(pPwd, pMsgBuf) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }

      if (pName->n >= TSDB_USER_LEN) {
        return buildInvalidOperationMsg(pMsgBuf, msg3);
      }

      if (parserValidateNameToken(pName) != TSDB_CODE_SUCCESS) {
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }

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

X
Xiaoyu Wang 已提交
4397
      pDcl->pMsg = (char*)buildAcctManipulationMsg(pInfo, &pDcl->msgLen, pCtx->requestId, msgBuf, msgBufLen);
X
Xiaoyu Wang 已提交
4398
      pDcl->msgType = (pInfo->type == TSDB_SQL_CREATE_ACCT)? TSDB_MSG_TYPE_CREATE_ACCT:TSDB_MSG_TYPE_ALTER_ACCT;
4399 4400 4401
      break;
    }

H
Haojun Liao 已提交
4402 4403
    case TSDB_SQL_DROP_ACCT:
    case TSDB_SQL_DROP_USER: {
X
Xiaoyu Wang 已提交
4404
      pDcl->pMsg = (char*)buildDropUserMsg(pInfo, &pDcl->msgLen, pCtx->requestId, msgBuf, msgBufLen);
X
Xiaoyu Wang 已提交
4405
      pDcl->msgType = (pInfo->type == TSDB_SQL_DROP_ACCT)? TSDB_MSG_TYPE_DROP_ACCT:TSDB_MSG_TYPE_DROP_USER;
H
Haojun Liao 已提交
4406 4407
      break;
    }
4408 4409
    
    case TSDB_SQL_SHOW: {
X
Xiaoyu Wang 已提交
4410
      code = setShowInfo(&pInfo->pMiscInfo->showOpt, pCtx, (void**)&pDcl->pMsg, &pDcl->msgLen, pMsgBuf);
X
Xiaoyu Wang 已提交
4411
      pDcl->msgType = TSDB_MSG_TYPE_SHOW;
4412 4413
      break;
    }
H
Haojun Liao 已提交
4414

4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431
    case TSDB_SQL_USE_DB: {
      const char* msg = "invalid db name";

      SToken* pToken = taosArrayGet(pInfo->pMiscInfo->a, 0);
      if (parserValidateNameToken(pToken) != TSDB_CODE_SUCCESS) {
        return buildInvalidOperationMsg(pMsgBuf, msg);
      }

      SName n = {0};
      int32_t ret = tNameSetDbName(&n, pCtx->acctId, pToken->z, pToken->n);
      if (ret != TSDB_CODE_SUCCESS) {
        return buildInvalidOperationMsg(pMsgBuf, msg);
      }

      SUseDbMsg *pUseDbMsg = (SUseDbMsg *) calloc(1, sizeof(SUseDbMsg));
      tNameExtractFullName(&n, pUseDbMsg->db);

X
Xiaoyu Wang 已提交
4432 4433
      pDcl->pMsg = (char*)pUseDbMsg;
      pDcl->msgLen = sizeof(SUseDbMsg);
X
Xiaoyu Wang 已提交
4434
      pDcl->msgType = TSDB_MSG_TYPE_USE_DB;
4435 4436 4437
      break;
    }

H
Haojun Liao 已提交
4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454
    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) {
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }

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

      if (parserValidateNameToken(&token) != TSDB_CODE_SUCCESS) {
        return buildInvalidOperationMsg(pMsgBuf, msg1);
      }

4455
      SCreateDbMsg* pCreateMsg = buildCreateDbMsg(pCreateDB, pCtx, pMsgBuf);
H
Haojun Liao 已提交
4456 4457 4458 4459 4460 4461
      if (doCheckDbOptions(pCreateMsg, pMsgBuf) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }

      strncpy(pCreateMsg->db, token.z, token.n);

X
Xiaoyu Wang 已提交
4462 4463
      pDcl->pMsg = (char*)pCreateMsg;
      pDcl->msgLen = sizeof(SCreateDbMsg);
X
Xiaoyu Wang 已提交
4464
      pDcl->msgType = (pInfo->type == TSDB_SQL_CREATE_DB)? TSDB_MSG_TYPE_CREATE_DB:TSDB_MSG_TYPE_ALTER_DB;
H
Haojun Liao 已提交
4465 4466 4467
      break;
    }

4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485
    case TSDB_SQL_DROP_DB: {
      const char* msg1 = "invalid database name";

      assert(taosArrayGetSize(pInfo->pMiscInfo->a) == 1);
      SToken* dbName = taosArrayGet(pInfo->pMiscInfo->a, 0);

      SName name = {0};
      code = tNameSetDbName(&name, pCtx->acctId, dbName->z, dbName->n);
      if (code != TSDB_CODE_SUCCESS) {
        return buildInvalidOperationMsg(pMsgBuf, msg1);
      }

      SDropDbMsg *pDropDbMsg = (SDropDbMsg*) calloc(1, sizeof(SDropDbMsg));

      code = tNameExtractFullName(&name, pDropDbMsg->db);
      pDropDbMsg->ignoreNotExists = pInfo->pMiscInfo->existsCheck ? 1 : 0;
      assert(code == TSDB_CODE_SUCCESS && name.type == TSDB_DB_NAME_T);

X
Xiaoyu Wang 已提交
4486
      pDcl->msgType = TSDB_MSG_TYPE_DROP_DB;
X
Xiaoyu Wang 已提交
4487 4488
      pDcl->msgLen = sizeof(SDropDbMsg);
      pDcl->pMsg = (char*)pDropDbMsg;
4489 4490 4491
      return TSDB_CODE_SUCCESS;
    }

4492 4493 4494 4495 4496 4497 4498
    case TSDB_SQL_CREATE_TABLE: {
      SCreateTableSql* pCreateTable = pInfo->pCreateTableInfo;

      if (pCreateTable->type == TSQL_CREATE_TABLE || pCreateTable->type == TSQL_CREATE_STABLE) {
        if ((code = doCheckForCreateTable(pInfo, pMsgBuf)) != TSDB_CODE_SUCCESS) {
          return code;
        }
X
Xiaoyu Wang 已提交
4499
        pDcl->pMsg = (char*)buildCreateTableMsg(pCreateTable, &pDcl->msgLen, pCtx, pMsgBuf);
X
Xiaoyu Wang 已提交
4500
        pDcl->msgType = (pCreateTable->type == TSQL_CREATE_TABLE)? TSDB_MSG_TYPE_CREATE_TABLE:TSDB_MSG_TYPE_CREATE_STB;
4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512
      } else if (pCreateTable->type == TSQL_CREATE_CTABLE) {
        //        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;
    }
4513 4514

    case TSDB_SQL_DROP_TABLE: {
X
Xiaoyu Wang 已提交
4515 4516
      pDcl->pMsg = (char*)buildDropTableMsg(pInfo, &pDcl->msgLen, pCtx, pMsgBuf);
      if (pDcl->pMsg == NULL) {
4517 4518 4519
        return terrno;
      }

X
Xiaoyu Wang 已提交
4520
      pDcl->msgType = TSDB_MSG_TYPE_DROP_STB;
4521 4522 4523 4524
      return TSDB_CODE_SUCCESS;
      break;
    }

4525 4526 4527 4528
    default:
      break;
  }

4529
  return code;
4530
}