astValidate.c 148.2 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 <function.h>
17
#include "astGenerator.h"
18
#include "function.h"
H
Haojun Liao 已提交
19
#include "parserInt.h"
20
#include "parserUtil.h"
21
#include "queryInfoUtil.h"
22 23 24 25
#include "tbuffer.h"
#include "tglobal.h"
#include "tmsgtype.h"
#include "ttime.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 762 763 764 765 766
  // It is a time window query
  pQueryInfo->info.timewindow = true;
  return TSDB_CODE_SUCCESS;
  // disable it temporarily
//  bool interpQuery = tscIsPointInterpQuery(pQueryInfo);
//  if ((pSqlNode->interval.token == TK_EVERY && (!interpQuery)) || (pSqlNode->interval.token == TK_INTERVAL && interpQuery)) {
//    return buildInvalidOperationMsg(pMsgBuf, msg4);
//  }
767 768
}

769 770 771 772 773
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";
774
  const char* msg5 = "only the primary time stamp column can be used in session window";
775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806

  // 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) {
807
    return buildInvalidOperationMsg(pMsgBuf, msg5);
808 809
  }

810 811 812 813 814
  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);
815
  pQueryInfo->info.sessionWindow = true;
816
  return TSDB_CODE_SUCCESS;
817 818 819
}

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

858
  pQueryInfo->stateWindow.col = createColumn(pTableMeta->uid, pTableMetaInfo->aliasName, index.type, pSchema);
859 860
  pQueryInfo->info.stateWindow = true;

861
  columnListInsert(pQueryInfo->colList, pTableMeta->uid, pSchema, index.type);
862
  return TSDB_CODE_SUCCESS;
863 864 865 866 867 868 869 870
}

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

int32_t validateOrderbyNode(SQueryStmtInfo *pQueryInfo, SSqlNode* pSqlNode, SMsgBuf* pMsgBuf) {
929 930 931 932 933 934 935 936 937
  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;
  }

938 939
  pQueryInfo->order = taosArrayInit(4, sizeof(SOrder));

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

  // handle the first part of order by
957
  bool found = false;
958
  for(int32_t i = 0; i < taosArrayGetSize(pSortOrder); ++i) {
959 960 961
    SListItem* pItem = taosArrayGet(pSortOrder, i);

    SVariant* pVar = &pItem->pVar;
962
    if (pVar->nType == TSDB_DATA_TYPE_BINARY) {
963
      SOrder order = {0};
964 965 966 967 968 969

      // 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) {
970 971 972 973 974 975
          setColumn(&order.col, pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, TSDB_COL_TMP, pSchema);

          order.order = pItem->sortOrder;
          taosArrayPush(pQueryInfo->order, &order);
          found = true;
          break;
976 977
        }
      }
978

979 980 981 982
      if (!found) {
        return buildInvalidOperationMsg(pMsgBuf, "invalid order by column");
      }

983 984 985 986
    } else {  // order by [1|2|3]
      if (pVar->i > getNumOfFields(&pQueryInfo->fieldsInfo)) {
        return buildInvalidOperationMsg(pMsgBuf, msg4);
      }
987

988 989
      int32_t    index = pVar->i - 1;
      SExprInfo* pExprInfo = getExprInfo(pQueryInfo, index);
990

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

  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
1128
        if (pExpr->base.pColumns->colIndex != index.columnIndex && index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_ID) {
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
          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;
1145
          for (int32_t i = 0; i < getNumOfExprs(pQueryInfo); ++i) {
1146
            SExprInfo* pExpr = getExprInfo(pQueryInfo, i);
1147
            if (getExprFunctionId(pExpr) == FUNCTION_PRJ && pExpr->base.pColumns->colId == PRIMARYKEY_TIMESTAMP_COL_ID) {
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
              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);

1228
        if (pExpr->base.pColumns->colIndex != index.columnIndex && index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_ID) {
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 1256 1257 1258 1259 1260
          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 已提交
1261
static int32_t checkFillQueryRange(SQueryStmtInfo* pQueryInfo, SMsgBuf* pMsgBuf) {
1262
  const char* msg1 = "start(end) time of time range required or time range too large";
1263 1264 1265 1266 1267

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

1268 1269 1270 1271 1272
  // TODO disable this check temporarily
//  bool initialWindows = TSWINDOW_IS_EQUAL(pQueryInfo->window, TSWINDOW_INITIALIZER);
//  if (initialWindows) {
//    return buildInvalidOperationMsg(pMsgBuf, msg1);
//  }
1273 1274 1275 1276 1277 1278 1279 1280 1281

  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) {
1282
      return buildInvalidOperationMsg(pMsgBuf, msg1);
1283 1284 1285 1286
    }
  }

  return TSDB_CODE_SUCCESS;
1287 1288 1289
}

int32_t validateFillNode(SQueryStmtInfo *pQueryInfo, SSqlNode* pSqlNode, SMsgBuf* pMsgBuf) {
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
  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 已提交
1308
  if (checkFillQueryRange(pQueryInfo, pMsgBuf) != TSDB_CODE_SUCCESS) {
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 1392 1393 1394 1395 1396
    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;
1397 1398
}

1399 1400
static void pushDownAggFuncExprInfo(SQueryStmtInfo* pQueryInfo);
static void addColumnNodeFromLowerLevel(SQueryStmtInfo* pQueryInfo);
1401

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

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

    // parse the group by clause in the first place
1445
    if (validateGroupbyNode(pQueryInfo, pSqlNode->pGroupby, pMsgBuf) != TSDB_CODE_SUCCESS) {
1446 1447 1448
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

1449
    if (validateSelectNodeList(pQueryInfo, pSqlNode->pSelNodeList, true, pMsgBuf) != TSDB_CODE_SUCCESS) {
1450 1451 1452
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

H
Haojun Liao 已提交
1453
    code = checkForUnsupportedQuery(pQueryInfo, pMsgBuf);
1454

1455
    STableMeta* pTableMeta = getMetaInfo(pQueryInfo, 0)->pTableMeta;
1456
    SSchema*    pSchema = getOneColumnSchema(pTableMeta, 0);
1457
    int32_t precision = pTableMeta->tableInfo.precision;
1458

H
Haojun Liao 已提交
1459
#if 0
1460
    if (pSchema->type != TSDB_DATA_TYPE_TIMESTAMP) {
1461
      int32_t numOfExprs = (int32_t)getNumOfExprs(pQueryInfo);
1462 1463

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

1466 1467 1468
        int32_t f = pExpr->pExpr->_node.functionId;
        if (f == FUNCTION_DERIVATIVE || f == FUNCTION_TWA || f == FUNCTION_IRATE) {
          return buildInvalidOperationMsg(pMsgBuf, msg7);
1469 1470 1471
        }
      }
    }
H
Haojun Liao 已提交
1472
#endif
1473 1474 1475

    // validate the query filter condition info
    if (pSqlNode->pWhere != NULL) {
1476
      if (validateWhereNode(pQueryInfo, pSqlNode->pWhere, pMsgBuf) != TSDB_CODE_SUCCESS) {
1477 1478 1479 1480
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }
    } else {
      if (pQueryInfo->numOfTables > 1) {
1481
        return buildInvalidOperationMsg(pMsgBuf, msg8);
1482 1483 1484 1485
      }
    }

    // validate the interval info
1486
    if (validateIntervalNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1487 1488
      return TSDB_CODE_TSC_INVALID_OPERATION;
    } else {
1489
      if (validateSessionNode(pQueryInfo, &pSqlNode->sessionVal, precision, pMsgBuf) != TSDB_CODE_SUCCESS) {
1490 1491 1492 1493
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }

      // parse the window_state
1494
      if (validateStateWindowNode(pQueryInfo, &pSqlNode->windowstateVal, pMsgBuf) != TSDB_CODE_SUCCESS) {
1495 1496 1497 1498 1499 1500
        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);
1501
    if (validateHavingNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1502 1503 1504
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

1505
    if ((code = validateLimitNode(pQueryInfo, pSqlNode, pMsgBuf)) != TSDB_CODE_SUCCESS) {
1506 1507 1508 1509
      return code;
    }

    // set order by info
1510
    if (validateOrderbyNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1511 1512 1513
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

1514
    if ((code = validateFillNode(pQueryInfo, pSqlNode, pMsgBuf)) != TSDB_CODE_SUCCESS) {
1515 1516 1517 1518
      return code;
    }
  } else {
    pQueryInfo->command = TSDB_SQL_SELECT;
1519
    if (taosArrayGetSize(pSqlNode->from->list) > TSDB_MAX_JOIN_TABLE_NUM) {
1520
      return buildInvalidOperationMsg(pMsgBuf, msg2);
1521 1522
    }

1523
    STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, 0);
1524
    pQueryInfo->info.stableQuery = UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo);
1525

1526
    int32_t precision = pTableMetaInfo->pTableMeta->tableInfo.precision;
1527 1528

    // parse the group by clause in the first place
1529
    if (validateGroupbyNode(pQueryInfo, pSqlNode->pGroupby, pMsgBuf) != TSDB_CODE_SUCCESS) {
1530 1531
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }
1532

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

H
Haojun Liao 已提交
1544
    if (validateSelectNodeList(pQueryInfo, pSqlNode->pSelNodeList, false, pMsgBuf) != TSDB_CODE_SUCCESS) {
1545 1546 1547 1548
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    // parse the window_state
1549
    if (validateStateWindowNode(pQueryInfo, &pSqlNode->windowstateVal, pMsgBuf) != TSDB_CODE_SUCCESS) {
1550 1551 1552 1553
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    // set interval value
1554
    if (validateIntervalNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
1555 1556 1557 1558
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

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

1577 1578 1579 1580 1581
    // set order by info
    if (validateOrderbyNode(pQueryInfo, pSqlNode, pMsgBuf) != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

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

1586
    if ((code = validateFillNode(pQueryInfo, pSqlNode, pMsgBuf)) != TSDB_CODE_SUCCESS) {
1587 1588 1589 1590
      return code;
    }
  }

1591 1592
  pushDownAggFuncExprInfo(pQueryInfo);
//  addColumnNodeFromLowerLevel(pQueryInfo);
1593 1594

  for(int32_t i = 0; i < 1; ++i) {
H
Haojun Liao 已提交
1595 1596 1597 1598 1599 1600 1601 1602
    SArray* functionList = extractFunctionList(pQueryInfo->exprList[i]);
    extractFunctionDesc(functionList, &pQueryInfo->info);

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

1603 1604 1605
  return TSDB_CODE_SUCCESS;  // Does not build query message here
}

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 1641 1642 1643 1644 1645
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;
}

1646 1647 1648 1649 1650 1651 1652 1653 1654
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;
    }
  }
1655

1656 1657 1658 1659 1660 1661
  return true;
}

static SExprInfo* createColumnNodeFromAggFunc(SSchema* pSchema);

static void pushDownAggFuncExprInfo(SQueryStmtInfo* pQueryInfo) {
1662 1663 1664 1665 1666 1667
  assert(pQueryInfo != NULL);

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

1668
    // If direct lower level expressions are all aggregate function, check if current function can be push down or not
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
    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);
1681
          // pExpr depends on the output of the down level, so it can not be push downwards
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
          if (pExpr->base.pColumns->info.colId == pNextLevelExpr->base.resSchema.colId) {
            canPushDown = false;
            break;
          }
        }

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

1692 1693
          // Add the project function of the current level, to output the calculated result
          SExprInfo* pNew = createColumnNodeFromAggFunc(&pExpr->base.resSchema);
1694 1695 1696 1697 1698 1699 1700
          taosArrayInsert(p, j, &pNew);
        }
      }
    }
  }
}

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 1739 1740 1741 1742 1743
// 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);
      }
    }
  }
}

1744 1745 1746
int32_t checkForInvalidExpr(SQueryStmtInfo* pQueryInfo, SMsgBuf* pMsgBuf) {
  assert(pQueryInfo != NULL && pMsgBuf != NULL);

H
Haojun Liao 已提交
1747 1748 1749 1750 1751
  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";
1752 1753
  const char* msg6 = "not support distinct mixed with join";
  const char* msg7 = "not support distinct mixed with groupby";
1754 1755
  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 已提交
1756 1757 1758 1759 1760 1761

  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
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
    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 已提交
1774 1775 1776 1777 1778 1779 1780
    }

    // 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);
    }
1781 1782 1783 1784 1785 1786

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

1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
      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) {
1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815
        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 已提交
1816
  }
1817

H
Haojun Liao 已提交
1818 1819 1820 1821 1822 1823 1824 1825
  /*
   * 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 已提交
1826 1827 1828 1829 1830
      if (pExpr->pExpr->nodeType != TEXPR_FUNCTION_NODE) {
        continue;
      }

      int32_t functionId = getExprFunctionId(pExpr);
1831
      if (functionId == FUNCTION_COUNT && TSDB_COL_IS_TAG(pExpr->base.pColumns->flag)) {
H
Haojun Liao 已提交
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 1867 1868 1869 1870 1871
        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) {
1872 1873
      return buildInvalidOperationMsg(pMsgBuf, msg6);
    }
1874

1875 1876 1877
    if (taosArrayGetSize(pQueryInfo->groupbyExpr.columnInfo) != 0) {
      return buildInvalidOperationMsg(pMsgBuf, msg7);
    }
1878
  }
H
Haojun Liao 已提交
1879 1880 1881 1882 1883 1884

  /*
   * 7. invalid sql:
   * nested subquery not support block_dist query
   * select block_dist() from (select * from table_name)
   */
1885 1886 1887 1888 1889 1890 1891 1892 1893

  /*
   * 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);
  }
1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922

  /*
   * 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");
        }
      }
    }
  }
1923
}
1924

1925
int32_t addResColumnInfo(SQueryStmtInfo* pQueryInfo, int32_t outputIndex, SSchema* pSchema, SExprInfo* pSqlExpr) {
1926 1927 1928 1929
  SInternalField* pInfo = insertFieldInfo(&pQueryInfo->fieldsInfo, outputIndex, pSchema);
  pInfo->pExpr = pSqlExpr;
  return TSDB_CODE_SUCCESS;
}
1930

1931 1932 1933 1934 1935 1936 1937
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);
1938

1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
    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);
  }
}

1957
SExprInfo* doAddOneExprInfo(SQueryStmtInfo* pQueryInfo, const char* funcName, SSourceParam* pSourceParam, int32_t outputIndex,
1958
                           STableMetaInfo* pTableMetaInfo, SSchema* pResultSchema, int32_t interSize, const char* token, bool finalResult) {
1959
  SExprInfo* pExpr = createExprInfo(pTableMetaInfo, funcName, pSourceParam, pResultSchema, interSize);
1960
  tstrncpy(pExpr->base.token, token, sizeof(pExpr->base.token));
1961 1962

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

1965
  uint64_t uid = pTableMetaInfo->pTableMeta->uid;
1966

1967 1968 1969
  if (pSourceParam->pColumnList != NULL) {
    SColumn* pCol = taosArrayGetP(pSourceParam->pColumnList, 0);

1970
    if (TSDB_COL_IS_TAG(pCol->flag) || TSDB_COL_IS_NORMAL_COL(pCol->flag)) {
1971
      SArray* p = TSDB_COL_IS_TAG(pCol->flag) ? pTableMetaInfo->tagColList : pQueryInfo->colList;
1972

1973 1974 1975 1976 1977 1978 1979 1980
      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)) {
1981 1982
      char* colName = pTableMetaInfo->pTableMeta->schema[0].name;
      insertPrimaryTsColumn(pQueryInfo->colList, colName, uid);
1983
    }
1984
  }
1985

1986
  if (finalResult) {
1987
    addResColumnInfo(pQueryInfo, outputIndex, pResultSchema, pExpr);
1988 1989
  }

1990
  return pExpr;
1991 1992
}

1993 1994 1995 1996 1997 1998
static void extractFunctionName(char* name, const tSqlExprItem* pItem) {
  assert(pItem != NULL);
  SToken* funcToken = &pItem->pNode->Expr.operand;
  memcpy(name, funcToken->z, funcToken->n);
}

1999
static int32_t addOneExprInfo(SQueryStmtInfo* pQueryInfo, tSqlExprItem* pItem, int32_t functionId, int32_t outputIndex, SSchema* pSchema, SColumnIndex* pColIndex, tExprNode* pNode, bool finalResult, SMsgBuf* pMsgBuf) {
2000 2001 2002 2003 2004 2005 2006
  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);
    }
  }

2007 2008 2009
  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);
2010

2011 2012
  SResultDataInfo resInfo = {0};
  getResultDataInfo(pSchema->type, pSchema->bytes, functionId, 0, &resInfo, 0, false);
2013

2014
  SSchema resultSchema = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), name);
2015 2016

  STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, pColIndex->tableIndex);
2017
  SColumn c = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, pColIndex->type, pSchema);
2018 2019 2020 2021

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

2022 2023 2024 2025
  char fname[FUNCTIONS_NAME_MAX_LENGTH] = {0};
  extractFunctionName(fname, pItem);
  doAddOneExprInfo(pQueryInfo, fname, &param, outputIndex, pTableMetaInfo, &resultSchema, resInfo.intermediateBytes, name, finalResult);

2026 2027 2028
  return TSDB_CODE_SUCCESS;
}

2029 2030 2031 2032 2033 2034 2035 2036 2037
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;
}

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

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

2065 2066 2067 2068 2069
  SColumn col = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, TSDB_COL_NORMAL, &s);

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

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

2073 2074
  SArray* pExprList = getCurrentExprList(pQueryInfo);
  addExprInfo(pExprList, outputIndex, pExpr, pQueryInfo->exprListLevelIndex);
2075 2076

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

2081 2082 2083
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";
2084

2085 2086 2087 2088 2089 2090
  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 {
2091 2092 2093 2094 2095 2096
    tSqlExprItem* pParamElem = taosArrayGet(pParamList, 0);

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

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

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

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

2131 2132
    SSchema* pSchema = getOneColumnSchema(pTableMeta, i);
    if (addOneExprInfo(pQueryInfo, pItem, functionId, *colIndex, pSchema, &index, NULL, finalResult, pMsgBuf) != 0) {
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 2158 2159 2160 2161 2162
      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};

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

2165
    if (code != TSDB_CODE_SUCCESS) {
2166 2167 2168 2169
      return buildInvalidOperationMsg(pMsgBuf, msg3);
    }

    // functions can not be applied to tags
2170
    if (TSDB_COL_IS_TAG(index.type) && (functionId == FUNCTION_INTERP || functionId == FUNCTION_SPREAD)) {
2171 2172 2173
      return buildInvalidOperationMsg(pMsgBuf, msg6);
    }

2174
    if (addOneExprInfo(pQueryInfo, pItem, functionId, (*outputIndex)++, &columnSchema, &index, pNode, finalResult, pMsgBuf) != 0) {
2175 2176 2177 2178 2179
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }
  }
}

2180
static int32_t multiColumnListInsert(SQueryStmtInfo* pQueryInfo, SArray* pColumnList, SMsgBuf* pMsgBuf);
2181
static int32_t addScalarExprAndResColumn(SQueryStmtInfo* pQueryInfo, int32_t exprIndex, tSqlExprItem* pItem, SMsgBuf* pMsgBuf);
2182

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

2194 2195
  pQueryInfo->exprListLevelIndex += 1;

2196
  if (tokenId == TK_ALL || tokenId == TK_ID) {  // simple parameter
2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
    // 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);
      }
2207

2208 2209 2210 2211
      if (!scalarFunc) {
        return buildInvalidOperationMsg(pMsgBuf, msg6);
      }

2212 2213 2214 2215 2216
      SArray* pExprList = getCurrentExprList(pQueryInfo);
      size_t n = taosArrayGetSize(pExprList);

      // todo extract the table uid
      pIndex->tableIndex = 0;
2217
      int32_t code = addScalarExprAndResColumn(pQueryInfo, n, pParamElem, pMsgBuf);
2218 2219 2220 2221
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

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

2231 2232 2233 2234
      // functions can not be applied to tags
      if (TSDB_COL_IS_TAG(pIndex->type)) {
        return buildInvalidOperationMsg(pMsgBuf, msg5);
      }
2235

2236 2237 2238 2239
      // 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);
    }
2240 2241
  } 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
2242
    pIndex->type = TSDB_COL_TMP;  // It is a temporary column generated by arithmetic expression.
2243

2244 2245
    SArray* pExprList = getCurrentExprList(pQueryInfo);
    size_t n = taosArrayGetSize(pExprList);
2246
    int32_t code = addScalarExprAndResColumn(pQueryInfo, n, pParamElem, pMsgBuf);
2247 2248
    if (code != TSDB_CODE_SUCCESS) {
      return code;
2249 2250
    }

2251 2252 2253 2254
    SExprInfo** pLastExpr = taosArrayGetLast(getCurrentExprList(pQueryInfo));
    *pNode = (*pLastExpr)->pExpr;
    *(SSchema*)  columnSchema = (*pLastExpr)->base.resSchema;
    *pTableMetaInfo = getMetaInfo(pQueryInfo, 0);
2255 2256 2257
  } else {
    assert(0);
  }
2258 2259

  pQueryInfo->exprListLevelIndex -= 1;
2260 2261 2262 2263 2264 2265
  return TSDB_CODE_SUCCESS;
}

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

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

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

2284
int32_t addAggExprAndResColumn(SQueryStmtInfo* pQueryInfo, int32_t colIndex, tSqlExprItem* pItem, bool finalResult, SMsgBuf* pMsgBuf) {
2285 2286
  STableMetaInfo* pTableMetaInfo = NULL;
  int32_t functionId = pItem->functionId;
2287
  int32_t code = TSDB_CODE_SUCCESS;
2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300

  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]";
2301 2302 2303 2304 2305
  const char* msg13 = "nested function is not supported";

  if (checkForAliasName(pMsgBuf, pItem->aliasName) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }
2306 2307 2308 2309 2310

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

2315
      tExprNode* pNode = NULL;
2316
      SColumnIndex index = COLUMN_INDEX_INITIALIZER;
2317 2318 2319
      SSchema columnSchema = {0};

      code = setColumnIndex(pQueryInfo, pParamList, &index, &columnSchema, &pNode, pMsgBuf);
2320 2321
      if (code != TSDB_CODE_SUCCESS) {
        return code;
2322 2323 2324
      }

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

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

2330
      pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);
2331 2332 2333 2334 2335
      SColumn c = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, index.type, &columnSchema);

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

2336
      int32_t outputIndex = getNumOfFields(&pQueryInfo->fieldsInfo);
2337 2338 2339 2340

      char fname[FUNCTIONS_NAME_MAX_LENGTH] = {0};
      extractFunctionName(fname, pItem);
      doAddOneExprInfo(pQueryInfo, fname, &param, outputIndex, pTableMetaInfo, &s, size, token, finalResult);
2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366
      return TSDB_CODE_SUCCESS;
    }

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

2367 2368 2369
      tExprNode* pNode     = NULL;
      int32_t tokenId      = pParamElem->pNode->tokenId;
      SColumnIndex index   = COLUMN_INDEX_INITIALIZER;
2370
      SSchema columnSchema = {0};
2371 2372
      code = extractFunctionParameterInfo(pQueryInfo, tokenId, &pTableMetaInfo, &columnSchema, &pNode, &index, pParamElem, pMsgBuf);

2373 2374 2375 2376 2377
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
      
      if (tokenId == TK_ALL || tokenId == TK_ID) {
2378 2379 2380 2381 2382
        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);
        }
2383 2384
      }

2385 2386
      int32_t precision = pTableMetaInfo->pTableMeta->tableInfo.precision;

2387 2388
      SResultDataInfo resInfo = {0};
      if (getResultDataInfo(columnSchema.type, columnSchema.bytes, functionId, 0, &resInfo, 0, false) != TSDB_CODE_SUCCESS) {
2389 2390
        return TSDB_CODE_TSC_INVALID_OPERATION;
      }
2391 2392 2393 2394

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

2399 2400 2401 2402
      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);
2403

2404 2405 2406 2407 2408
      SColumn c = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, index.type, &columnSchema);

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

2409 2410
      char funcName[FUNCTIONS_NAME_MAX_LENGTH] = {0};
      extractFunctionName(funcName, pItem);
2411

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

        int64_t tickPerSec = 0;
2433
        code = getTickPerSecond(&pParamElem[1].pNode->value, precision, &tickPerSec, pMsgBuf);
2434 2435
        if (code != TSDB_CODE_SUCCESS) {
          return code;
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 2462 2463 2464 2465 2466
        }

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

2467
        if (taosArrayGetSize(pParamList) > 1 && (pItem->aliasName != NULL)) {
2468 2469 2470
          return buildInvalidOperationMsg(pMsgBuf, msg8);
        }

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

      tSqlExprItem* pParamElem = taosArrayGet(pItem->pNode->Expr.paramList, 0);
2504
      if (pParamElem->pNode->tokenId == TK_ALL) {
2505 2506 2507
        return buildInvalidOperationMsg(pMsgBuf, msg2);
      }

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

      // 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
2525
      if (!IS_NUMERIC_TYPE(columnSchema.type)) {
2526 2527 2528 2529 2530 2531 2532 2533
        return buildInvalidOperationMsg(pMsgBuf, msg1);
      }

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

2534
      SResultDataInfo resInfo = {0};
2535 2536 2537 2538 2539 2540
      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
      }
2541

2542
      SSchema s = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), "");
2543

2544 2545
      char token[TSDB_COL_NAME_LEN] = {0};
      setTokenAndResColumnName(pItem, s.name, token, sizeof(s.name) - 1);
2546 2547 2548 2549 2550 2551

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

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

2552 2553 2554
      char funcName[FUNCTIONS_NAME_MAX_LENGTH] = {0};
      extractFunctionName(funcName, pItem);
      SExprInfo* pExpr = doAddOneExprInfo(pQueryInfo, funcName, &param, colIndex, pTableMetaInfo, &s, resInfo.intermediateBytes, token, finalResult);
2555

2556 2557 2558 2559 2560 2561
      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);
2562 2563 2564 2565 2566 2567

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

      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
2588 2589
      if ((code = checkForkParam(pItem->pNode, 1, pMsgBuf)) != TSDB_CODE_SUCCESS) {
        return code;
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 2620 2621 2622 2623 2624
      }

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

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

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

2630 2631
      SResultDataInfo resInfo = {0};
      int32_t ret = getResultDataInfo(s.type, s.bytes, FUNCTION_TID_TAG, 0, &resInfo, 0, 0);
2632 2633
      assert(ret == TSDB_CODE_SUCCESS);

2634 2635 2636 2637 2638 2639
      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);

2640
      /*SExprInfo* pExpr = */doAddOneExprInfo(pQueryInfo, "tbid", &param, 0, pTableMetaInfo, &result, 0, s.name, true);
2641 2642 2643 2644 2645
      return TSDB_CODE_SUCCESS;
    }

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

2650
      SColumnIndex index = {.tableIndex = 0, .columnIndex = 0, .type = TSDB_COL_NORMAL};
2651 2652
      pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);

2653 2654
      SResultDataInfo resInfo = {0};
      getResultDataInfo(TSDB_DATA_TYPE_INT, 4, functionId, 0, &resInfo, 0, 0);
2655

2656 2657
      SSchema s = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), "block_dist");
      SSchema colSchema = {0};
2658

2659 2660
      char token[TSDB_COL_NAME_LEN] = {0};
      setTokenAndResColumnName(pItem, s.name, token, sizeof(s.name) - 1);
2661 2662 2663 2664 2665 2666

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

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

H
Haojun Liao 已提交
2667
      SExprInfo* pExpr = doAddOneExprInfo(pQueryInfo, "block_dist", &param, colIndex, pTableMetaInfo, &s, resInfo.intermediateBytes, token, finalResult);
2668 2669 2670

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

2674 2675 2676 2677 2678 2679 2680 2681 2682
    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);
2683

2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728
      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);

2729 2730 2731 2732
      char funcName[FUNCTIONS_NAME_MAX_LENGTH] = {0};
      extractFunctionName(funcName, pItem);

      doAddOneExprInfo(pQueryInfo, funcName, &param, colIndex, pTableMetaInfo, &s, resInfo.intermediateBytes, token, finalResult);
2733 2734
      return TSDB_CODE_SUCCESS;
    }
2735

2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
    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);
      }

2763 2764
      SResultDataInfo resInfo = {0};
      getResultDataInfo(TSDB_DATA_TYPE_INT, 4, functionId, 0, &resInfo, 0, false/*, pUdfInfo*/);
2765

2766 2767
      SSchema s = createSchema(resInfo.type, resInfo.bytes, getNewResColId(), "");
      SSchema* colSchema = getOneColumnSchema(pTableMetaInfo->pTableMeta, index.tableIndex);
2768

2769 2770
      char token[TSDB_COL_NAME_LEN] = {0};
      setTokenAndResColumnName(pItem, s.name, token, sizeof(s.name) - 1);
2771 2772 2773 2774 2775 2776

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

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

2777 2778 2779
      char funcName[FUNCTIONS_NAME_MAX_LENGTH] = {0};
      extractFunctionName(funcName, pItem);
      doAddOneExprInfo(pQueryInfo, funcName, &param, colIndex, pTableMetaInfo, &s, resInfo.intermediateBytes, token, finalResult);
2780 2781 2782 2783 2784 2785 2786
      return TSDB_CODE_SUCCESS;
    }
  }

  return TSDB_CODE_TSC_INVALID_OPERATION;
}

2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801
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;
  }

2802
  SColumn c = createColumn(pTableMeta->uid, pTableMetaInfo->aliasName, index.type, pSchema);
2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820
  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);

2821 2822
  if (scalar) {
    printf("scalar function found!\n");
2823
//    if (addScalarExprAndResColumn(pQueryInfo, outputIndex, &item, pMsgBuf) != TSDB_CODE_SUCCESS) {
2824 2825 2826 2827 2828 2829
//      return TSDB_CODE_TSC_INVALID_OPERATION;
//    }
  } else {
    if (addAggExprAndResColumn(pQueryInfo, outputIndex, &item, false, pMsgBuf) != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }
2830

2831 2832 2833
    // 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) {
2834 2835
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }
2836 2837 2838 2839 2840 2841 2842 2843 2844

    // 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;
      }
    }
2845 2846 2847 2848 2849
  }

  return TSDB_CODE_SUCCESS;
}

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

  return code;
}

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

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

2875 2876 2877 2878
  tSqlExpr sqlNode = {0};
  sqlNode.type = SQL_NODE_TABLE_COLUMN;
  sqlNode.columnName = colNameToken;

2879 2880 2881
  tExprNode* pNode = NULL;
  bool       keepTableCols = true;
  int32_t    ret = sqlExprToExprNode(&pNode, &sqlNode, pQueryInfo, pColumnList, &keepTableCols, pMsgBuf);
2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
  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);
2893

2894 2895 2896 2897 2898 2899 2900 2901 2902
  // 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;
2903 2904 2905 2906 2907 2908

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

2909
  pQueryInfo->info.projectionQuery = true;
2910
  return TSDB_CODE_SUCCESS;
2911 2912
}

H
Haojun Liao 已提交
2913
static int32_t doAddMultipleProjectExprAndResColumns(SQueryStmtInfo* pQueryInfo, SColumnIndex* pIndex, int32_t startPos, SMsgBuf* pMsgBuf) {
2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924
  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) {
2925
    SSchema* pSchema = getOneColumnSchema(pTableMetaInfo->pTableMeta, j);
H
Haojun Liao 已提交
2926
    doAddOneProjectCol(pQueryInfo, startPos + j, pSchema, NULL, getNewResColId(), pMsgBuf);
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 2959 2960 2961 2962 2963
  }

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

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

  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) {
2984
      return buildInvalidOperationMsg(pMsgBuf, msg1);
2985 2986 2987 2988 2989 2990 2991
    }

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

H
Haojun Liao 已提交
2992
  return doAddOneProjectCol(pQueryInfo, startPos, &colSchema, pItem->aliasName, getNewResColId(), pMsgBuf);
2993 2994
}

2995 2996 2997 2998
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";

2999 3000 3001 3002
  if (checkForAliasName(pMsgBuf, pItem->aliasName) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

3003
  int32_t startPos = (int32_t)getNumOfExprs(pQueryInfo);
3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016
  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 已提交
3017
        int32_t inc = doAddMultipleProjectExprAndResColumns(pQueryInfo, &index, startPos, pMsgBuf);
3018
        startPos += inc;
3019 3020
      }
    } else {
H
Haojun Liao 已提交
3021
      doAddMultipleProjectExprAndResColumns(pQueryInfo, &index, startPos, pMsgBuf);
3022 3023
    }

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

3033 3034
    char token[TSDB_COL_NAME_LEN] = {0};
    tstrncpy(token, pItem->pNode->exprToken.z, MIN(TSDB_COL_NAME_LEN, TSDB_COL_NAME_LEN));
3035

3036 3037 3038 3039 3040 3041
    STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, index.tableIndex);
    SColumn c = createColumn(pTableMetaInfo->pTableMeta->uid, pTableMetaInfo->aliasName, index.type, &colSchema);

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

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

3060
      SSchema* pSchema = getOneColumnSchema(pTableMetaInfo->pTableMeta, index.columnIndex);
H
Haojun Liao 已提交
3061
      doAddOneProjectCol(pQueryInfo, startPos, pSchema, pItem->aliasName, getNewResColId(), pMsgBuf);
3062
    }
3063 3064 3065 3066

    // 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)) {
3067 3068
      STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;
      insertPrimaryTsColumn(pQueryInfo->colList, pTableMeta->schema[0].name, pTableMeta->uid);
3069 3070 3071
    }
  } else {
    return TSDB_CODE_TSC_INVALID_OPERATION;
3072 3073
  }

3074 3075 3076
  return TSDB_CODE_SUCCESS;
}

3077
static int32_t validateExprLeafNode(tSqlExpr* pExpr, SQueryStmtInfo* pQueryInfo, SArray* pList, int32_t* type, SMsgBuf* pMsgBuf) {
3078 3079 3080 3081 3082
  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;
3083
    }
3084

3085 3086 3087
    int32_t code = validateExprLeafColumnNode(pQueryInfo, &pExpr->columnName, pList, pMsgBuf);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
3088
    }
3089 3090 3091 3092 3093 3094 3095 3096 3097 3098
  } 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;
    }

3099 3100 3101
    int32_t code = validateExprLeafFunctionNode(pQueryInfo, pExpr, pMsgBuf);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
3102 3103 3104
    }
  }

3105 3106
  return TSDB_CODE_SUCCESS;
}
3107

3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135
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;
}

3136 3137 3138 3139 3140 3141
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));

3142 3143
  pExpr->nodeType = TEXPR_COL_NODE;
  pExpr->pSchema  = calloc(1, sizeof(SSchema));
3144 3145 3146 3147 3148 3149 3150 3151

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

3152 3153
  *(SSchema*)(pExpr->pSchema) = *pSchema;

3154
  if (keepTableCols && TSDB_COL_IS_NORMAL_COL(pIndex->type)) {
3155 3156 3157 3158
    SColumn c = createColumn(pTableMeta->uid, pTableMetaInfo->aliasName, pIndex->type, pExpr->pSchema);
    taosArrayPush(pCols, &c);
  }

3159 3160 3161 3162 3163 3164 3165 3166
  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);
  }

3167 3168 3169
  return pExpr;
}

3170
static SExprInfo* createColumnNodeFromAggFunc(SSchema* pSchema) {
3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186
  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;
}

3187 3188
static int32_t validateSqlExpr(const tSqlExpr* pSqlExpr, SQueryStmtInfo *pQueryInfo, SMsgBuf* pMsgBuf);

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

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

3204
      int32_t code = sqlExprToExprNode(&(*p)[i], pItem->pNode, pQueryInfo, pCols, keepTableCols, pMsgBuf);
3205 3206 3207 3208 3209 3210 3211 3212 3213 3214
      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;
3215
    (*p) = calloc(*num, POINTER_BYTES);
3216 3217

    SColumnIndex index = {.type = TSDB_COL_NORMAL, .tableIndex = 0, .columnIndex = 0};
3218
    (*p)[0] = doCreateColumnNode(pQueryInfo, &index, *keepTableCols, pCols);
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 3249 3250 3251 3252 3253
  }

  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};
3254
      strncpy(token, pLeft->Expr.operand.z, pLeft->Expr.operand.n);
3255 3256
      bool agg1 = qIsAggregateFunction(token);

3257
      strncpy(token, pRight->Expr.operand.z, pRight->Expr.operand.n);
3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277
      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 已提交
3278 3279
    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) {
3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296
      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 已提交
3297 3298 3299 3300 3301 3302 3303 3304 3305
  } 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) {
3306
      int32_t ret = validateScalarFunctionParamNum((tSqlExpr*) pSqlExpr, functionId, pMsgBuf);
H
Haojun Liao 已提交
3307 3308 3309 3310
      if (ret != TSDB_CODE_SUCCESS) {
        return buildInvalidOperationMsg(pMsgBuf, "invalid number of function parameters");
      }
    }
3311 3312 3313 3314 3315 3316
  }

  return TSDB_CODE_SUCCESS;
}

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

3320 3321 3322
  SColumnIndex index = COLUMN_INDEX_INITIALIZER;
  if (pSqlExpr->type == SQL_NODE_EXPR) {
    if (pSqlExpr->pLeft != NULL) {
3323
      int32_t ret = sqlExprToExprNode(&pLeft, pSqlExpr->pLeft, pQueryInfo, pCols, keepTableCols, pMsgBuf);
3324 3325 3326
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }
3327 3328
    }

3329
    if (pSqlExpr->pRight != NULL) {
3330
      int32_t ret = sqlExprToExprNode(&pRight, pSqlExpr->pRight, pQueryInfo, pCols, keepTableCols, pMsgBuf);
3331 3332 3333 3334
      if (ret != TSDB_CODE_SUCCESS) {
        tExprTreeDestroy(pLeft, NULL);
        return ret;
      }
3335 3336
    }

3337 3338 3339
    if (pSqlExpr->pLeft == NULL && pSqlExpr->pRight == NULL && pSqlExpr->tokenId == 0) {
      *pExpr = calloc(1, sizeof(tExprNode));
      return TSDB_CODE_SUCCESS;
3340
    }
3341
 } else if (pSqlExpr->type == SQL_NODE_SQLFUNCTION) {
3342 3343 3344 3345 3346
    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;
    }
3347

3348
    if (!scalar) {
3349
      pQueryInfo->exprListLevelIndex += 1;
3350
    }
3351

3352
    *keepTableCols = false;
3353

3354 3355
    int32_t num = 0;
    tExprNode** p = NULL;
3356
    int32_t code = doProcessFunctionLeafNodeParam(pQueryInfo, &num, &p, pCols, keepTableCols, pSqlExpr, pMsgBuf);
3357 3358 3359
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
3360

3361
    int32_t outputIndex = (int32_t)getNumOfExprs(pQueryInfo);
3362

3363 3364
    if (scalar) {
      printf("scalar function found! %s\n", pSqlExpr->exprToken.z);
3365

3366 3367 3368
      // Expression on the results of aggregation functions
      *pExpr = calloc(1, sizeof(tExprNode));
      (*pExpr)->nodeType = TEXPR_FUNCTION_NODE;
3369

3370 3371 3372 3373 3374 3375 3376 3377 3378
      (*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;
3379
      }
3380 3381 3382

      pQueryInfo->exprListLevelIndex -= 1;
      // convert the aggregate function to be the input data columns for the outer function.
3383
    }
3384
  }
3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409

  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) {
3410
      // Expression on the results of aggregation functions
3411 3412 3413 3414 3415
      *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);

3416 3417 3418
      // it must be the aggregate function
      assert(qIsAggregateFunction((*pExpr)->pSchema->name));

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

3430
      *pExpr = doCreateColumnNode(pQueryInfo, &index, *keepTableCols, pCols);
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 3462 3463 3464 3465 3466
      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 已提交
3467
    *pExpr = (tExprNode*)calloc(1, sizeof(tExprNode));
3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480
    (*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;
}

3481
static int32_t addScalarExprAndResColumn(SQueryStmtInfo* pQueryInfo, int32_t exprIndex, tSqlExprItem* pItem, SMsgBuf* pMsgBuf) {
3482
  SArray* pColumnList = taosArrayInit(4, sizeof(SColumn));
3483
  SSchema s = createSchema(TSDB_DATA_TYPE_DOUBLE, sizeof(double), getNewResColId(), "");
3484

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

3490
  tExprNode* pNode = NULL;
3491
  bool       keepTableCols = true;
3492
  ret = sqlExprToExprNode(&pNode, pItem->pNode, pQueryInfo, pColumnList, &keepTableCols, pMsgBuf);
3493 3494 3495 3496
  if (ret != TSDB_CODE_SUCCESS) {
    tExprTreeDestroy(pNode, NULL);
    return buildInvalidOperationMsg(pMsgBuf, "invalid expression in select clause");
  }
3497

3498 3499 3500
  SExprInfo* pExpr = createBinaryExprInfo(pNode, &s);
  setTokenAndResColumnName(pItem, pExpr->base.resSchema.name, pExpr->base.token, TSDB_COL_NAME_LEN);

3501 3502
  SArray*    pExprList = getCurrentExprList(pQueryInfo);
  addExprInfo(pExprList, exprIndex, pExpr, pQueryInfo->exprListLevelIndex);
3503

3504 3505 3506 3507 3508 3509 3510
  // 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;
  }
3511

3512
  pExpr->base.numOfCols = num;
3513

3514 3515 3516 3517 3518 3519 3520 3521 3522
  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
3523

3524 3525 3526 3527
  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;
3528

3529
  tbufCloseWriter(&bw);
3530

H
Haojun Liao 已提交
3531 3532 3533 3534 3535
  if (pQueryInfo->exprListLevelIndex == 0) {
    int32_t exists = getNumOfFields(&pQueryInfo->fieldsInfo);
    addResColumnInfo(pQueryInfo, exists, &pExpr->base.resSchema, pExpr);
  }

3536
  //    tbufCloseWriter(&bw); // TODO there is a memory leak
3537

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

3556 3557
  int32_t code = TSDB_CODE_SUCCESS;
  size_t  numOfExpr = taosArrayGetSize(pSelNodeList);
3558 3559

  for (int32_t i = 0; i < numOfExpr; ++i) {
3560
    int32_t outputIndex = (int32_t) getNumOfExprs(pQueryInfo);
3561 3562 3563 3564
    tSqlExprItem* pItem = taosArrayGet(pSelNodeList, i);
    int32_t type = pItem->pNode->type;

    if (pItem->distinct) {
3565
      if (i != 0 || type == SQL_NODE_SQLFUNCTION || type == SQL_NODE_EXPR) {
3566 3567 3568
        return buildInvalidOperationMsg(pMsgBuf, msg4);
      }

H
Haojun Liao 已提交
3569
      pQueryInfo->info.distinct = true;
3570 3571 3572
    }

    if (type == SQL_NODE_SQLFUNCTION) {
3573
      bool scalarFunc = false;
3574
      pItem->functionId = qIsBuiltinFunction(pItem->pNode->Expr.operand.z, pItem->pNode->Expr.operand.n, &scalarFunc);
H
Haojun Liao 已提交
3575 3576 3577 3578
      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) {
3579
          return buildInvalidOperationMsg(pMsgBuf, msg5);
H
Haojun Liao 已提交
3580
//        }
3581

H
Haojun Liao 已提交
3582
//        pItem->functionId = functionId;
3583 3584
      }

3585
      if (scalarFunc) { // scalar function
3586
        if ((code = addScalarExprAndResColumn(pQueryInfo, outputIndex, pItem, pMsgBuf)) != TSDB_CODE_SUCCESS) {
3587 3588 3589 3590 3591 3592 3593
          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;
        }
3594 3595 3596
      }
    } 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
3597
      // select table_name1.field_name1, table_name2.field_name2 from table_name1, table_name2
3598 3599
      if ((code = addProjectionExprAndResColumn(pQueryInfo, pItem, outerQuery, pMsgBuf)) != TSDB_CODE_SUCCESS) {
        return code;
3600 3601
      }
    } else if (type == SQL_NODE_EXPR) {
3602
      if ((code = addScalarExprAndResColumn(pQueryInfo, i, pItem, pMsgBuf)) != TSDB_CODE_SUCCESS) {
3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614
        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);
3615

3616
  // Evaluate expression in where clause
3617 3618 3619 3620 3621 3622
  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;
    }
3623 3624
  }

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

3635
  return TSDB_CODE_SUCCESS;
3636
}
H
Haojun Liao 已提交
3637

3638
int32_t qParserValidateSqlNode(struct SCatalog* pCatalog, SSqlInfo* pInfo, SQueryStmtInfo* pQueryInfo, int64_t id, char* msgBuf, int32_t msgBufLen) {
H
Haojun Liao 已提交
3639
  //1. if it is a query, get the meta info and continue.
3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652
  assert(pCatalog != NULL && pInfo != NULL);
  int32_t code = 0;
#if 0
  switch (pInfo->type) {
    case TSDB_SQL_DROP_TABLE:
    case TSDB_SQL_DROP_USER:
    case TSDB_SQL_DROP_ACCT:
    case TSDB_SQL_DROP_DNODE:
    case TSDB_SQL_DROP_DB: {
      const char* msg1 = "param name too long";
      const char* msg2 = "invalid name";

      SToken* pzName = taosArrayGet(pInfo->pMiscInfo->a, 0);
3653
      if ((pInfo->type != TSDB_SQL_DROP_DNODE) && (parserValidateIdToken(pzName) != TSDB_CODE_SUCCESS)) {
3654
        return setInvalidOperatorMsg(pMsgBuf, msg2);
3655 3656 3657 3658 3659 3660
      }

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

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

        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) {
3692
        return setInvalidOperatorMsg(pMsgBuf, msg);
3693 3694 3695 3696
      }

      int32_t ret = tNameSetDbName(&pTableMetaInfo->name, getAccountId(pSql), pToken);
      if (ret != TSDB_CODE_SUCCESS) {
3697
        return setInvalidOperatorMsg(pMsgBuf, msg);
3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731
      }

      break;
    }

    case TSDB_SQL_RESET_CACHE: {
      return TSDB_CODE_SUCCESS;
    }

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

      break;
    }

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

      break;
    }

    case TSDB_SQL_ALTER_DB:
    case TSDB_SQL_CREATE_DB: {
      const char* msg1 = "invalid db name";
      const char* msg2 = "name too long";

      SCreateDbInfo* pCreateDB = &(pInfo->pMiscInfo->dbOpt);
      if (pCreateDB->dbname.n >= TSDB_DB_NAME_LEN) {
3732
        return setInvalidOperatorMsg(pMsgBuf, msg2);
3733 3734 3735 3736 3737 3738
      }

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

      if (tscValidateName(&token) != TSDB_CODE_SUCCESS) {
3739
        return setInvalidOperatorMsg(pMsgBuf, msg1);
3740 3741 3742 3743
      }

      int32_t ret = tNameSetDbName(&pTableMetaInfo->name, getAccountId(pSql), &token);
      if (ret != TSDB_CODE_SUCCESS) {
3744
        return setInvalidOperatorMsg(pMsgBuf, msg2);
3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757
      }

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

      break;
    }

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

      if (taosArrayGetSize(pInfo->pMiscInfo->a) > 1) {
3758
        return setInvalidOperatorMsg(pMsgBuf, msg);
3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781
      }

      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) {
3782
        return setInvalidOperatorMsg(pMsgBuf, msg3);
3783 3784 3785
      }

      if (tscValidateName(pName) != TSDB_CODE_SUCCESS) {
3786
        return setInvalidOperatorMsg(pMsgBuf, msg2);
3787 3788 3789 3790 3791 3792 3793 3794 3795
      }

      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 {
3796
          return setInvalidOperatorMsg(pMsgBuf, msg1);
3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807
        }
      }

      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) {
3808
        return setInvalidOperatorMsg(pMsgBuf, msg1);
3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823
      }
      // 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) {
3824
        return setInvalidOperatorMsg(pMsgBuf, msg1);
3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838
      }

      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) {
3839
        return setInvalidOperatorMsg(pMsgBuf, msg1);
3840 3841 3842
      }

      if (pToken->n > TSDB_DB_NAME_LEN) {
3843
        return setInvalidOperatorMsg(pMsgBuf, msg1);
3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855
      }
      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) {
3856
        return setInvalidOperatorMsg(pMsgBuf, msg2);
3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869
      }

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

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

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

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

      break;
    }

    case TSDB_SQL_CREATE_USER:
    case TSDB_SQL_ALTER_USER: {
      const char* msg2 = "invalid user/account name";
      const char* msg3 = "name too long";
      const char* msg5 = "invalid user rights";
      const char* msg7 = "not support options";

      pCmd->command = pInfo->type;

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

      if (pName->n >= TSDB_USER_LEN) {
3899
        return setInvalidOperatorMsg(pMsgBuf, msg3);
3900 3901 3902
      }

      if (tscValidateName(pName) != TSDB_CODE_SUCCESS) {
3903
        return setInvalidOperatorMsg(pMsgBuf, msg2);
3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926
      }

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

          SToken* pPrivilege = &pUser->privilege;

          if (strncasecmp(pPrivilege->z, "super", 5) == 0 && pPrivilege->n == 5) {
            pCmd->count = 1;
          } else if (strncasecmp(pPrivilege->z, "read", 4) == 0 && pPrivilege->n == 4) {
            pCmd->count = 2;
          } else if (strncasecmp(pPrivilege->z, "write", 5) == 0 && pPrivilege->n == 5) {
            pCmd->count = 3;
          } else {
3927
            return setInvalidOperatorMsg(pMsgBuf, msg5);
3928 3929
          }
        } else {
3930
          return setInvalidOperatorMsg(pMsgBuf, msg7);
3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942
        }
      }

      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) {
3943
        return setInvalidOperatorMsg(pMsgBuf, msg);
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 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996
      }

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

3997
        if (size > 1 && pSqlNode->from && pSqlNode->from->type == SQL_FROM_NODE_SUBQUERY) {
3998
          return setInvalidOperatorMsg(pMsgBuf, msg1);
3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031
        }

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

4032
      STableMetaInfo* pTableMetaInfo1 = getMetaInfo(pCmd->active, 0);
4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059
      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 已提交
4060

4061 4062 4063
      assert(taosArrayGetSize(pInfo->pMiscInfo->a) == 1);
      code = tNameSetDbName(&pTableMetaInfo->name, getAccountId(pSql), pzName);
      if (code != TSDB_CODE_SUCCESS) {
4064
        return setInvalidOperatorMsg(pMsgBuf, msg1);
4065 4066 4067 4068 4069 4070
      }
      break;
    }
    case TSDB_SQL_COMPACT_VNODE:{
      const char* msg = "invalid compact";
      if (setCompactVnodeInfo(pSql, pInfo) != TSDB_CODE_SUCCESS) {
4071
        return setInvalidOperatorMsg(pMsgBuf, msg);
4072 4073 4074 4075
      }
      break;
    }
    default:
4076
      return setInvalidOperatorMsg(pMsgBuf, "not support sql expression");
4077 4078
  }
#endif
H
Haojun Liao 已提交
4079

4080
  SMetaReq req = {0};
4081
  SMetaData data = {0};
H
Haojun Liao 已提交
4082

4083 4084 4085
  // TODO: check if the qnode info has been cached already
  req.qNodeEpset = true;
  code = qParserExtractRequestedMetaInfo(pInfo, &req, msgBuf, msgBufLen);
4086 4087 4088
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
4089 4090

  // load the meta data from catalog
4091 4092 4093 4094
  code = catalogGetMetaData(pCatalog, &req, &data);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }
4095 4096

  // evaluate the sqlnode
4097 4098 4099
  STableMeta* pTableMeta = (STableMeta*) taosArrayGetP(data.pTableMeta, 0);
  assert(pTableMeta != NULL);

4100 4101
  SMsgBuf buf = {.buf = msgBuf, .len = msgBufLen};

4102
  size_t len = taosArrayGetSize(pInfo->sub.node);
4103
  for(int32_t i = 0; i < len; ++i) {
4104
    SSqlNode* p = taosArrayGetP(pInfo->sub.node, i);
4105
    code = evaluateSqlNode(p, pTableMeta->tableInfo.precision, &buf);
4106 4107 4108 4109
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }
4110

4111
  for(int32_t i = 0; i < len; ++i) {
4112
    SSqlNode* p = taosArrayGetP(pInfo->sub.node, i);
4113 4114 4115
    validateSqlNode(p, pQueryInfo, &buf);
  }

4116

4117
  return code;
H
Haojun Liao 已提交
4118
}