tscSQLParser.c 125.8 KB
Newer Older
H
hzcheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * 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/>.
 */

#define _XOPEN_SOURCE
S
slguan 已提交
17
#define _DEFAULT_SOURCE
H
hzcheng 已提交
18 19 20

#include <stdio.h>
#include <stdlib.h>
S
slguan 已提交
21
#ifdef LINUX
H
hzcheng 已提交
22 23 24 25 26 27
#include <strings.h>
#endif
#include <float.h>
#include <math.h>
#include <string.h>

S
slguan 已提交
28
#include "os.h"
H
hzcheng 已提交
29 30 31 32 33 34 35 36
#include "taos.h"
#include "tstoken.h"
#include "ttime.h"

#include "tscUtil.h"
#include "tschemautil.h"
#include "tsclient.h"
#include "tsql.h"
S
slguan 已提交
37
#pragma GCC diagnostic ignored "-Wunused-variable"
H
hzcheng 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

typedef struct SColumnIdList {
  SSchema* pSchema;
  int32_t  numOfCols;
  int32_t  numOfRecordedCols;
  int32_t  ids[TSDB_MAX_COLUMNS];
} SColumnIdList;

typedef struct SColumnList {
  int32_t numOfCols;
  int32_t ids[TSDB_MAX_COLUMNS];
} SColumnList;

static void setProjExprForMetricQuery(SSqlCmd* pCmd, int32_t fieldIDInResult, int32_t colIdx);

static int32_t setShowInfo(SSqlObj* pSql, SSqlInfo* pInfo);

static bool has(tFieldList* pFieldList, int32_t offset, char* name);

static char* getAccountId(SSqlObj* pSql);

static void getCurrentDBName(SSqlObj* pSql, SSQLToken* pDBToken);
static bool hasSpecifyDB(SSQLToken* pTableName);
static bool validateTableColumnInfo(tFieldList* pFieldList, SSqlCmd* pCmd);

static bool validateTagParams(tFieldList* pTagsList, tFieldList* pFieldList, SSqlCmd* pCmd);

static int32_t setObjFullName(char* fullName, char* account, SSQLToken* pDB, SSQLToken* tableName, int32_t* len);

static int32_t getColumnIndexByName(SSQLToken* pToken, SSchema* pSchema, int32_t numOfCols);

static void getColumnName(tSQLExprItem* pItem, char* resultFieldName, int32_t nLen);
static void getRevisedName(char* resultFieldName, int32_t functionId, int32_t maxLen, char* columnName);

static int32_t addExprAndResultField(SSqlCmd* pCmd, int32_t colIdx, tSQLExprItem* pItem);

static int32_t insertResultField(SSqlCmd* pCmd, int32_t fieldIDInResult, SColumnList* pIdList, int16_t bytes,
                                 int8_t type, char* fieldName);
static int32_t changeFunctionID(int32_t optr, int16_t* pExpr);

78
static void setErrMsg(SSqlCmd* pCmd, const char* pzErrMsg);
H
hzcheng 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

static int32_t buildSelectionClause(SSqlCmd* pCmd, tSQLExprList* pSelection, bool isMetric);

static bool validateIpAddress(char* ip);
static bool onlyQueryMetricTags(SSqlCmd* pCmd);
static bool hasUnsupportFunctionsForMetricQuery(SSqlCmd* pCmd);
static bool functionCompatibleCheck(SSqlCmd* pCmd);

static void setColumnOffsetValueInResultset(SSqlCmd* pCmd);
static int32_t setGroupByClause(SSqlCmd* pCmd, tVariantList* pList);

static int32_t setIntervalClause(SSqlCmd* pCmd, SQuerySQL* pQuerySql);
static int32_t setSlidingClause(SSqlCmd* pCmd, SQuerySQL* pQuerySql);

static int32_t addProjectionExprAndResultField(SSqlCmd* pCmd, SSchema* pSchema, tSQLExprItem* pItem, bool isMet);

static int32_t buildQueryCond(SSqlObj* pSql, tSQLExpr* pExpr);
static int32_t setFillPolicy(SSqlCmd* pCmd, SQuerySQL* pQuerySQL);
static int32_t setOrderByClause(SSqlCmd* pCmd, SQuerySQL* pQuerySql, SSchema* pSchema, int32_t numOfCols);

static int32_t tsRewriteFieldNameIfNecessary(SSqlCmd* pCmd);
static bool validateOneTags(SSqlCmd* pCmd, TAOS_FIELD* pTagField);
static int32_t setAlterTableInfo(SSqlObj* pSql, struct SSqlInfo* pInfo);
static int32_t validateSqlFunctionInStreamSql(SSqlCmd* pCmd);
static int32_t buildArithmeticExprString(tSQLExpr* pExpr, char** exprString, SColumnIdList* colIdList);
static int32_t validateFunctionsInIntervalOrGroupbyQuery(SSqlCmd* pCmd);
static int32_t validateArithmeticSQLExpr(tSQLExpr* pExpr, SSchema* pSchema, int32_t numOfCols);
static int32_t validateDNodeConfig(tDCLSQL* pOptions);
static int32_t validateColumnName(char* name);
static int32_t setKillInfo(SSqlObj* pSql, struct SSqlInfo* pInfo);
static bool hasTimestampForPointInterpQuery(SSqlCmd* pCmd);
static void updateTagColumnIndex(SSqlCmd* pCmd);
static int32_t setLimitOffsetValueInfo(SSqlObj* pSql, SQuerySQL* pQuerySql);
static void addRequiredTagColumn(SSqlCmd* pCmd, int32_t tagColIndex);
113
static int32_t parseCreateDBOptions(SCreateDBInfo* pCreateDbSql, SSqlCmd* pCmd);
H
hzcheng 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141

static int32_t tscQueryOnlyMetricTags(SSqlCmd* pCmd, bool* queryOnMetricTags) {
  assert(pCmd->metricQuery == 1);

  // here colIdx == -1 means the special column tbname that is the name of each table
  *queryOnMetricTags = true;
  for (int32_t i = 0; i < pCmd->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pCmd, i);

    if (pExpr->sqlFuncId != TSDB_FUNC_TAGPRJ &&
        !(pExpr->sqlFuncId == TSDB_FUNC_COUNT && pExpr->colInfo.colIdx == -1)) {  // 23 == "tagprj" function
      *queryOnMetricTags = false;
      break;
    }
  }

  return TSDB_CODE_SUCCESS;
}

// todo handle memory leak in error handle function
int32_t tscToSQLCmd(SSqlObj* pSql, struct SSqlInfo* pInfo) {
  if (pInfo == NULL || pSql == NULL || pSql->signature != pSql) {
    return TSDB_CODE_APP_ERROR;
  }

  SSqlCmd* pCmd = &(pSql->cmd);

  if (!pInfo->validSql) {
142
    setErrMsg(pCmd, pInfo->pzErrMsg);
H
hzcheng 已提交
143 144 145 146 147 148 149 150 151 152 153 154
    return TSDB_CODE_INVALID_SQL;
  }

  tscCleanSqlCmd(pCmd);
  tscAllocPayloadWithSize(pCmd, TSDB_DEFAULT_PAYLOAD_SIZE);

  // transfer pInfo into select operation
  switch (pInfo->sqlType) {
    case DROP_TABLE:
    case DROP_USER:
    case DROP_ACCOUNT:
    case DROP_DATABASE: {
155 156 157
      const char* msg = "param name too long";
      const char* msg1 = "invalid ip address";
      const char* msg2 = "invalid name";
H
hzcheng 已提交
158 159 160

      SSQLToken* pzName = &pInfo->pDCLInfo->a[0];
      if ((pInfo->sqlType != DROP_DNODE) && (tscValidateName(pzName) != TSDB_CODE_SUCCESS)) {
161
        setErrMsg(pCmd, msg2);
H
hzcheng 已提交
162 163 164 165 166 167 168 169 170 171 172
        return TSDB_CODE_INVALID_SQL;
      }

      if (pInfo->sqlType == DROP_DATABASE) {
        assert(pInfo->pDCLInfo->nTokens == 2);

        pCmd->command = TSDB_SQL_DROP_DB;
        pCmd->existsCheck = (pInfo->pDCLInfo->a[1].n == 1);

        int32_t code = setObjFullName(pCmd->name, getAccountId(pSql), pzName, NULL, NULL);
        if (code != TSDB_CODE_SUCCESS) {
173
          setErrMsg(pCmd, msg2);
H
hzcheng 已提交
174 175 176 177 178 179 180 181 182 183 184
        }

        return code;
      } else if (pInfo->sqlType == DROP_TABLE) {
        assert(pInfo->pDCLInfo->nTokens == 2);

        pCmd->existsCheck = (pInfo->pDCLInfo->a[1].n == 1);
        pCmd->command = TSDB_SQL_DROP_TABLE;

        int32_t ret = setMeterID(pSql, pzName);
        if (ret != TSDB_CODE_SUCCESS) {
185
          setErrMsg(pCmd, msg);
H
hzcheng 已提交
186 187 188 189
        }
        return ret;
      } else {
        if (pzName->n > TSDB_USER_LEN) {
190
          setErrMsg(pCmd, msg);
H
hzcheng 已提交
191 192 193 194 195 196 197 198 199 200 201 202 203
          return TSDB_CODE_INVALID_SQL;
        }

        if (pInfo->sqlType == DROP_USER) {
          pCmd->command = TSDB_SQL_DROP_USER;
        }

        strncpy(pCmd->name, pzName->z, pzName->n);
        return TSDB_CODE_SUCCESS;
      }
    }

    case USE_DATABASE: {
204
      const char* msg = "db name too long";
H
hzcheng 已提交
205 206 207
      pCmd->command = TSDB_SQL_USE_DB;

      SSQLToken* pToken = &pInfo->pDCLInfo->a[0];
P
plum-lihui 已提交
208
	  
209
	  if (tscValidateName(pToken) != TSDB_CODE_SUCCESS) {
210 211
	  	const char* msg1 = "invalid db name";
        setErrMsg(pCmd, msg1);
212 213
        return TSDB_CODE_INVALID_SQL;
      }
P
plum-lihui 已提交
214
	  
H
hzcheng 已提交
215
      if (pToken->n > TSDB_DB_NAME_LEN) {
216
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
        return TSDB_CODE_INVALID_SQL;
      }

      int32_t ret = setObjFullName(pCmd->name, getAccountId(pSql), pToken, NULL, NULL);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }

      break;
    }

    case RESET_QUERY_CACHE: {
      pCmd->command = TSDB_SQL_RESET_CACHE;
      break;
    }

    case SHOW_DATABASES:
    case SHOW_TABLES:
    case SHOW_STABLES:
    case SHOW_DNODES:
    case SHOW_USERS:
    case SHOW_VGROUPS:
    case SHOW_CONNECTIONS:
    case SHOW_QUERIES:
    case SHOW_STREAMS:
    case SHOW_SCORES:
    case SHOW_CONFIGS: {
      return setShowInfo(pSql, pInfo);
    }

    case ALTER_DATABASE:
    case CREATE_DATABASE: {
249 250
      const char* msg2 = "name too long";
      const char* msg3 = "invalid db name";
H
hzcheng 已提交
251 252 253 254 255 256 257 258

      if (pInfo->sqlType == ALTER_DATABASE) {
        pCmd->command = TSDB_SQL_ALTER_DB;
      } else {
        pCmd->command = TSDB_SQL_CREATE_DB;
        pCmd->existsCheck = (pInfo->pDCLInfo->a[0].n == 1);
      }

259
      SCreateDBInfo* pCreateDB = &(pInfo->pDCLInfo->dbOpt);
H
hzcheng 已提交
260
      if (tscValidateName(&pCreateDB->dbname) != TSDB_CODE_SUCCESS) {
261
        setErrMsg(pCmd, msg3);
H
hzcheng 已提交
262 263 264 265 266
        return TSDB_CODE_INVALID_SQL;
      }

      int32_t ret = setObjFullName(pCmd->name, getAccountId(pSql), &(pCreateDB->dbname), NULL, NULL);
      if (ret != TSDB_CODE_SUCCESS) {
267
        setErrMsg(pCmd, msg2);
H
hzcheng 已提交
268 269 270
        return ret;
      }

271 272
      if (parseCreateDBOptions(pCreateDB, pCmd) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
273 274 275 276 277 278 279 280 281
      }

      break;
    }

    case CREATE_USER: {
      pCmd->command = (pInfo->sqlType == CREATE_USER) ? TSDB_SQL_CREATE_USER : TSDB_SQL_CREATE_ACCT;
      assert(pInfo->pDCLInfo->nTokens >= 2);

282 283 284 285 286
      const char* msg = "name or password too long";
      const char* msg1 = "password can not be empty";
      const char* msg2 = "invalid user/account name";
      const char* msg3 = "password needs single quote marks enclosed";
      const char* msg4 = "invalid state option, available options[no, r, w, all]";
H
hzcheng 已提交
287 288

      if (pInfo->pDCLInfo->a[1].type != TK_STRING) {
289
        setErrMsg(pCmd, msg3);
H
hzcheng 已提交
290 291 292 293 294 295 296 297
        return TSDB_CODE_INVALID_SQL;
      }

      strdequote(pInfo->pDCLInfo->a[1].z);
      strtrim(pInfo->pDCLInfo->a[1].z);  // trim space before and after passwords
      pInfo->pDCLInfo->a[1].n = strlen(pInfo->pDCLInfo->a[1].z);

      if (pInfo->pDCLInfo->a[1].n <= 0) {
298
        setErrMsg(pCmd, msg1);
H
hzcheng 已提交
299 300 301 302
        return TSDB_CODE_INVALID_SQL;
      }

      if (pInfo->pDCLInfo->a[0].n > TSDB_USER_LEN || pInfo->pDCLInfo->a[1].n > TSDB_PASSWORD_LEN) {
303
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
304 305 306 307
        return TSDB_CODE_INVALID_SQL;
      }

      if (tscValidateName(&pInfo->pDCLInfo->a[0]) != TSDB_CODE_SUCCESS) {
308
        setErrMsg(pCmd, msg2);
H
hzcheng 已提交
309 310 311 312 313 314 315 316 317 318 319 320
        return TSDB_CODE_INVALID_SQL;
      }

      strncpy(pCmd->name, pInfo->pDCLInfo->a[0].z, pInfo->pDCLInfo->a[0].n);     // name
      strncpy(pCmd->payload, pInfo->pDCLInfo->a[1].z, pInfo->pDCLInfo->a[1].n);  // passwd
      break;
    }
    case ALTER_ACCT: {
      pCmd->command = TSDB_SQL_ALTER_ACCT;
      int32_t num = pInfo->pDCLInfo->nTokens;
      assert(num >= 1 && num <= 2);

321 322 323 324 325
      const char* msg = "password too long";
      const char* msg1 = "password can not be empty";
      const char* msg2 = "invalid user/account name";
      const char* msg3 = "password needs single quote marks enclosed";
      const char* msg4 = "invalid state option, available options[no, r, w, all]";
H
hzcheng 已提交
326 327 328

      if (num == 2) {
        if (pInfo->pDCLInfo->a[1].type != TK_STRING) {
329
          setErrMsg(pCmd, msg3);
H
hzcheng 已提交
330 331 332 333 334 335 336 337
          return TSDB_CODE_INVALID_SQL;
        }

        strdequote(pInfo->pDCLInfo->a[1].z);
        strtrim(pInfo->pDCLInfo->a[1].z);  // trim space before and after passwords
        pInfo->pDCLInfo->a[1].n = strlen(pInfo->pDCLInfo->a[1].z);

        if (pInfo->pDCLInfo->a[1].n <= 0) {
338
          setErrMsg(pCmd, msg1);
H
hzcheng 已提交
339 340 341 342
          return TSDB_CODE_INVALID_SQL;
        }

        if (pInfo->pDCLInfo->a[1].n > TSDB_PASSWORD_LEN) {
343
          setErrMsg(pCmd, msg);
H
hzcheng 已提交
344 345 346 347 348 349 350
          return TSDB_CODE_INVALID_SQL;
        }

        strncpy(pCmd->payload, pInfo->pDCLInfo->a[1].z, pInfo->pDCLInfo->a[1].n);  // passwd
      }

      if (pInfo->pDCLInfo->a[0].n > TSDB_USER_LEN) {
351
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
352 353 354 355
        return TSDB_CODE_INVALID_SQL;
      }

      if (tscValidateName(&pInfo->pDCLInfo->a[0]) != TSDB_CODE_SUCCESS) {
356
        setErrMsg(pCmd, msg2);
H
hzcheng 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
        return TSDB_CODE_INVALID_SQL;
      }

      strncpy(pCmd->name, pInfo->pDCLInfo->a[0].z, pInfo->pDCLInfo->a[0].n);  // name

      SCreateAcctSQL* pAcctOpt = &pInfo->pDCLInfo->acctOpt;
      pCmd->defaultVal[0] = pAcctOpt->users;
      pCmd->defaultVal[1] = pAcctOpt->dbs;
      pCmd->defaultVal[2] = pAcctOpt->tseries;
      pCmd->defaultVal[3] = pAcctOpt->streams;
      pCmd->defaultVal[4] = pAcctOpt->pps;
      pCmd->defaultVal[5] = pAcctOpt->storage;
      pCmd->defaultVal[6] = pAcctOpt->qtime;
      pCmd->defaultVal[7] = pAcctOpt->conns;

      if (pAcctOpt->stat.n == 0) {
        pCmd->defaultVal[8] = -1;
      } else {
        strdequote(pAcctOpt->stat.z);
        pAcctOpt->stat.n = strlen(pAcctOpt->stat.z);

        if (pAcctOpt->stat.z[0] == 'r' && pAcctOpt->stat.n == 1) {
          pCmd->defaultVal[8] = TSDB_VN_READ_ACCCESS;
        } else if (pAcctOpt->stat.z[0] == 'w' && pAcctOpt->stat.n == 1) {
          pCmd->defaultVal[8] = TSDB_VN_WRITE_ACCCESS;
        } else if (strncmp(pAcctOpt->stat.z, "all", 3) == 0 && pAcctOpt->stat.n == 3) {
          pCmd->defaultVal[8] = TSDB_VN_ALL_ACCCESS;
        } else if (strncmp(pAcctOpt->stat.z, "no", 2) == 0 && pAcctOpt->stat.n == 2) {
          pCmd->defaultVal[8] = 0;
        } else {
387
          setErrMsg(pCmd, msg4);
H
hzcheng 已提交
388 389 390 391 392 393 394 395 396
          return TSDB_CODE_INVALID_SQL;
        }
      }
      break;
    }
    case DESCRIBE_TABLE: {
      pCmd->command = TSDB_SQL_DESCRIBE_TABLE;

      SSQLToken* pToken = &pInfo->pDCLInfo->a[0];
397
      const char* msg = "table name is too long";
H
hzcheng 已提交
398

399
	  if (tscValidateName(pToken) != TSDB_CODE_SUCCESS) {
400 401
	  	const char* msg1 = "invalid table name";
        setErrMsg(pCmd, msg1);
402 403
        return TSDB_CODE_INVALID_SQL;
      }
P
plum-lihui 已提交
404
	  
H
hzcheng 已提交
405
      if (pToken->n > TSDB_METER_NAME_LEN) {
406
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
407 408 409 410
        return TSDB_CODE_INVALID_SQL;
      }

      if (setMeterID(pSql, pToken) != TSDB_CODE_SUCCESS) {
411
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
        return TSDB_CODE_INVALID_SQL;
      }

      int32_t ret = tscGetMeterMeta(pSql, pSql->cmd.name);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }

      break;
    }
    case ALTER_DNODE:
    case ALTER_USER_PASSWD:
    case ALTER_USER_PRIVILEGES: {
      pCmd->command = (pInfo->sqlType == ALTER_DNODE) ? TSDB_SQL_CFG_PNODE : TSDB_SQL_ALTER_USER;

      tDCLSQL* pDCL = pInfo->pDCLInfo;

429 430 431 432
      const char* msg = "parameters too long";
      const char* msg1 = "invalid ip address";
      const char* msg2 = "invalid configure options or values";
      const char* msg3 = "password can not be empty";
H
hzcheng 已提交
433 434 435 436 437 438 439 440

      if (pInfo->sqlType != ALTER_DNODE) {
        strdequote(pDCL->a[1].z);
        strtrim(pDCL->a[1].z);
        pDCL->a[1].n = strlen(pDCL->a[1].z);
      }

      if (pDCL->a[1].n <= 0) {
441
        setErrMsg(pCmd, msg3);
H
hzcheng 已提交
442 443 444 445
        return TSDB_CODE_INVALID_SQL;
      }

      if (pDCL->a[0].n > TSDB_METER_NAME_LEN || pDCL->a[1].n > TSDB_PASSWORD_LEN) {
446
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
447 448 449 450 451 452 453 454 455
        return TSDB_CODE_INVALID_SQL;
      }

      if (pCmd->command == TSDB_SQL_CFG_PNODE) {
        char ip[128] = {0};
        strncpy(ip, pDCL->a[0].z, pDCL->a[0].n);

        /* validate the ip address */
        if (!validateIpAddress(ip)) {
456
          setErrMsg(pCmd, msg1);
H
hzcheng 已提交
457 458 459 460 461 462 463
          return TSDB_CODE_INVALID_SQL;
        }

        strcpy(pCmd->name, ip);

        /* validate the parameter names and options */
        if (validateDNodeConfig(pDCL) != TSDB_CODE_SUCCESS) {
464
          setErrMsg(pCmd, msg2);
H
hzcheng 已提交
465 466 467 468 469 470 471 472 473 474
          return TSDB_CODE_INVALID_SQL;
        }

        strncpy(pCmd->payload, pDCL->a[1].z, pDCL->a[1].n);

        if (pDCL->nTokens == 3) {
          pCmd->payload[pDCL->a[1].n] = ' ';  // add sep
          strncpy(&pCmd->payload[pDCL->a[1].n + 1], pDCL->a[2].z, pDCL->a[2].n);
        }
      } else {
475 476
        const char* msg = "invalid user rights";
        const char* msg1 = "password can not be empty or larger than 24 characters";
H
hzcheng 已提交
477 478 479 480 481 482 483 484 485 486 487 488

        strncpy(pCmd->name, pDCL->a[0].z, pDCL->a[0].n);

        if (pInfo->sqlType == ALTER_USER_PASSWD) {
          /* update the password for user */
          pCmd->order.order |= TSDB_ALTER_USER_PASSWD;

          strdequote(pDCL->a[1].z);
          pDCL->a[1].n = strlen(pDCL->a[1].z);

          if (pDCL->a[1].n <= 0 || pInfo->pDCLInfo->a[1].n > TSDB_PASSWORD_LEN) {
            /* password cannot be empty string */
489
            setErrMsg(pCmd, msg1);
H
hzcheng 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503
            return TSDB_CODE_INVALID_SQL;
          }

          strncpy(pCmd->payload, pDCL->a[1].z, pDCL->a[1].n);
        } else if (pInfo->sqlType == ALTER_USER_PRIVILEGES) {
          pCmd->order.order |= TSDB_ALTER_USER_PRIVILEGES;

          if (strncasecmp(pDCL->a[1].z, "super", 5) == 0 && pDCL->a[1].n == 5) {
            pCmd->count = 1;
          } else if (strncasecmp(pDCL->a[1].z, "read", 4) == 0 && pDCL->a[1].n == 4) {
            pCmd->count = 2;
          } else if (strncasecmp(pDCL->a[1].z, "write", 5) == 0 && pDCL->a[1].n == 5) {
            pCmd->count = 3;
          } else {
504
            setErrMsg(pCmd, msg);
H
hzcheng 已提交
505 506 507 508 509 510 511 512 513 514
            return TSDB_CODE_INVALID_SQL;
          }
        } else {
          return TSDB_CODE_INVALID_SQL;
        }
      }
      break;
    }
    case ALTER_LOCAL: {
      pCmd->command = TSDB_SQL_CFG_LOCAL;
515
      const char* msg = "parameter too long";
H
hzcheng 已提交
516
      if (pInfo->pDCLInfo->a[0].n > TSDB_METER_ID_LEN) {
517
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
518 519 520 521 522 523 524 525
        return TSDB_CODE_INVALID_SQL;
      }

      strncpy(pCmd->payload, pInfo->pDCLInfo->a[0].z, pInfo->pDCLInfo->a[0].n);
      break;
    }
    case TSQL_CREATE_NORMAL_METER:
    case TSQL_CREATE_NORMAL_METRIC: {
526 527
      const char* msg = "table name too long";
      const char* msg1 = "invalid table name";
H
hzcheng 已提交
528 529 530 531 532 533 534 535 536 537 538 539

      tFieldList* pFieldList = pInfo->pCreateTableInfo->colInfo.pColumns;
      tFieldList* pTagList = pInfo->pCreateTableInfo->colInfo.pTagColumns;
      assert(pFieldList != NULL);

      pCmd->command = TSDB_SQL_CREATE_TABLE;
      pCmd->existsCheck = pInfo->pCreateTableInfo->existCheck;

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

      if (tscValidateName(pzTableName) != TSDB_CODE_SUCCESS) {
540
        setErrMsg(pCmd, msg1);
H
hzcheng 已提交
541 542 543 544
        return TSDB_CODE_INVALID_SQL;
      }

      if (setMeterID(pSql, pzTableName) != TSDB_CODE_SUCCESS) {
545
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
        return TSDB_CODE_INVALID_SQL;
      }

      if (!validateTableColumnInfo(pFieldList, pCmd) ||
          (pTagList != NULL && !validateTagParams(pTagList, pFieldList, pCmd))) {
        return TSDB_CODE_INVALID_SQL;
      }

      int32_t col = 0;
      for (; col < pFieldList->nField; ++col) {
        tscFieldInfoSetValFromField(&pCmd->fieldsInfo, col, &pFieldList->p[col]);
      }
      pCmd->numOfCols = (int16_t)pFieldList->nField;

      if (pTagList != NULL) {  // create metric[optional]
        for (int32_t i = 0; i < pTagList->nField; ++i) {
          tscFieldInfoSetValFromField(&pCmd->fieldsInfo, col++, &pTagList->p[i]);
        }
        pCmd->count = pTagList->nField;
      }

      break;
    }
    case TSQL_CREATE_METER_FROM_METRIC: {
      pCmd->command = TSDB_SQL_CREATE_TABLE;
      pCmd->existsCheck = pInfo->pCreateTableInfo->existCheck;

573 574 575
      const char* msg = "invalid table name";
      const char* msg1 = "illegal value or data overflow";
      const char* msg2 = "illegal number of tags";
H
hzcheng 已提交
576 577 578 579

      // table name
      // metric name, create table by using dst
      SSQLToken* pToken = &(pInfo->pCreateTableInfo->usingInfo.metricName);
P
plum-lihui 已提交
580

581
	  if (tscValidateName(pToken) != TSDB_CODE_SUCCESS) {
582
        setErrMsg(pCmd, msg);
583 584
        return TSDB_CODE_INVALID_SQL;
      }
P
plum-lihui 已提交
585

H
hzcheng 已提交
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
      int32_t    ret = setMeterID(pSql, pToken);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }

      // get meter meta from mnode
      STagData* pTag = (STagData*)pCmd->payload;
      strncpy(pTag->name, pCmd->name, TSDB_METER_ID_LEN);

      tVariantList* pList = pInfo->pCreateTableInfo->usingInfo.pTagVals;

      int32_t code = tscGetMeterMeta(pSql, pTag->name);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      if (pSql->cmd.pMeterMeta->numOfTags != pList->nExpr) {
603
        setErrMsg(pCmd, msg2);
H
hzcheng 已提交
604 605 606 607 608 609 610 611 612 613
        return TSDB_CODE_INVALID_SQL;
      }

      /* too long tag values will be truncated automatically */
      SSchema* pTagSchema = tsGetTagSchema(pCmd->pMeterMeta);

      char* tagVal = pTag->data;
      for (int32_t i = 0; i < pList->nExpr; ++i) {
        int32_t ret = tVariantDump(&(pList->a[i].pVar), tagVal, pTagSchema[i].type);
        if (ret != TSDB_CODE_SUCCESS) {
614
          setErrMsg(pCmd, msg1);
H
hzcheng 已提交
615 616 617 618 619 620 621
          return TSDB_CODE_INVALID_SQL;
        }

        tagVal += pTagSchema[i].bytes;
      }

      if (tscValidateName(&pInfo->pCreateTableInfo->name) != TSDB_CODE_SUCCESS) {
622
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
623 624 625 626 627 628 629 630 631 632 633 634 635 636
        return TSDB_CODE_INVALID_SQL;
      }

      ret = setMeterID(pSql, &pInfo->pCreateTableInfo->name);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }

      pCmd->numOfCols = 0;
      pCmd->count = 0;
      break;
    }
    case TSQL_CREATE_STREAM: {
      pCmd->command = TSDB_SQL_CREATE_TABLE;
637 638
      const char* msg = "table name too long";
      const char* msg1 = "invalid table name";
H
hzcheng 已提交
639 640 641 642 643 644

      // if sql specifies db, use it, otherwise use default db
      SSQLToken* pzTableName = &(pInfo->pCreateTableInfo->name);
      SQuerySQL* pQuerySql = pInfo->pCreateTableInfo->pSelect;

      if (tscValidateName(pzTableName) != TSDB_CODE_SUCCESS) {
645
        setErrMsg(pCmd, msg1);
H
hzcheng 已提交
646 647 648 649 650
        return TSDB_CODE_INVALID_SQL;
      }

      SSQLToken* pSrcMeterName = &pInfo->pCreateTableInfo->pSelect->from;
      if (tscValidateName(pSrcMeterName) != TSDB_CODE_SUCCESS) {
651
        setErrMsg(pCmd, msg1);
H
hzcheng 已提交
652 653 654 655
        return TSDB_CODE_INVALID_SQL;
      }

      if (setMeterID(pSql, pSrcMeterName) != TSDB_CODE_SUCCESS) {
656
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
        return TSDB_CODE_INVALID_SQL;
      }

      int32_t code = tscGetMeterMeta(pSql, pCmd->name);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      bool isMetric = UTIL_METER_IS_METRIC(pCmd);
      if (buildSelectionClause(pCmd, pQuerySql->pSelection, isMetric) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
      }

      if (pQuerySql->pWhere != NULL) {  // query condition in stream computing
        if (buildQueryCond(pSql, pQuerySql->pWhere) != TSDB_CODE_SUCCESS) {
          return TSDB_CODE_INVALID_SQL;
        }
      }

      // set interval value
      if (setIntervalClause(pCmd, pQuerySql) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
      } else {
        if ((pCmd->nAggTimeInterval > 0) && (validateFunctionsInIntervalOrGroupbyQuery(pCmd) != TSDB_CODE_SUCCESS)) {
          return TSDB_CODE_INVALID_SQL;
        }
      }

      if (setSlidingClause(pCmd, pQuerySql) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
      }

      // set the created table[stream] name
      if (setMeterID(pSql, pzTableName) != TSDB_CODE_SUCCESS) {
691
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
692 693 694 695 696 697 698 699
        return TSDB_CODE_INVALID_SQL;
      }

      // copy sql length
      tscAllocPayloadWithSize(pCmd, pQuerySql->selectToken.n + 8);

      strncpy(pCmd->payload, pQuerySql->selectToken.z, pQuerySql->selectToken.n);
      if (pQuerySql->selectToken.n > TSDB_MAX_SAVED_SQL_LEN) {
700 701
        const char* msg4 = "sql too long";  // todo ADD support
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
        return TSDB_CODE_INVALID_SQL;
      }

      if (tsRewriteFieldNameIfNecessary(pCmd) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
      }

      pCmd->numOfCols = pCmd->fieldsInfo.numOfOutputCols;

      if (validateSqlFunctionInStreamSql(pCmd) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
      }

      /*
       * check if fill operation is available, the fill operation is parsed and executed during query execution, not here.
       */
      if (pQuerySql->fillType != NULL) {
        if (pCmd->nAggTimeInterval == 0) {
720 721
          const char* msg1 = "fill only available for interval query";
          setErrMsg(pCmd, msg1);
H
hzcheng 已提交
722 723 724 725 726 727 728 729

          return TSDB_CODE_INVALID_SQL;
        }

        tVariantListItem* pItem = &pQuerySql->fillType->a[0];
        if (pItem->pVar.nType == TSDB_DATA_TYPE_BINARY) {
          if (!((strncmp(pItem->pVar.pz, "none", 4) == 0 && pItem->pVar.nLen == 4) ||
                (strncmp(pItem->pVar.pz, "null", 4) == 0 && pItem->pVar.nLen == 4))) {
730 731
            const char* msg2 = "fill option not supported in stream computing";
            setErrMsg(pCmd, msg2);
H
hzcheng 已提交
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746

            return TSDB_CODE_INVALID_SQL;
          }
        }
      }

      break;
    }

    case TSQL_QUERY_METER: {
      SQuerySQL* pQuerySql = pInfo->pQueryInfo;
      assert(pQuerySql != NULL);

      // too many result columns not support order by in query
      if (pQuerySql->pSelection->nExpr > TSDB_MAX_COLUMNS) {
747 748
        const char* msg = "too many columns in selection clause";
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
749 750
        return TSDB_CODE_INVALID_SQL;
      }
751 752
 
	  if (tscValidateName(&(pQuerySql->from)) != TSDB_CODE_SUCCESS) {
753 754
	  	const char* msg = "invalid table name";
        setErrMsg(pCmd, msg);
755 756
        return TSDB_CODE_INVALID_SQL;
      }
P
plum-lihui 已提交
757
	  
H
hzcheng 已提交
758
      if (setMeterID(pSql, &pQuerySql->from) != TSDB_CODE_SUCCESS) {
759 760
        const char* msg = "table name too long";
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
        return TSDB_CODE_INVALID_SQL;
      }

      pSql->cmd.command = TSDB_SQL_SELECT;

      int32_t code = tscGetMeterMeta(pSql, pCmd->name);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      bool isMetric = UTIL_METER_IS_METRIC(pCmd);
      if (buildSelectionClause(pCmd, pQuerySql->pSelection, isMetric) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
      }

      // set interval value
      if (setIntervalClause(pCmd, pQuerySql) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
      } else {
        if ((pCmd->nAggTimeInterval > 0) && (validateFunctionsInIntervalOrGroupbyQuery(pCmd) != TSDB_CODE_SUCCESS)) {
          return TSDB_CODE_INVALID_SQL;
        }
      }

      // set sliding value
      SSQLToken* pSliding = &pQuerySql->sliding;
      if (pSliding->n != 0) {
        if (!tscEmbedded) {
789 790
          const char* msg = "not support sliding in query";
          setErrMsg(pCmd, msg);
H
hzcheng 已提交
791 792 793 794 795 796 797 798
          return TSDB_CODE_INVALID_SQL;
        }

        code = getTimestampInUsFromStr(pSliding->z, pSliding->n, &pCmd->nSlidingTime);
        if (pCmd->pMeterMeta->precision == TSDB_TIME_PRECISION_MILLI) {
          pCmd->nSlidingTime /= 1000;
        }

799 800
        const char* msg3 = "sliding value too small";
        const char* msg4 = "sliding value no larger than the interval value";
H
hzcheng 已提交
801 802

        if (pCmd->nSlidingTime < tsMinSlidingTime) {
803
          setErrMsg(pCmd, msg3);
H
hzcheng 已提交
804 805 806 807
          return TSDB_CODE_INVALID_SQL;
        }

        if (pCmd->nSlidingTime > pCmd->nAggTimeInterval) {
808
          setErrMsg(pCmd, msg4);
H
hzcheng 已提交
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
          return TSDB_CODE_INVALID_SQL;
        }
      }

      if (setGroupByClause(pCmd, pQuerySql->pGroupby) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
      }

      // set order by info
      if (setOrderByClause(pCmd, pQuerySql, tsGetSchema(pCmd->pMeterMeta), pCmd->pMeterMeta->numOfColumns) !=
          TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
      }

      // set where info
      if (pQuerySql->pWhere != NULL) {
        if (buildQueryCond(pSql, pQuerySql->pWhere) != TSDB_CODE_SUCCESS) {
          return TSDB_CODE_INVALID_SQL;
        }

        if (pCmd->pMeterMeta->precision == TSDB_TIME_PRECISION_MILLI) {
          pCmd->stime = pCmd->stime / 1000;
          pCmd->etime = pCmd->etime / 1000;
        }
      } else {  // set the time range
        pCmd->stime = 0;
        pCmd->etime = INT64_MAX;
      }

      // no result due to invalid query time range
      if (pCmd->stime > pCmd->etime) {
        pCmd->command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
        return TSDB_CODE_SUCCESS;
      }

      if (!hasTimestampForPointInterpQuery(pCmd)) {
845 846
        const char* msg = "point interpolation query needs timestamp";
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
847 848 849 850
        return TSDB_CODE_INVALID_SQL;
      }

      if (pQuerySql->fillType != NULL) {
851 852
        const char* msg1 = "fill only available for interval query";
        const char* msg2 = "start(end) time of query range required or time range too large";
H
hzcheng 已提交
853 854

        if (pCmd->nAggTimeInterval == 0 && (!tscIsPointInterpQuery(pCmd))) {
855
          setErrMsg(pCmd, msg1);
H
hzcheng 已提交
856 857 858 859 860 861 862 863 864
          return TSDB_CODE_INVALID_SQL;
        }

        if (pCmd->nAggTimeInterval > 0) {
          int64_t timeRange = labs(pCmd->stime - pCmd->etime);
          // number of result is not greater than 10,000,000

          // TODO define macro
          if ((timeRange == 0) || (timeRange / pCmd->nAggTimeInterval) > 10000000) {
865
            setErrMsg(pCmd, msg2);
H
hzcheng 已提交
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
            return TSDB_CODE_INVALID_SQL;
          }
        }

        int32_t ret = setFillPolicy(pCmd, pQuerySql);
        if (ret != TSDB_CODE_SUCCESS) {
          return ret;
        }
      }

      // handle the limit offset value, validate the limit
      pCmd->limit = pQuerySql->limit;

      /* temporarily save the original limitation value */
      if ((code = setLimitOffsetValueInfo(pSql, pQuerySql)) != TSDB_CODE_SUCCESS) {
        return code;
      }

      setColumnOffsetValueInResultset(pCmd);
      updateTagColumnIndex(pCmd);
      break;
    }
    case TSQL_INSERT: {
      assert(false);
    }
    case ALTER_TABLE_ADD_COLUMN:
    case ALTER_TABLE_DROP_COLUMN:
    case ALTER_TABLE_TAGS_ADD:
    case ALTER_TABLE_TAGS_DROP:
    case ALTER_TABLE_TAGS_CHG:
    case ALTER_TABLE_TAGS_SET: {
      return setAlterTableInfo(pSql, pInfo);
    }

    case KILL_CONNECTION:
    case KILL_QUERY:
    case KILL_STREAM: {
      return setKillInfo(pSql, pInfo);
    }

    default:
      return TSDB_CODE_INVALID_SQL;
  }

  return TSDB_CODE_SUCCESS;
}

static bool isTopBottomQuery(SSqlCmd* pCmd) {
  if (pCmd->exprsInfo.numOfExprs != 2) {
    return false;
  }

  int32_t functionId = tscSqlExprGet(pCmd, 1)->sqlFuncId;
  return functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM || functionId == TSDB_FUNC_TOP_DST ||
         functionId == TSDB_FUNC_BOTTOM_DST;
}

int32_t setIntervalClause(SSqlCmd* pCmd, SQuerySQL* pQuerySql) {
  if (pQuerySql->interval.type == 0) {
    return TSDB_CODE_SUCCESS;
  }

  // interval is not null
  SSQLToken* t = &pQuerySql->interval;
  if (getTimestampInUsFromStr(t->z, t->n, &pCmd->nAggTimeInterval) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_INVALID_SQL;
  }

  /* revised the time precision according to the flag */
  if (pCmd->pMeterMeta->precision == TSDB_TIME_PRECISION_MILLI) {
    pCmd->nAggTimeInterval = pCmd->nAggTimeInterval / 1000;
  }

  /* parser has filter the illegal type, no need to check here */
  pCmd->intervalTimeUnit = pQuerySql->interval.z[pQuerySql->interval.n - 1];

  // interval cannot be less than 10 milliseconds
  if (pCmd->nAggTimeInterval < tsMinIntervalTime) {
944 945
    const char* msg = "interval cannot be less than 10 ms";
    setErrMsg(pCmd, msg);
H
hzcheng 已提交
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
    return TSDB_CODE_INVALID_SQL;
  }

  // for top/bottom + interval query, we do not add additional timestamp column in the front
  if (isTopBottomQuery(pCmd)) {
    return TSDB_CODE_SUCCESS;
  }

  // need to add timestamp column in resultset, if interval is existed
  tscSqlExprInsert(pCmd, 0, TSDB_FUNC_TS, 0, TSDB_DATA_TYPE_TIMESTAMP, TSDB_KEYSIZE);

  SColumnList ids = {.numOfCols = 1, .ids = {0}};
  int32_t ret = insertResultField(pCmd, 0, &ids, TSDB_KEYSIZE, TSDB_DATA_TYPE_TIMESTAMP, aAggs[TSDB_FUNC_TS].aName);

  return ret;
}

int32_t setSlidingClause(SSqlCmd* pCmd, SQuerySQL* pQuerySql) {
964 965
  const char* msg0 = "sliding value too small";
  const char* msg1 = "sliding value no larger than the interval value";
H
hzcheng 已提交
966 967 968 969 970 971 972 973 974 975

  SSQLToken* pSliding = &pQuerySql->sliding;

  if (pSliding->n != 0) {
    getTimestampInUsFromStr(pSliding->z, pSliding->n, &pCmd->nSlidingTime);
    if (pCmd->pMeterMeta->precision == TSDB_TIME_PRECISION_MILLI) {
      pCmd->nSlidingTime /= 1000;
    }

    if (pCmd->nSlidingTime < tsMinSlidingTime) {
976
      setErrMsg(pCmd, msg0);
H
hzcheng 已提交
977 978 979 980
      return TSDB_CODE_INVALID_SQL;
    }

    if (pCmd->nSlidingTime > pCmd->nAggTimeInterval) {
981
      setErrMsg(pCmd, msg1);
H
hzcheng 已提交
982 983 984 985 986 987 988 989 990 991 992 993 994
      return TSDB_CODE_INVALID_SQL;
    }
  }

  return TSDB_CODE_SUCCESS;
}

int32_t setMeterID(SSqlObj *pSql, SSQLToken *pzTableName) {
  SSqlCmd *pCmd = &(pSql->cmd);
  int32_t ret = TSDB_CODE_SUCCESS;

  //clear array
  memset(pCmd->name, 0, tListLen(pCmd->name));
995
  const char* msg = "name too long";
H
hzcheng 已提交
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011

  if (hasSpecifyDB(pzTableName)) {
    /*
     * db has been specified in sql string
     * so we ignore current db path
     */
    ret = setObjFullName(pCmd->name, getAccountId(pSql), NULL, pzTableName, NULL);
  } else {
    /* get current DB name first, then set it into path */
    SSQLToken t = {0};
    getCurrentDBName(pSql, &t);

    ret = setObjFullName(pCmd->name, NULL, &t, pzTableName, NULL);
  }

  if (ret != TSDB_CODE_SUCCESS) {
1012
    setErrMsg(pCmd, msg);
H
hzcheng 已提交
1013 1014 1015 1016 1017 1018 1019 1020
  }

  return ret;
}

static bool validateTableColumnInfo(tFieldList* pFieldList, SSqlCmd* pCmd) {
  assert(pFieldList != NULL);

1021 1022 1023 1024 1025 1026 1027
  const char* msg = "illegal number of columns";
  const char* msg1 = "first column must be timestamp";
  const char* msg2 = "row length exceeds max length";
  const char* msg3 = "duplicated column names";
  const char* msg4 = "invalid data types";
  const char* msg5 = "invalid binary/nchar column length";
  const char* msg6 = "invalid column name";
H
hzcheng 已提交
1028 1029 1030

  // number of fields no less than 2
  if (pFieldList->nField <= 1 || pFieldList->nField > TSDB_MAX_COLUMNS) {
1031
    setErrMsg(pCmd, msg);
H
hzcheng 已提交
1032 1033 1034 1035 1036
    return false;
  }

  // first column must be timestamp
  if (pFieldList->p[0].type != TSDB_DATA_TYPE_TIMESTAMP) {
1037
    setErrMsg(pCmd, msg1);
H
hzcheng 已提交
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
    return false;
  }

  int32_t nLen = 0;
  for (int32_t i = 0; i < pFieldList->nField; ++i) {
    nLen += pFieldList->p[i].bytes;
  }

  // max row length must be less than TSDB_MAX_BYTES_PER_ROW
  if (nLen > TSDB_MAX_BYTES_PER_ROW) {
1048
    setErrMsg(pCmd, msg2);
H
hzcheng 已提交
1049 1050 1051 1052 1053 1054 1055
    return false;
  }

  // field name must be unique
  for (int32_t i = 0; i < pFieldList->nField; ++i) {
    TAOS_FIELD* pField = &pFieldList->p[i];
    if (pField->type < TSDB_DATA_TYPE_BOOL || pField->type > TSDB_DATA_TYPE_NCHAR) {
1056
      setErrMsg(pCmd, msg4);
H
hzcheng 已提交
1057 1058 1059 1060 1061
      return false;
    }

    if ((pField->type == TSDB_DATA_TYPE_BINARY && (pField->bytes <= 0 || pField->bytes > TSDB_MAX_BINARY_LEN)) ||
        (pField->type == TSDB_DATA_TYPE_NCHAR && (pField->bytes <= 0 || pField->bytes > TSDB_MAX_NCHAR_LEN))) {
1062
      setErrMsg(pCmd, msg5);
H
hzcheng 已提交
1063 1064 1065 1066
      return false;
    }

    if (validateColumnName(pField->name) != TSDB_CODE_SUCCESS) {
1067
      setErrMsg(pCmd, msg6);
H
hzcheng 已提交
1068 1069 1070 1071
      return false;
    }

    if (has(pFieldList, i + 1, pFieldList->p[i].name) == true) {
1072
      setErrMsg(pCmd, msg3);
H
hzcheng 已提交
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
      return false;
    }
  }

  return true;
}

static bool validateTagParams(tFieldList* pTagsList, tFieldList* pFieldList, SSqlCmd* pCmd) {
  assert(pTagsList != NULL);

1083 1084 1085 1086 1087 1088 1089
  const char* msg1 = "invalid number of tag columns";
  const char* msg2 = "tag length too long";
  const char* msg3 = "duplicated column names";
  const char* msg4 = "timestamp not allowed in tags";
  const char* msg5 = "invalid data type in tags";
  const char* msg6 = "invalid tag name";
  const char* msg7 = "invalid binary/nchar tag length";
H
hzcheng 已提交
1090 1091 1092

  // number of fields at least 1
  if (pTagsList->nField < 1 || pTagsList->nField > TSDB_MAX_TAGS) {
1093
    setErrMsg(pCmd, msg1);
H
hzcheng 已提交
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
    return false;
  }

  int32_t nLen = 0;
  for (int32_t i = 0; i < pTagsList->nField; ++i) {
    nLen += pTagsList->p[i].bytes;
  }

  // max tag row length must be less than TSDB_MAX_TAGS_LEN
  if (nLen > TSDB_MAX_TAGS_LEN) {
1104
    setErrMsg(pCmd, msg2);
H
hzcheng 已提交
1105 1106 1107 1108 1109 1110
    return false;
  }

  // field name must be unique
  for (int32_t i = 0; i < pTagsList->nField; ++i) {
    if (has(pFieldList, 0, pTagsList->p[i].name) == true) {
1111
      setErrMsg(pCmd, msg3);
H
hzcheng 已提交
1112 1113 1114 1115 1116 1117 1118
      return false;
    }
  }

  /* timestamp in tag is not allowed */
  for (int32_t i = 0; i < pTagsList->nField; ++i) {
    if (pTagsList->p[i].type == TSDB_DATA_TYPE_TIMESTAMP) {
1119
      setErrMsg(pCmd, msg4);
H
hzcheng 已提交
1120 1121 1122 1123
      return false;
    }

    if (pTagsList->p[i].type < TSDB_DATA_TYPE_BOOL || pTagsList->p[i].type > TSDB_DATA_TYPE_NCHAR) {
1124
      setErrMsg(pCmd, msg5);
H
hzcheng 已提交
1125 1126 1127 1128 1129
      return false;
    }

    if ((pTagsList->p[i].type == TSDB_DATA_TYPE_BINARY && pTagsList->p[i].bytes <= 0) ||
        (pTagsList->p[i].type == TSDB_DATA_TYPE_NCHAR && pTagsList->p[i].bytes <= 0)) {
1130
      setErrMsg(pCmd, msg7);
H
hzcheng 已提交
1131 1132 1133 1134
      return false;
    }

    if (validateColumnName(pTagsList->p[i].name) != TSDB_CODE_SUCCESS) {
1135
      setErrMsg(pCmd, msg6);
H
hzcheng 已提交
1136 1137 1138 1139
      return false;
    }

    if (has(pTagsList, i + 1, pTagsList->p[i].name) == true) {
1140
      setErrMsg(pCmd, msg3);
H
hzcheng 已提交
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
      return false;
    }
  }

  return true;
}

/*
 * tags name /column name is truncated in sql.y
 */
bool validateOneTags(SSqlCmd* pCmd, TAOS_FIELD* pTagField) {
1152 1153 1154 1155 1156 1157
  const char* msg1 = "timestamp not allowed in tags";
  const char* msg2 = "duplicated column names";
  const char* msg3 = "tag length too long";
  const char* msg4 = "invalid tag name";
  const char* msg5 = "invalid binary/nchar tag length";
  const char* msg6 = "invalid data type in tags";
H
hzcheng 已提交
1158 1159 1160 1161 1162 1163 1164 1165

  SMeterMeta* pMeterMeta = pCmd->pMeterMeta;

  // no more than 6 tags
  if (pMeterMeta->numOfTags == TSDB_MAX_TAGS) {
    char msg[128] = {0};
    sprintf(msg, "tags no more than %d", TSDB_MAX_TAGS);

1166
    setErrMsg(pCmd, msg);
H
hzcheng 已提交
1167 1168 1169 1170 1171
    return false;
  }

  // no timestamp allowable
  if (pTagField->type == TSDB_DATA_TYPE_TIMESTAMP) {
1172
    setErrMsg(pCmd, msg1);
H
hzcheng 已提交
1173 1174 1175 1176
    return false;
  }

  if (pTagField->type < TSDB_DATA_TYPE_BOOL && pTagField->type > TSDB_DATA_TYPE_NCHAR) {
1177
    setErrMsg(pCmd, msg6);
H
hzcheng 已提交
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
    return false;
  }

  SSchema* pTagSchema = tsGetTagSchema(pCmd->pMeterMeta);
  int32_t  nLen = 0;

  for (int32_t i = 0; i < pMeterMeta->numOfTags; ++i) {
    nLen += pTagSchema[i].bytes;
  }

  // length less than TSDB_MAX_TASG_LEN
  if (nLen + pTagField->bytes > TSDB_MAX_TAGS_LEN) {
1190
    setErrMsg(pCmd, msg3);
H
hzcheng 已提交
1191 1192 1193 1194 1195
    return false;
  }

  // tags name can not be a keyword
  if (validateColumnName(pTagField->name) != TSDB_CODE_SUCCESS) {
1196
    setErrMsg(pCmd, msg4);
H
hzcheng 已提交
1197 1198 1199 1200 1201
    return false;
  }

  // binary(val), val can not be equalled to or less than 0
  if ((pTagField->type == TSDB_DATA_TYPE_BINARY || pTagField->type == TSDB_DATA_TYPE_NCHAR) && pTagField->bytes <= 0) {
1202
    setErrMsg(pCmd, msg5);
H
hzcheng 已提交
1203 1204 1205 1206 1207 1208 1209 1210
    return false;
  }

  // field name must be unique
  SSchema* pSchema = tsGetSchema(pMeterMeta);

  for (int32_t i = 0; i < pMeterMeta->numOfTags + pMeterMeta->numOfColumns; ++i) {
    if (strncasecmp(pTagField->name, pSchema[i].name, TSDB_COL_NAME_LEN) == 0) {
1211
      setErrMsg(pCmd, msg2);
H
hzcheng 已提交
1212 1213 1214 1215 1216 1217 1218 1219
      return false;
    }
  }

  return true;
}

bool validateOneColumn(SSqlCmd* pCmd, TAOS_FIELD* pColField) {
1220 1221 1222 1223 1224 1225
  const char* msg1 = "too many columns";
  const char* msg2 = "duplicated column names";
  const char* msg3 = "column length too long";
  const char* msg4 = "invalid data types";
  const char* msg5 = "invalid column name";
  const char* msg6 = "invalid column length";
H
hzcheng 已提交
1226 1227 1228 1229 1230 1231

  SMeterMeta* pMeterMeta = pCmd->pMeterMeta;

  // no more max columns
  if (pMeterMeta->numOfColumns >= TSDB_MAX_COLUMNS ||
      pMeterMeta->numOfTags + pMeterMeta->numOfColumns >= TSDB_MAX_COLUMNS) {
1232
    setErrMsg(pCmd, msg1);
H
hzcheng 已提交
1233 1234 1235 1236
    return false;
  }

  if (pColField->type < TSDB_DATA_TYPE_BOOL || pColField->type > TSDB_DATA_TYPE_NCHAR) {
1237
    setErrMsg(pCmd, msg4);
H
hzcheng 已提交
1238 1239 1240 1241
    return false;
  }

  if (validateColumnName(pColField->name) != TSDB_CODE_SUCCESS) {
1242
    setErrMsg(pCmd, msg5);
H
hzcheng 已提交
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
    return false;
  }

  SSchema* pSchema = tsGetSchema(pMeterMeta);
  int32_t  nLen = 0;

  for (int32_t i = 0; i < pMeterMeta->numOfColumns; ++i) {
    nLen += pSchema[i].bytes;
  }

  if (pColField->bytes <= 0) {
1254
    setErrMsg(pCmd, msg6);
H
hzcheng 已提交
1255 1256 1257 1258 1259
    return false;
  }

  // length less than TSDB_MAX_BYTES_PER_ROW
  if (nLen + pColField->bytes > TSDB_MAX_BYTES_PER_ROW) {
1260
    setErrMsg(pCmd, msg3);
H
hzcheng 已提交
1261 1262 1263 1264 1265 1266
    return false;
  }

  // field name must be unique
  for (int32_t i = 0; i < pMeterMeta->numOfTags + pMeterMeta->numOfColumns; ++i) {
    if (strncasecmp(pColField->name, pSchema[i].name, TSDB_COL_NAME_LEN) == 0) {
1267
      setErrMsg(pCmd, msg2);
H
hzcheng 已提交
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
      return false;
    }
  }

  return true;
}

/* is contained in pFieldList or not */
static bool has(tFieldList* pFieldList, int32_t startIdx, char* name) {
  for (int32_t j = startIdx; j < pFieldList->nField; ++j) {
    if (strncasecmp(name, pFieldList->p[j].name, TSDB_COL_NAME_LEN) == 0) return true;
  }

  return false;
}

static char* getAccountId(SSqlObj* pSql) { return pSql->pTscObj->acctId; }

static void getCurrentDBName(SSqlObj* pSql, SSQLToken* pDBToken) {
  pDBToken->z = pSql->pTscObj->db;
  pDBToken->n = strlen(pSql->pTscObj->db);
}

/* length limitation, strstr cannot be applied */
static bool hasSpecifyDB(SSQLToken* pTableName) {
  for (int32_t i = 0; i < pTableName->n; ++i) {
    if (pTableName->z[i] == TS_PATH_DELIMITER[0]) {
      return true;
    }
  }

  return false;
}

static int32_t setObjFullName(char* fullName, char* account, SSQLToken* pDB, SSQLToken* tableName, int32_t* xlen) {
  int32_t totalLen = 0;

  if (account != NULL) {
    int32_t len = strlen(account);
    strcpy(fullName, account);
    fullName[len] = TS_PATH_DELIMITER[0];
    totalLen += (len + 1);
  }

  /* db name is not specified, the tableName dose not include db name */
  if (pDB != NULL) {
    if (pDB->n > TSDB_DB_NAME_LEN) {
      return TSDB_CODE_INVALID_SQL;
    }

    memcpy(&fullName[totalLen], pDB->z, pDB->n);
    totalLen += pDB->n;
  }

  if (tableName != NULL) {
    if (pDB != NULL) {
      fullName[totalLen] = TS_PATH_DELIMITER[0];
      totalLen += 1;

      /* here we only check the table name length limitation */
      if (tableName->n > TSDB_METER_NAME_LEN) {
        return TSDB_CODE_INVALID_SQL;
      }
    } else {  // pDB == NULL, the db prefix name is specified in tableName
      /* the length limitation includes tablename + dbname + sep */
      if (tableName->n > TSDB_METER_NAME_LEN + TSDB_DB_NAME_LEN + tListLen(TS_PATH_DELIMITER)) {
        return TSDB_CODE_INVALID_SQL;
      }
    }

    memcpy(&fullName[totalLen], tableName->z, tableName->n);
    totalLen += tableName->n;
  }

  fullName[totalLen] = 0;

  if (xlen != NULL) {
    *xlen = totalLen;
  }
  return (totalLen <= TSDB_METER_ID_LEN) ? TSDB_CODE_SUCCESS : TSDB_CODE_INVALID_SQL;
}

static void extractColumnNameFromString(tSQLExprItem* pItem, char* tmpBuf) {
  if (pItem->pNode->nSQLOptr == TK_STRING) {
    strdequote(pItem->pNode->val.pz);
    strcpy(tmpBuf, pItem->pNode->val.pz);

    tVariantDestroy(&pItem->pNode->val);
    pItem->pNode->nSQLOptr = TK_ID;

    SSQLToken* pIdToken = &pItem->pNode->colInfo;
    pIdToken->type = TK_ID;
    pIdToken->z = tmpBuf;
    pIdToken->n = strlen(pIdToken->z);
  }
}

int32_t buildSelectionClause(SSqlCmd* pCmd, tSQLExprList* pSelection, bool isMetric) {
  assert(pSelection != NULL && pCmd != NULL);

1368 1369 1370 1371
  const char* msg1 = "invalid column name/illegal column type in arithmetic expression";
  const char* msg2 = "functions can not be mixed up";
  const char* msg3 = "not support query expression";
  const char* msg4 = "function not support in STable query";
H
hzcheng 已提交
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 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407

  SSchema* pSchema = tsGetSchema(pCmd->pMeterMeta);

  for (int32_t i = 0; i < pSelection->nExpr; ++i) {
    int32_t outputIndex = pCmd->fieldsInfo.numOfOutputCols;

    tSQLExprItem* pItem = &pSelection->a[i];
    if (pItem->pNode->nSQLOptr == TK_ALL || pItem->pNode->nSQLOptr == TK_ID ||
        pItem->pNode->nSQLOptr == TK_STRING) {  // project on all fields

      if (pItem->pNode->nSQLOptr == TK_ID && (pItem->pNode->colInfo.z == NULL && pItem->pNode->colInfo.n == 0)) {
        /* it is actually a function, but the function name is invalid */
        return TSDB_CODE_INVALID_SQL;
      }

      /* if the name of column is quoted, remove it and set the right
       * information for later process */
      char tmpName[TSDB_METER_NAME_LEN + 1] = {0};
      extractColumnNameFromString(pItem, tmpName);

      /* select * / select field_name1, field_name2  from table_name */
      int32_t ret = addProjectionExprAndResultField(pCmd, pSchema, pItem, isMetric);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }
    } else if (pItem->pNode->nSQLOptr >= TK_COUNT && pItem->pNode->nSQLOptr <= TK_LAST_ROW) {
      // sql function optr
      /* sql function in selection clause, append sql function info in pSqlCmd structure sequentially */
      if (addExprAndResultField(pCmd, outputIndex, pItem) == -1) {
        return TSDB_CODE_INVALID_SQL;
      }

    } else if (pItem->pNode->nSQLOptr >= TK_PLUS && pItem->pNode->nSQLOptr <= TK_REM) {
      /* arithmetic function in select*/
      int32_t ret = validateArithmeticSQLExpr(pItem->pNode, pSchema, pCmd->pMeterMeta->numOfColumns);
      if (ret != TSDB_CODE_SUCCESS) {
1408
        setErrMsg(pCmd, msg1);
H
hzcheng 已提交
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442
        return TSDB_CODE_INVALID_SQL;
      }

      SColumnIdList ids = {0};
      ids.pSchema = pSchema;
      ids.numOfCols = pCmd->pMeterMeta->numOfColumns;

      char  arithmeticExprStr[1024] = {0};
      char* p = arithmeticExprStr;

      if (buildArithmeticExprString(pItem->pNode, &p, &ids) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
      }

      // expr string is set as the parameter of function
      SSqlExpr* pExpr = tscSqlExprInsert(pCmd, outputIndex, TSDB_FUNC_ARITHM, 0, TSDB_DATA_TYPE_DOUBLE, sizeof(double));
      addExprParams(pExpr, arithmeticExprStr, TSDB_DATA_TYPE_BINARY, strlen(arithmeticExprStr));

      /* todo alias name should use the original sql string */
      if (pItem->aliasName != NULL) {
        strncpy(pExpr->aliasName, pItem->aliasName, TSDB_COL_NAME_LEN);
      } else {
        strncpy(pExpr->aliasName, arithmeticExprStr, TSDB_COL_NAME_LEN);
      }

      SColumnList idx = {.numOfCols = ids.numOfRecordedCols, .ids = {0}};
      memcpy(idx.ids, ids.ids, ids.numOfRecordedCols * sizeof(ids.ids[0]));

      insertResultField(pCmd, i, &idx, sizeof(double), TSDB_DATA_TYPE_DOUBLE, pExpr->aliasName);
    } else {
      /*
       * not support such expression
       * e.g., select 12+5 from table_name
       */
1443
      setErrMsg(pCmd, msg3);
H
hzcheng 已提交
1444 1445 1446 1447 1448 1449 1450 1451 1452
      return TSDB_CODE_INVALID_SQL;
    }

    if (pCmd->fieldsInfo.numOfOutputCols > TSDB_MAX_COLUMNS) {
      return TSDB_CODE_INVALID_SQL;
    }
  }

  if (!functionCompatibleCheck(pCmd)) {
1453
    setErrMsg(pCmd, msg2);
H
hzcheng 已提交
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
    return TSDB_CODE_INVALID_SQL;
  }

  if (isMetric) {
    pCmd->metricQuery = 1;

    if (onlyQueryMetricTags(pCmd)) {  // local handle the metric tag query
      pCmd->command = TSDB_SQL_RETRIEVE_TAGS;
      pCmd->count = pCmd->pMeterMeta->numOfColumns;  // the number of meter schema, tricky.
    }

    /*
     * transfer sql functions that need secondary merge into another format
     * in dealing with metric queries such as: count/first/last
     */
    tscTansformSQLFunctionForMetricQuery(pCmd);

    if (hasUnsupportFunctionsForMetricQuery(pCmd)) {
1472
      setErrMsg(pCmd, msg4);
H
hzcheng 已提交
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579
      return TSDB_CODE_INVALID_SQL;
    }
  }

  return TSDB_CODE_SUCCESS;
}

int32_t insertResultField(SSqlCmd* pCmd, int32_t outputIndex, SColumnList* pIdList, int16_t bytes, int8_t type,
                          char* fieldName) {
  for (int32_t i = 0; i < pIdList->numOfCols; ++i) {
    tscColumnInfoInsert(pCmd, pIdList->ids[i]);
  }

  tscFieldInfoSetValue(&pCmd->fieldsInfo, outputIndex, type, fieldName, bytes);
  return TSDB_CODE_SUCCESS;
}

void setProjExprForMetricQuery(SSqlCmd* pCmd, int32_t outputIndex, int32_t colIdx) {
  pCmd->metricQuery = 1;
  SSchema* pSchema = tsGetSchemaColIdx(pCmd->pMeterMeta, colIdx);

  int16_t functionId = (int16_t)((colIdx >= pCmd->pMeterMeta->numOfColumns) ? TSDB_FUNC_TAGPRJ :  // tagPrj function
                                     TSDB_FUNC_PRJ);                                              // colprj function

  int32_t numOfCols = pCmd->pMeterMeta->numOfColumns;

  bool isTag = false;
  if (colIdx >= numOfCols) {
    colIdx -= numOfCols;
    addRequiredTagColumn(pCmd, colIdx);
    isTag = true;
  }

  SSqlExpr* pExpr = tscSqlExprInsert(pCmd, outputIndex, functionId, colIdx, pSchema->type, pSchema->bytes);
  pExpr->colInfo.isTag = isTag;
}

void addRequiredTagColumn(SSqlCmd* pCmd, int32_t tagColIndex) {
  if (pCmd->numOfReqTags == 0 || pCmd->tagColumnIndex[pCmd->numOfReqTags - 1] < tagColIndex) {
    pCmd->tagColumnIndex[pCmd->numOfReqTags++] = tagColIndex;
  } else {  // find the appropriate position
    for (int32_t i = 0; i < pCmd->numOfReqTags; ++i) {
      if (tagColIndex > pCmd->tagColumnIndex[i]) {
        continue;
      } else if (tagColIndex == pCmd->tagColumnIndex[i]) {
        break;
      } else {
        memmove(&pCmd->tagColumnIndex[i + 1], &pCmd->tagColumnIndex[i],
                sizeof(pCmd->tagColumnIndex[0]) * (pCmd->numOfReqTags - i));
        pCmd->tagColumnIndex[i] = tagColIndex;

        pCmd->numOfReqTags++;
        break;
      }
    }
  }

  // plus one means tbname
  assert(tagColIndex >= -1 && tagColIndex < TSDB_MAX_TAGS && pCmd->numOfReqTags <= TSDB_MAX_TAGS + 1);
}

int32_t addProjectionExprAndResultField(SSqlCmd* pCmd, SSchema* pSchema, tSQLExprItem* pItem, bool isMetric) {
  int32_t startPos = pCmd->fieldsInfo.numOfOutputCols;

  if (pItem->pNode->nSQLOptr == TK_ALL) {  // project on all fields
    int32_t     numOfTotalColumns = 0;
    SMeterMeta* pMeterMeta = pCmd->pMeterMeta;

    if (isMetric) {  // metric query
      numOfTotalColumns = pMeterMeta->numOfColumns + pMeterMeta->numOfTags;

      for (int32_t j = 0; j < numOfTotalColumns; ++j) {
        setProjExprForMetricQuery(pCmd, startPos + j, j);

        SColumnList ids = {.numOfCols = 1, .ids = {j}};

        // tag columns do not add to source list
        if (j >= pMeterMeta->numOfColumns) {
          ids.numOfCols = 0;
        }
        insertResultField(pCmd, startPos + j, &ids, pSchema[j].bytes, pSchema[j].type, pSchema[j].name);
      }
    } else {  // meter query
      numOfTotalColumns = pMeterMeta->numOfColumns;
      for (int32_t j = 0; j < numOfTotalColumns; ++j) {
        tscSqlExprInsert(pCmd, j, TSDB_FUNC_PRJ, j, pSchema[j].type, pSchema[j].bytes);

        SColumnList ids = {.numOfCols = 1, .ids = {j}};
        insertResultField(pCmd, startPos + j, &ids, pSchema[j].bytes, pSchema[j].type, pSchema[j].name);
      }
    }

  } else if (pItem->pNode->nSQLOptr == TK_ID) {  // simple column projection query
    int32_t numOfAllCols = pCmd->pMeterMeta->numOfColumns + pCmd->pMeterMeta->numOfTags;
    int32_t idx = getColumnIndexByName(&pItem->pNode->colInfo, pSchema, numOfAllCols);
    if (idx == -1) {
      if (strncmp(pItem->pNode->colInfo.z, TSQL_TBNAME_L, 6) == 0 && pItem->pNode->colInfo.n == 6) {
        SSqlExpr* pExpr =
            tscSqlExprInsert(pCmd, startPos, TSDB_FUNC_TAGPRJ, -1, TSDB_DATA_TYPE_BINARY, TSDB_METER_NAME_LEN);

        SColumnList ids = {.numOfCols = 1, .ids = {idx}};
        insertResultField(pCmd, startPos, &ids, TSDB_METER_NAME_LEN, TSDB_DATA_TYPE_BINARY, TSQL_TBNAME_L);

        pCmd->metricQuery = 1;
        addRequiredTagColumn(pCmd, -1);
        pExpr->colInfo.isTag = true;
      } else {
1580 1581
        const char* msg = "invalid column name";
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
        return TSDB_CODE_INVALID_SQL;
      }
    } else {
      if (isMetric) {
        setProjExprForMetricQuery(pCmd, startPos, idx);
      } else {
        tscSqlExprInsert(pCmd, startPos, TSDB_FUNC_PRJ, idx, pSchema[idx].type, pSchema[idx].bytes);
      }

      char*       colName = (pItem->aliasName == NULL) ? pSchema[idx].name : pItem->aliasName;
      SColumnList ids = {.numOfCols = 1, .ids = {idx}};

      if (idx >= pCmd->pMeterMeta->numOfColumns || idx == -1) {
        ids.numOfCols = 0;
      }

      insertResultField(pCmd, startPos, &ids, pSchema[idx].bytes, pSchema[idx].type, colName);
    }
  } else {
    return TSDB_CODE_INVALID_SQL;
  }

  return TSDB_CODE_SUCCESS;
}

static int32_t setExprInfoForFunctions(SSqlCmd* pCmd, SSchema* pSchema, int32_t functionID, char* aliasName,
                                       int32_t resColIdx, int32_t idx) {
  int16_t type = 0;
  int16_t bytes = 0;

1612
  char columnName[TSDB_COL_NAME_LEN] = {0};
1613
  const char* msg1 = "not support column types";
H
hzcheng 已提交
1614 1615 1616 1617

  if (functionID == TSDB_FUNC_SPREAD) {
    if (pSchema[idx].type == TSDB_DATA_TYPE_BINARY || pSchema[idx].type == TSDB_DATA_TYPE_NCHAR ||
        pSchema[idx].type == TSDB_DATA_TYPE_BOOL) {
1618
      setErrMsg(pCmd, msg1);
H
hzcheng 已提交
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
      return -1;
    } else {
      type = TSDB_DATA_TYPE_DOUBLE;
      bytes = tDataTypeDesc[type].nSize;
    }
  } else {
    type = pSchema[idx].type;
    bytes = pSchema[idx].bytes;
  }

  if (aliasName != NULL) {
    strcpy(columnName, aliasName);
  } else {
    getRevisedName(columnName, functionID, TSDB_COL_NAME_LEN, pSchema[idx].name);
  }

  tscSqlExprInsert(pCmd, resColIdx, functionID, idx, type, bytes);

  /* for point interpolation/last_row query, we need the timestamp column to be
   * loaded */
  if (functionID == TSDB_FUNC_INTERP || functionID == TSDB_FUNC_LAST_ROW) {
    tscColumnInfoInsert(pCmd, PRIMARYKEY_TIMESTAMP_COL_INDEX);
  }

  SColumnList ids = {.numOfCols = 1, .ids = {idx}};
  insertResultField(pCmd, resColIdx, &ids, bytes, type, columnName);

  return TSDB_CODE_SUCCESS;
}

int32_t addExprAndResultField(SSqlCmd* pCmd, int32_t colIdx, tSQLExprItem* pItem) {
  int32_t  optr = pItem->pNode->nSQLOptr;
  SSchema* pSchema = tsGetSchema(pCmd->pMeterMeta);
  int32_t  numOfAddedColumn = 1;

1654 1655 1656 1657
  const char* msg = "invalid parameters";
  const char* msg1 = "not support column types";
  const char* msg3 = "illegal column name";
  const char* msg5 = "parameter is out of range [0, 100]";
H
hzcheng 已提交
1658 1659 1660 1661 1662

  switch (optr) {
    case TK_COUNT: {
      if (pItem->pNode->pParam != NULL && pItem->pNode->pParam->nExpr != 1) {
        /* more than one parameter for count() function */
1663
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676
        return -1;
      }

      int16_t functionID = 0;
      if (changeFunctionID(optr, &functionID) != TSDB_CODE_SUCCESS) {
        return -1;
      }

      int32_t columnId = 0;

      if (pItem->pNode->pParam != NULL) {
        SSQLToken* pToken = &pItem->pNode->pParam->a[0].pNode->colInfo;
        if (pToken->z == NULL || pToken->n == 0) {
1677
          setErrMsg(pCmd, msg3);
H
hzcheng 已提交
1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
          return -1;
        }

        /* count the number of meters created according to the metric */
        if (strncmp(pToken->z, "tbname", 6) == 0 && pToken->n == 6) {
          tscSqlExprInsert(pCmd, colIdx, functionID, -1, TSDB_DATA_TYPE_BIGINT,
                           tDataTypeDesc[TSDB_DATA_TYPE_BIGINT].nSize);
        } else {
          columnId = getColumnIndexByName(pToken, pSchema, pCmd->pMeterMeta->numOfColumns);
          if (columnId < 0) {  // invalid column name
1688
            setErrMsg(pCmd, msg3);
H
hzcheng 已提交
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
            return -1;
          }

          tscSqlExprInsert(pCmd, colIdx, functionID, columnId, TSDB_DATA_TYPE_BIGINT,
                           tDataTypeDesc[TSDB_DATA_TYPE_BIGINT].nSize);
        }
      } else {
        /* count(*) is equalled to count(primary_timestamp_key) */
        tscSqlExprInsert(pCmd, colIdx, functionID, PRIMARYKEY_TIMESTAMP_COL_INDEX, TSDB_DATA_TYPE_BIGINT,
                         tDataTypeDesc[TSDB_DATA_TYPE_BIGINT].nSize);
      }

      char columnName[TSDB_COL_NAME_LEN] = {0};
      getColumnName(pItem, columnName, TSDB_COL_NAME_LEN);

      // count always use the primary timestamp key column, which is 0.
      SColumnList ids = {.numOfCols = 1, .ids = {columnId}};
      insertResultField(pCmd, colIdx, &ids, sizeof(int64_t), TSDB_DATA_TYPE_BIGINT, columnName);
      return numOfAddedColumn;
    }
    case TK_SUM:
    case TK_AVG:
    case TK_WAVG:
    case TK_MIN:
    case TK_MAX:
    case TK_DIFF:
    case TK_STDDEV:
    case TK_LEASTSQUARES: {
      // 1. valid the number of parameters
      if (pItem->pNode->pParam == NULL || (optr != TK_LEASTSQUARES && pItem->pNode->pParam->nExpr != 1) ||
          (optr == TK_LEASTSQUARES && pItem->pNode->pParam->nExpr != 3)) {
        /* no parameters or more than one parameter for function */
1721
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
1722 1723 1724 1725 1726
        return -1;
      }

      tSQLExprItem* pParamElem = &(pItem->pNode->pParam->a[0]);
      if (pParamElem->pNode->nSQLOptr != TK_ALL && pParamElem->pNode->nSQLOptr != TK_ID) {
1727
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
1728 1729 1730 1731 1732
        return -1;
      }

      int32_t idx = getColumnIndexByName(&pParamElem->pNode->colInfo, pSchema, pCmd->pMeterMeta->numOfColumns);
      if (idx < 0) {  // invalid column name
1733
        setErrMsg(pCmd, msg3);
H
hzcheng 已提交
1734 1735 1736 1737 1738 1739
        return -1;
      }

      // 2. check if sql function can be applied on this column data type
      int16_t colType = pSchema[idx].type;
      if (colType == TSDB_DATA_TYPE_BOOL || colType >= TSDB_DATA_TYPE_BINARY) {
1740
        setErrMsg(pCmd, msg1);
H
hzcheng 已提交
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
        return -1;
      }

      char columnName[TSDB_COL_NAME_LEN] = {0};
      getColumnName(pItem, columnName, TSDB_COL_NAME_LEN);

      int16_t resultType = 0;
      int16_t resultSize = 0;

      int16_t functionID = 0;
      if (changeFunctionID(optr, &functionID) != TSDB_CODE_SUCCESS) {
        return -1;
      }

      getResultInfo(pSchema[idx].type, pSchema[idx].bytes, functionID, 0, &resultType, &resultSize);

      if (optr == TK_DIFF) {
        // set the first column ts for diff query
        colIdx += 1;
        tscSqlExprInsert(pCmd, 0, TSDB_FUNC_TS_DUMMY, 0, TSDB_DATA_TYPE_TIMESTAMP, TSDB_KEYSIZE);

        SColumnList ids = {.numOfCols = 1, .ids = {0}};
        insertResultField(pCmd, 0, &ids, TSDB_KEYSIZE, TSDB_DATA_TYPE_TIMESTAMP, aAggs[TSDB_FUNC_TS_DUMMY].aName);
      }

      SSqlExpr* pExpr = tscSqlExprInsert(pCmd, colIdx, functionID, idx, resultType, resultSize);

      if (optr == TK_LEASTSQUARES) {
        /* set the leastsquares parameters */
        char val[8] = {0};
        if (tVariantDump(&pParamElem[1].pNode->val, val, TSDB_DATA_TYPE_DOUBLE) < 0) {
          return TSDB_CODE_INVALID_SQL;
        }

        addExprParams(pExpr, val, TSDB_DATA_TYPE_DOUBLE, sizeof(double));

        memset(val, 0, tListLen(val));
        if (tVariantDump(&pParamElem[2].pNode->val, val, TSDB_DATA_TYPE_DOUBLE) < 0) {
          return TSDB_CODE_INVALID_SQL;
        }

        addExprParams(pExpr, val, TSDB_DATA_TYPE_DOUBLE, sizeof(double));
      }

      SColumnList ids = {.numOfCols = 1, .ids = {idx}};
      insertResultField(pCmd, colIdx, &ids, pExpr->resBytes, pExpr->resType, columnName);

      return numOfAddedColumn;
    }
    case TK_FIRST:
    case TK_LAST:
    case TK_SPREAD:
    case TK_LAST_ROW:
    case TK_INTERP: {
      bool requireAllFields = (pItem->pNode->pParam == NULL);

      int16_t functionID = 0;
      changeFunctionID(optr, &functionID);

      if (!requireAllFields) {
        if (pItem->pNode->pParam->nExpr < 1) {
1802
          setErrMsg(pCmd, msg3);
H
hzcheng 已提交
1803 1804 1805 1806 1807 1808 1809 1810
          return -1;
        }

        /* in first/last function, multiple columns can be add to resultset */

        for (int32_t i = 0; i < pItem->pNode->pParam->nExpr; ++i) {
          tSQLExprItem* pParamElem = &(pItem->pNode->pParam->a[i]);
          if (pParamElem->pNode->nSQLOptr != TK_ALL && pParamElem->pNode->nSQLOptr != TK_ID) {
1811
            setErrMsg(pCmd, msg3);
H
hzcheng 已提交
1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
            return -1;
          }

          int32_t idx = getColumnIndexByName(&pParamElem->pNode->colInfo, pSchema, pCmd->pMeterMeta->numOfColumns);
          if (idx == -1) {
            return -1;
          }

          if (setExprInfoForFunctions(pCmd, pSchema, functionID, pItem->aliasName, colIdx + i, idx) != 0) {
            return -1;
          }
        }

        return pItem->pNode->pParam->nExpr;
      } else {
        for (int32_t i = 0; i < pCmd->pMeterMeta->numOfColumns; ++i) {
          if (setExprInfoForFunctions(pCmd, pSchema, functionID, pItem->aliasName, colIdx + i, i) != 0) {
            return -1;
          }
        }

        return pCmd->pMeterMeta->numOfColumns;
      }
    }
    case TK_TOP:
    case TK_BOTTOM:
    case TK_PERCENTILE:
    case TK_APERCENTILE: {
      // 1. valid the number of parameters
      if (pItem->pNode->pParam == NULL || pItem->pNode->pParam->nExpr != 2) {
        /* no parameters or more than one parameter for function */
1843
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
1844 1845 1846 1847 1848
        return -1;
      }

      tSQLExprItem* pParamElem = &(pItem->pNode->pParam->a[0]);
      if (pParamElem->pNode->nSQLOptr != TK_ID) {
1849
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
      }

      char columnName[TSDB_COL_NAME_LEN] = {0};
      getColumnName(pItem, columnName, TSDB_COL_NAME_LEN);

      int32_t idx = getColumnIndexByName(&pParamElem->pNode->colInfo, pSchema, pCmd->pMeterMeta->numOfColumns);
      if (idx == -1) {
        return -1;
      }

      // 2. valid the column type
      int16_t colType = pSchema[idx].type;
      if (colType == TSDB_DATA_TYPE_BOOL || colType >= TSDB_DATA_TYPE_BINARY) {
1863
        setErrMsg(pCmd, msg1);
H
hzcheng 已提交
1864 1865 1866 1867 1868
        return -1;
      }

      // 3. valid the parameters
      if (pParamElem[1].pNode->nSQLOptr == TK_ID) {
1869
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
        return -1;
      }

      tVariant* pVariant = &pParamElem[1].pNode->val;

      int8_t  resultType = pSchema[idx].type;
      int16_t resultSize = pSchema[idx].bytes;

      char val[8] = {0};
      if (optr == TK_PERCENTILE || optr == TK_APERCENTILE) {
        tVariantDump(pVariant, val, TSDB_DATA_TYPE_DOUBLE);

        double dp = *((double*)val);
        if (dp < 0 || dp > 100) {  // todo use macro
1884
          setErrMsg(pCmd, msg5);
H
hzcheng 已提交
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039
          return -1;
        }

        resultSize = sizeof(double);
        resultType = TSDB_DATA_TYPE_DOUBLE;

        /*
         * sql function transformation
         * for dp = 0, it is actually min,
         * for dp = 100, it is max,
         */
        int16_t functionId = 0;
        if (changeFunctionID(optr, &functionId) != TSDB_CODE_SUCCESS) {
          return -1;
        }

        SSqlExpr* pExpr = tscSqlExprInsert(pCmd, colIdx, functionId, idx, resultType, resultSize);
        addExprParams(pExpr, val, TSDB_DATA_TYPE_DOUBLE, sizeof(double));
      } else {
        tVariantDump(pVariant, val, TSDB_DATA_TYPE_BIGINT);

        int64_t nTop = *((int32_t*)val);
        if (nTop <= 0 || nTop > 100) {  // todo use macro
          return -1;
        }

        int16_t functionId = 0;
        if (changeFunctionID(optr, &functionId) != TSDB_CODE_SUCCESS) {
          return -1;
        }
        // set the first column ts for top/bottom query
        tscSqlExprInsert(pCmd, 0, TSDB_FUNC_TS, 0, TSDB_DATA_TYPE_TIMESTAMP, TSDB_KEYSIZE);
        SColumnList ids = {.numOfCols = 1, .ids = {0}};
        insertResultField(pCmd, 0, &ids, TSDB_KEYSIZE, TSDB_DATA_TYPE_TIMESTAMP, aAggs[TSDB_FUNC_TS].aName);

        colIdx += 1;  // the first column is ts
        numOfAddedColumn += 1;

        SSqlExpr* pExpr = tscSqlExprInsert(pCmd, colIdx, functionId, idx, resultType, resultSize);
        addExprParams(pExpr, val, TSDB_DATA_TYPE_BIGINT, sizeof(int64_t));
      }

      SColumnList ids = {.numOfCols = 1, .ids = {idx}};
      insertResultField(pCmd, colIdx, &ids, resultSize, resultType, columnName);
      return numOfAddedColumn;
    }
    default:
      return -1;
  }
}

void getColumnName(tSQLExprItem* pItem, char* resultFieldName, int32_t nameLength) {
  if (pItem->aliasName != NULL) {
    strncpy(resultFieldName, pItem->aliasName, nameLength);
  } else {
    int32_t len = (pItem->pNode->operand.n < nameLength) ? pItem->pNode->operand.n : nameLength;
    strncpy(resultFieldName, pItem->pNode->operand.z, len);
  }
}

void getRevisedName(char* resultFieldName, int32_t functionId, int32_t maxLen, char* columnName) {
  snprintf(resultFieldName, maxLen, "%s(%s)", aAggs[functionId].aName, columnName);
}

int32_t getColumnIndexByName(SSQLToken* pToken, SSchema* pSchema, int32_t numOfCols) {
  if (pToken->z == NULL || pToken->n == 0) {
    return -1;
  }

  char* r = strnchr(pToken->z, '.', pToken->n);
  if (r != NULL) {
    r += 1;

    pToken->n -= (r - pToken->z);
    pToken->z = r;
  }
  if (strncasecmp(pToken->z, "_c0", pToken->n) == 0) return 0;

  for (int32_t i = 0; i < numOfCols; ++i) {
    if (pToken->n != strlen(pSchema[i].name)) continue;
    if (strncasecmp(pSchema[i].name, pToken->z, pToken->n) == 0) return i;
  }

  return -1;
}

int32_t changeFunctionID(int32_t optr, int16_t* functionId) {
  switch (optr) {
    case TK_COUNT:
      *functionId = TSDB_FUNC_COUNT;
      break;
    case TK_SUM:
      *functionId = TSDB_FUNC_SUM;
      break;
    case TK_AVG:
      *functionId = TSDB_FUNC_AVG;
      break;
    case TK_MIN:
      *functionId = TSDB_FUNC_MIN;
      break;
    case TK_MAX:
      *functionId = TSDB_FUNC_MAX;
      break;
    case TK_STDDEV:
      *functionId = TSDB_FUNC_STDDEV;
      break;
    case TK_PERCENTILE:
      *functionId = TSDB_FUNC_PERCT;
      break;
    case TK_APERCENTILE:
      *functionId = TSDB_FUNC_APERCT;
      break;
    case TK_FIRST:
      *functionId = TSDB_FUNC_FIRST;
      break;
    case TK_LAST:
      *functionId = TSDB_FUNC_LAST;
      break;
    case TK_LEASTSQUARES:
      *functionId = TSDB_FUNC_LEASTSQR;
      break;
    case TK_TOP:
      *functionId = TSDB_FUNC_TOP;
      break;
    case TK_BOTTOM:
      *functionId = TSDB_FUNC_BOTTOM;
      break;
    case TK_DIFF:
      *functionId = TSDB_FUNC_DIFF;
      break;
    case TK_SPREAD:
      *functionId = TSDB_FUNC_SPREAD;
      break;
    case TK_WAVG:
      *functionId = TSDB_FUNC_WAVG;
      break;
    case TK_INTERP:
      *functionId = TSDB_FUNC_INTERP;
      break;
    case TK_LAST_ROW:
      *functionId = TSDB_FUNC_LAST_ROW;
      break;
    default:
      return -1;
  }

  return TSDB_CODE_SUCCESS;
}

// TODO support like for showing metrics, there are show meters with like ops
int32_t setShowInfo(SSqlObj* pSql, struct SSqlInfo* pInfo) {
  SSqlCmd* pCmd = &pSql->cmd;
  pCmd->command = TSDB_SQL_SHOW;
  int8_t type = pInfo->sqlType;

2040 2041 2042
  const char* msg = "database name too long";
  const char* msg1 = "invalid database name";
  const char* msg2 = "pattern filter string too long";
H
hzcheng 已提交
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086

  switch (type) {
    case SHOW_VGROUPS:
      pCmd->type = TSDB_MGMT_TABLE_VGROUP;
      break;
    case SHOW_TABLES:
      pCmd->type = TSDB_MGMT_TABLE_TABLE;
      break;
    case SHOW_STABLES:
      pCmd->type = TSDB_MGMT_TABLE_METRIC;
      break;

    case SHOW_DATABASES:
      pCmd->type = TSDB_MGMT_TABLE_DB;
      break;
    case SHOW_DNODES:
      pCmd->type = TSDB_MGMT_TABLE_PNODE;
      break;
    case SHOW_USERS:
      pCmd->type = TSDB_MGMT_TABLE_USER;
      break;
    case SHOW_CONNECTIONS:
      pCmd->type = TSDB_MGMT_TABLE_CONNS;
      break;
    case SHOW_QUERIES:
      pCmd->type = TSDB_MGMT_TABLE_QUERIES;
      break;
    case SHOW_STREAMS:
      pCmd->type = TSDB_MGMT_TABLE_STREAMS;
      break;
    default:
      return TSDB_CODE_INVALID_SQL;
  }

  /*
   * database prefix in pInfo->pDCLInfo->a[0]
   * wildcard in like clause in pInfo->pDCLInfo->a[1]
   */
  if (type == SHOW_TABLES || type == SHOW_STABLES || type == SHOW_VGROUPS) {
    // db prefix in tagCond, show table conds in payload
    if (pInfo->pDCLInfo->nTokens > 0) {
      SSQLToken* pDbPrefixToken = &pInfo->pDCLInfo->a[0];

      if (pDbPrefixToken->n > TSDB_DB_NAME_LEN) {  // db name is too long
2087
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
2088 2089 2090 2091
        return TSDB_CODE_INVALID_SQL;
      }

      if (pDbPrefixToken->n > 0 && tscValidateName(pDbPrefixToken) != TSDB_CODE_SUCCESS) {
2092
        setErrMsg(pCmd, msg1);
H
hzcheng 已提交
2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
        return TSDB_CODE_INVALID_SQL;
      }

      int32_t ret = 0;
      if (pDbPrefixToken->n > 0) {  // has db prefix
        if (pCmd->tagCond.allocSize < TSDB_MAX_TAGS_LEN) {
          pCmd->tagCond.pData = realloc(pCmd->tagCond.pData, TSDB_MAX_TAGS_LEN);
          pCmd->tagCond.allocSize = TSDB_MAX_TAGS_LEN;
        }
        ret = setObjFullName(pCmd->tagCond.pData, getAccountId(pSql), pDbPrefixToken, NULL, &pCmd->tagCond.len);
      } else {
        ret = setObjFullName(pCmd->name, getAccountId(pSql), NULL, NULL, NULL);
      }

      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }

      if (type != SHOW_VGROUPS && pInfo->pDCLInfo->nTokens == 2) {
        // set the like conds for show tables
        SSQLToken* likeToken = &pInfo->pDCLInfo->a[1];
        strncpy(pCmd->payload, likeToken->z, likeToken->n);
        strdequote(pCmd->payload);
        pCmd->payloadLen = strlen(pCmd->payload);

        if (pCmd->payloadLen > TSDB_METER_NAME_LEN) {
2119
          setErrMsg(pCmd, msg2);
H
hzcheng 已提交
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159
          return TSDB_CODE_INVALID_SQL;  // wildcard is too long
        }
      }
    }
  }

  return TSDB_CODE_SUCCESS;
}

int32_t setKillInfo(SSqlObj* pSql, struct SSqlInfo* pInfo) {
  SSqlCmd* pCmd = &pSql->cmd;

  switch (pInfo->sqlType) {
    case KILL_QUERY:
      pCmd->command = TSDB_SQL_KILL_QUERY;
      break;
    case KILL_STREAM:
      pCmd->command = TSDB_SQL_KILL_STREAM;
      break;
    case KILL_CONNECTION:
      pCmd->command = TSDB_SQL_KILL_CONNECTION;
      break;
    default:
      return TSDB_CODE_INVALID_SQL;
  }

  SSQLToken* pToken = &(pInfo->pDCLInfo->a[0]);
  if (pToken->n > TSDB_KILL_MSG_LEN) {
    return TSDB_CODE_INVALID_SQL;
  }

  strncpy(pCmd->payload, pToken->z, pToken->n);

  const char delim = ':';
  char*      ipStr = strtok(pToken->z, &delim);
  char*      portStr = strtok(NULL, &delim);

  if (!validateIpAddress(ipStr)) {
    memset(pCmd->payload, 0, tListLen(pCmd->payload));

2160 2161
    const char* msg = "invalid ip address";
    setErrMsg(pCmd, msg);
H
hzcheng 已提交
2162 2163 2164 2165 2166 2167 2168
    return TSDB_CODE_INVALID_SQL;
  }

  int32_t port = strtol(portStr, NULL, 10);
  if (port <= 0 || port > 65535) {
    memset(pCmd->payload, 0, tListLen(pCmd->payload));

2169 2170
    const char* msg = "invalid port";
    setErrMsg(pCmd, msg);
H
hzcheng 已提交
2171 2172 2173 2174 2175 2176
    return TSDB_CODE_INVALID_SQL;
  }

  return TSDB_CODE_SUCCESS;
}

2177 2178 2179
void setErrMsg(SSqlCmd* pCmd, const char* pzErrMsg) {
  strncpy(pCmd->payload, pzErrMsg, pCmd->allocSize);
  pCmd->payload[pCmd->allocSize - 1] = 0;
H
hzcheng 已提交
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306
}

bool validateIpAddress(char* ip) {
  in_addr_t ipAddr = inet_addr(ip);
  return (ipAddr != 0) && (ipAddr != 0xffffffff);
}

void tscTansformSQLFunctionForMetricQuery(SSqlCmd* pCmd) {
  if (pCmd->pMeterMeta == NULL || !UTIL_METER_IS_METRIC(pCmd)) {
    return;
  }

  assert(pCmd->pMeterMeta->numOfTags >= 0);

  int16_t bytes = 0;
  int16_t type = 0;

  for (int32_t k = 0; k < pCmd->fieldsInfo.numOfOutputCols; ++k) {
    SSqlExpr*   pExpr = tscSqlExprGet(pCmd, k);
    TAOS_FIELD* pField = tscFieldInfoGetField(pCmd, k);

    int16_t functionId = aAggs[pExpr->sqlFuncId].stableFuncId;

    if (functionId >= TSDB_FUNC_SUM_DST && functionId <= TSDB_FUNC_APERCT_DST) {
      getResultInfo(pField->type, pField->bytes, functionId, pExpr->param[0].i64Key, &type, &bytes);
      tscSqlExprUpdate(pCmd, k, functionId, pExpr->colInfo.colIdx, TSDB_DATA_TYPE_BINARY, bytes);
    }
  }

  tscFieldInfoRenewOffsetForInterResult(pCmd);
}

/* transfer the field-info back to original input format */
void tscRestoreSQLFunctionForMetricQuery(SSqlCmd* pCmd) {
  if (!UTIL_METER_IS_METRIC(pCmd)) {
    return;
  }

  for (int32_t i = 0; i < pCmd->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr*   pExpr = tscSqlExprGet(pCmd, i);
    TAOS_FIELD* pField = tscFieldInfoGetField(pCmd, i);

    if (pExpr->sqlFuncId >= TSDB_FUNC_SUM_DST && pExpr->sqlFuncId <= TSDB_FUNC_WAVG_DST) {
      pExpr->resBytes = pField->bytes;
      pExpr->resType = pField->type;
    }
  }
}

bool onlyQueryMetricTags(SSqlCmd* pCmd) {
  assert(pCmd->metricQuery == 1);

  for (int32_t i = 0; i < pCmd->fieldsInfo.numOfOutputCols; ++i) {
    if (tscSqlExprGet(pCmd, i)->sqlFuncId != TSDB_FUNC_TAGPRJ) {  // 18 == "tagprj" function
      return false;
    }
  }

  return true;
}

bool hasUnsupportFunctionsForMetricQuery(SSqlCmd* pCmd) {
  // filter sql function not supported by metric query yet.
  for (int32_t i = 0; i < pCmd->fieldsInfo.numOfOutputCols; ++i) {
    int32_t functionId = tscSqlExprGet(pCmd, i)->sqlFuncId;
    if ((aAggs[functionId].nStatus & TSDB_FUNCSTATE_METRIC) == 0) {
      return true;
    }
  }
  return false;
}

static bool functionCompatibleCheck(SSqlCmd* pCmd) {
  int32_t startIdx = 0;
  int32_t functionID = tscSqlExprGet(pCmd, startIdx)->sqlFuncId;
  if (functionID == TSDB_FUNC_TS || functionID == TSDB_FUNC_TS_DUMMY) {
    startIdx++;  // ts function can be simultaneously used with any other
                 // functions.
  }

  int32_t nRetCount = funcCompatList[tscSqlExprGet(pCmd, startIdx)->sqlFuncId];

  // diff function cannot be executed with other function
  // arithmetic function can be executed with other arithmetic functions
  for (int32_t i = startIdx + 1; i < pCmd->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pCmd, i);
    if (funcCompatList[pExpr->sqlFuncId] != nRetCount) {
      return false;
    }
  }

  return true;
}

void updateTagColumnIndex(SSqlCmd* pCmd) {
  // update tags column index for group by tags
  for (int32_t i = 0; i < pCmd->groupbyExpr.numOfGroupbyCols; ++i) {
    int32_t index = pCmd->groupbyExpr.tagIndex[i];

    for (int32_t j = 0; j < pCmd->numOfReqTags; ++j) {
      int32_t tagColIndex = pCmd->tagColumnIndex[j];
      if (tagColIndex == index) {
        pCmd->groupbyExpr.tagIndex[i] = j;
        break;
      }
    }
  }

  // update tags column index for expression
  for (int32_t i = 0; i < pCmd->exprsInfo.numOfExprs; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pCmd, i);

    // not tags, continue
    if (!pExpr->colInfo.isTag) {
      continue;
    }

    for (int32_t j = 0; j < pCmd->numOfReqTags; ++j) {
      if (pExpr->colInfo.colIdx == pCmd->tagColumnIndex[j]) {
        pExpr->colInfo.colIdx = j;
        break;
      }
    }
  }
}

int32_t setGroupByClause(SSqlCmd* pCmd, tVariantList* pList) {
2307 2308 2309 2310
  const char* msg1 = "too many columns in group by clause";
  const char* msg2 = "invalid column name in group by clause";
  const char* msg3 = "functions are not available in group by query";
  const char* msg4 = "group by only available for STable query";
H
hzcheng 已提交
2311 2312 2313 2314 2315

  if (UTIL_METER_IS_NOMRAL_METER(pCmd)) {
    if (pList == NULL) {
      return TSDB_CODE_SUCCESS;
    } else {
2316
      setErrMsg(pCmd, msg4);
H
hzcheng 已提交
2317 2318 2319 2320 2321 2322 2323 2324 2325 2326
      return TSDB_CODE_INVALID_SQL;
    }
  }

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

  pCmd->groupbyExpr.numOfGroupbyCols = pList->nExpr;
  if (pList->nExpr > TSDB_MAX_TAGS) {
2327
    setErrMsg(pCmd, msg1);
H
hzcheng 已提交
2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
    return TSDB_CODE_INVALID_SQL;
  }

  SMeterMeta* pMeterMeta = pCmd->pMeterMeta;
  SSchema*    pSchema = tsGetSchema(pMeterMeta);

  int32_t numOfReqTags = 0;

  for (int32_t i = 0; i < pList->nExpr; ++i) {
    tVariant* pVar = &pList->a[i].pVar;
    SSQLToken token = {pVar->nLen, pVar->nType, pVar->pz};

    int32_t colIdx = 0;
    int16_t type = 0;
    int16_t bytes = 0;
    char*   name = NULL;

    /* group by tbname*/
    if (strncasecmp(pVar->pz, TSQL_TBNAME_L, pVar->nLen) == 0) {
      colIdx = -1;
      type = TSDB_DATA_TYPE_BINARY;
      bytes = TSDB_METER_NAME_LEN;
      name = TSQL_TBNAME_L;
    } else {
      colIdx = getColumnIndexByName(&token, pSchema, pMeterMeta->numOfTags + pMeterMeta->numOfColumns);
      if (colIdx < pMeterMeta->numOfColumns || colIdx > TSDB_MAX_TAGS + pMeterMeta->numOfColumns) {
2354
        setErrMsg(pCmd, msg2);
H
hzcheng 已提交
2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391
        return TSDB_CODE_INVALID_SQL;
      }

      type = pSchema[colIdx].type;
      bytes = pSchema[colIdx].bytes;
      name = pSchema[colIdx].name;
      numOfReqTags++;
    }

    SSqlExpr* pExpr = tscSqlExprInsert(pCmd, pCmd->fieldsInfo.numOfOutputCols, TSDB_FUNC_TAG, colIdx, type, bytes);
    pExpr->colInfo.isTag = true;

    // NOTE: tag column does not add to source column list
    SColumnList ids = {0};
    insertResultField(pCmd, pCmd->fieldsInfo.numOfOutputCols, &ids, bytes, type, name);

    int32_t relIndex = 0;
    if (colIdx != -1) {
      relIndex = colIdx - pMeterMeta->numOfColumns;
    } else {  // tbname
      relIndex = colIdx;
    }

    pExpr->colInfo.colIdx = relIndex;
    pCmd->groupbyExpr.tagIndex[i] = relIndex;

    assert(pCmd->groupbyExpr.tagIndex[i] >= -1);
    addRequiredTagColumn(pCmd, pCmd->groupbyExpr.tagIndex[i]);
  }

  /*
   * check all query functions in selection clause, multi-output functions are not available in query function
   */
  for (int32_t i = 0; i < pCmd->fieldsInfo.numOfOutputCols; ++i) {
    int32_t functId = tscSqlExprGet(pCmd, i)->sqlFuncId;
    if (IS_MULTIOUTPUT(aAggs[functId].nStatus) && functId != TSDB_FUNC_TOP_DST && functId != TSDB_FUNC_BOTTOM_DST &&
        functId != TSDB_FUNC_TOP && functId != TSDB_FUNC_BOTTOM) {
2392
      setErrMsg(pCmd, msg3);
H
hzcheng 已提交
2393 2394 2395 2396
      return TSDB_CODE_INVALID_SQL;
    }

    if (functId == TSDB_FUNC_COUNT && tscSqlExprGet(pCmd, i)->colInfo.colIdx == -1) {
2397
      setErrMsg(pCmd, msg3);
H
hzcheng 已提交
2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
      return TSDB_CODE_INVALID_SQL;
    }
  }

  return TSDB_CODE_SUCCESS;
}

void setColumnOffsetValueInResultset(SSqlCmd* pCmd) {
  if (pCmd->metricQuery == 0) {
    tscFieldInfoCalOffset(pCmd);
  } else {
    tscFieldInfoRenewOffsetForInterResult(pCmd);
  }
}

static void setColumnFilterInfo(SSqlCmd* pCmd, SColumnBase* pColFilter, int32_t colIdx, tSQLExpr* pExpr) {
  tSQLExpr* pRight = pExpr->pRight;
  SSchema*  pSchema = tsGetSchema(pCmd->pMeterMeta);

  pColFilter->filterOn = 1;

  pColFilter->colIndex = colIdx;

  int16_t colType = pSchema[colIdx].type;
  if ((colType >= TSDB_DATA_TYPE_TINYINT && colType <= TSDB_DATA_TYPE_BIGINT) || colType == TSDB_DATA_TYPE_TIMESTAMP) {
    colType = TSDB_DATA_TYPE_BIGINT;
  } else if (colType == TSDB_DATA_TYPE_FLOAT || colType == TSDB_DATA_TYPE_DOUBLE) {
    colType = TSDB_DATA_TYPE_DOUBLE;
  }

  if (pExpr->nSQLOptr == TK_LE || pExpr->nSQLOptr == TK_LT) {
    tVariantDump(&pRight->val, (char*)&pColFilter->upperBndd, colType);
  } else {  // TK_GT,TK_GE,TK_EQ,TK_NE are based on the pColFilter->lowerBndd
    if (colType == TSDB_DATA_TYPE_BINARY) {
      pColFilter->pz = (int64_t)malloc(pRight->val.nLen + 1);
      pColFilter->len = pRight->val.nLen;

      tVariantDump(&pRight->val, (char*)pColFilter->pz, colType);
      ((char*)pColFilter->pz)[pColFilter->len] = 0;
    } else {
      tVariantDump(&pRight->val, (char*)&pColFilter->lowerBndd, colType);
    }
  }

  switch (pExpr->nSQLOptr) {
    case TK_LE:
      pColFilter->upperRelOptr = TSDB_RELATION_LESS_EQUAL;
      break;
    case TK_LT:
      pColFilter->upperRelOptr = TSDB_RELATION_LESS;
      break;
    case TK_GT:
      pColFilter->lowerRelOptr = TSDB_RELATION_LARGE;
      break;
    case TK_GE:
      pColFilter->lowerRelOptr = TSDB_RELATION_LARGE_EQUAL;
      break;
    case TK_EQ:
      pColFilter->lowerRelOptr = TSDB_RELATION_EQUAL;
      break;
    case TK_NE:
      pColFilter->lowerRelOptr = TSDB_RELATION_NOT_EQUAL;
      break;
    case TK_LIKE:
      pColFilter->lowerRelOptr = TSDB_RELATION_LIKE;
      break;
  }
}

static int32_t getTimeRange(int64_t* stime, int64_t* etime, tSQLExpr* pRight, int32_t optr, int16_t precision);

static int32_t exprToString(tSQLExpr* pExpr, char** exprString, SColumnIdList* pIdList) {
  if (pExpr->nSQLOptr == TK_ID) {  // column name
    strncpy(*exprString, pExpr->colInfo.z, pExpr->colInfo.n);
    *exprString += pExpr->colInfo.n;

    if (pIdList) {
      bool validColumn = false;
      // record and check the column name
      for (int32_t i = 0; i < pIdList->numOfCols; ++i) {
        int32_t len = strlen(pIdList->pSchema[i].name);

        if (pExpr->colInfo.n == len && strncasecmp(pExpr->colInfo.z, pIdList->pSchema[i].name, len) == 0) {
          pIdList->ids[pIdList->numOfRecordedCols++] = (int16_t)i;
          validColumn = true;
          break;
        }
      }

      if (!validColumn) {
        return TSDB_CODE_INVALID_SQL;
      }
    }
  } else if (pExpr->nSQLOptr >= TK_BOOL && pExpr->nSQLOptr <= TK_STRING) {  // value
    *exprString += tVariantToString(&pExpr->val, *exprString);
  } else {
    return TSDB_CODE_INVALID_SQL;
  }

  return TSDB_CODE_SUCCESS;
}

static int32_t optrToString(tSQLExpr* pExpr, char** exprString) {
  char le[] = "<=";
  char ge[] = ">=";
  char ne[] = "<>";
  char likeOptr[] = "LIKE";

  switch (pExpr->nSQLOptr) {
    case TK_LE: {
      *(int16_t*)(*exprString) = *(int16_t*)le;
      *exprString += 1;
      break;
    }
    case TK_GE: {
      *(int16_t*)(*exprString) = *(int16_t*)ge;
      *exprString += 1;
      break;
    }
    case TK_NE: {
      *(int16_t*)(*exprString) = *(int16_t*)ne;
      *exprString += 1;
      break;
    }

    case TK_LT:
      *(*exprString) = '<';
      break;
    case TK_GT:
      *(*exprString) = '>';
      break;
    case TK_EQ:
      *(*exprString) = '=';
      break;
    case TK_PLUS:
      *(*exprString) = '+';
      break;
    case TK_MINUS:
      *(*exprString) = '-';
      break;
    case TK_STAR:
      *(*exprString) = '*';
      break;
    case TK_DIVIDE:
      *(*exprString) = '/';
      break;
    case TK_REM:
      *(*exprString) = '%';
      break;
    case TK_LIKE: {
      int32_t len = sprintf(*exprString, " %s ", likeOptr);
      *exprString += (len - 1);
      break;
    }
    default:
      return TSDB_CODE_INVALID_SQL;
  }

  *exprString += 1;

  return TSDB_CODE_SUCCESS;
}

static int32_t createTableNameList(tSQLExpr* pExpr, char** queryStr) {
  tSQLExprList* pList = pExpr->pParam;
  if (pList->nExpr <= 0) {
    return TSDB_CODE_INVALID_SQL;
  }

  int32_t len = 0;
  for (int32_t i = 0; i < pList->nExpr; ++i) {
    tSQLExpr* pSub = pList->a[i].pNode;
    strncpy(*queryStr + len, pSub->val.pz, pSub->val.nLen);

    len += pSub->val.nLen;
    (*queryStr)[len++] = ',';

    if (pSub->val.nLen <= 0 || pSub->val.nLen > TSDB_METER_NAME_LEN) {
      return TSDB_CODE_INVALID_SQL;
    }
  }

  *queryStr += len;

  return TSDB_CODE_SUCCESS;
}

static bool isTbnameToken(SSQLToken* token) {
  return (strncasecmp(TSQL_TBNAME_L, token->z, token->n) == 0 && token->n == strlen(TSQL_TBNAME_L));
}

static int32_t buildTagQueryCondString(SSqlCmd* pCmd, tSQLExpr* pExpr, char** queryStr) {
  tSQLExpr* pLeft = pExpr->pLeft;
  tSQLExpr* pRight = pExpr->pRight;

2593 2594 2595
  const char* msg0 = "invalid table name list";
  const char* msg1 = "like operation is not allowed on numeric tags";
  const char* msg2 = "in and query condition cannot be mixed up";
H
hzcheng 已提交
2596 2597 2598 2599 2600
  STagCond* pCond = &pCmd->tagCond;

  if (pExpr->nSQLOptr == TK_IN && pRight->nSQLOptr == TK_SET) {
    /* table name array list, invoke another routine */
    if (pCond->type == TSQL_STABLE_QTYPE_COND) {
2601
      setErrMsg(pCmd, msg2);
H
hzcheng 已提交
2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612
      return TSDB_CODE_INVALID_SQL;
    }

    pCond->type = TSQL_STABLE_QTYPE_SET;

    if (!isTbnameToken(&pLeft->colInfo)) {
      return TSDB_CODE_INVALID_SQL;
    }

    int32_t ret = createTableNameList(pRight, queryStr);
    if (ret != TSDB_CODE_SUCCESS) {
2613
      setErrMsg(pCmd, msg0);
H
hzcheng 已提交
2614 2615 2616 2617 2618 2619
    }
    return ret;
  }

  // already use IN predicates
  if (pCond->type == TSQL_STABLE_QTYPE_SET) {
2620
    setErrMsg(pCmd, msg2);
H
hzcheng 已提交
2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
    return TSDB_CODE_INVALID_SQL;
  } else {
    pCond->type = TSQL_STABLE_QTYPE_COND;
  }

  *(*queryStr) = '(';
  *queryStr += 1;

  exprToString(pLeft, queryStr, NULL);
  if (optrToString(pExpr, queryStr) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_INVALID_SQL;
  }

  /* pattern string is too long */
  if (pExpr->nSQLOptr == TK_LIKE) {
    if (pRight->val.nLen > TSDB_PATTERN_STRING_MAX_LEN) {
      return TSDB_CODE_INVALID_SQL;
    }

    SSchema* pSchema = tsGetSchema(pCmd->pMeterMeta);

    int32_t numOfCols = pCmd->pMeterMeta->numOfColumns;
    int32_t numOfTags = pCmd->pMeterMeta->numOfTags;

    int32_t colIdx = getColumnIndexByName(&pLeft->colInfo, pSchema, numOfCols + numOfTags);
    if ((!isTbnameToken(&pLeft->colInfo)) && pSchema[colIdx].type != TSDB_DATA_TYPE_BINARY &&
        pSchema[colIdx].type != TSDB_DATA_TYPE_NCHAR) {
2648
      setErrMsg(pCmd, msg1);
H
hzcheng 已提交
2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781
      return TSDB_CODE_INVALID_SQL;
    }
  }

  exprToString(pRight, queryStr, NULL);

  *(*queryStr) = ')';
  *queryStr += 1;

  return TSDB_CODE_SUCCESS;
}

// todo error handle / such as and /or mixed with +/-/*/
int32_t buildArithmeticExprString(tSQLExpr* pExpr, char** exprString, SColumnIdList* colIdList) {
  tSQLExpr* pLeft = pExpr->pLeft;
  tSQLExpr* pRight = pExpr->pRight;

  *(*exprString) = '(';
  *exprString += 1;

  if (pLeft->nSQLOptr >= TK_PLUS && pLeft->nSQLOptr <= TK_REM) {
    buildArithmeticExprString(pLeft, exprString, colIdList);
  } else {
    int32_t ret = exprToString(pLeft, exprString, colIdList);
    if (ret != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_INVALID_SQL;
    }
  }

  optrToString(pExpr, exprString);

  if (pRight->nSQLOptr >= TK_PLUS && pRight->nSQLOptr <= TK_REM) {
    buildArithmeticExprString(pRight, exprString, colIdList);
  } else {
    int32_t ret = exprToString(pRight, exprString, colIdList);
    if (ret != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_INVALID_SQL;
    }
  }

  *(*exprString) = ')';
  *exprString += 1;

  return TSDB_CODE_SUCCESS;
}

static int32_t validateSQLExpr(tSQLExpr* pExpr, SSchema* pSchema, int32_t numOfCols) {
  if (pExpr->nSQLOptr == TK_ID) {
    bool validColumnName = false;
    for (int32_t i = 0; i < numOfCols; ++i) {
      if (strncasecmp(pExpr->colInfo.z, pSchema[i].name, pExpr->colInfo.n) == 0 &&
          pExpr->colInfo.n == strlen(pSchema[i].name)) {
        if (pSchema[i].type < TSDB_DATA_TYPE_TINYINT || pSchema[i].type > TSDB_DATA_TYPE_DOUBLE) {
          return TSDB_CODE_INVALID_SQL;
        }
        validColumnName = true;
      }
    }

    if (!validColumnName) {
      return TSDB_CODE_INVALID_SQL;
    }

  } else if (pExpr->nSQLOptr == TK_FLOAT && (isnan(pExpr->val.dKey) || isinf(pExpr->val.dKey))) {
    return TSDB_CODE_INVALID_SQL;
  }

  return TSDB_CODE_SUCCESS;
}

static int32_t validateArithmeticSQLExpr(tSQLExpr* pExpr, SSchema* pSchema, int32_t numOfCols) {
  if (pExpr == NULL) {
    return TSDB_CODE_SUCCESS;
  }

  tSQLExpr* pLeft = pExpr->pLeft;
  if (pLeft->nSQLOptr >= TK_PLUS && pLeft->nSQLOptr <= TK_REM) {
    int32_t ret = validateArithmeticSQLExpr(pLeft, pSchema, numOfCols);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
  } else {
    int32_t ret = validateSQLExpr(pLeft, pSchema, numOfCols);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
  }

  tSQLExpr* pRight = pExpr->pRight;
  if (pRight->nSQLOptr >= TK_PLUS && pRight->nSQLOptr <= TK_REM) {
    int32_t ret = validateArithmeticSQLExpr(pRight, pSchema, numOfCols);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
  } else {
    int32_t ret = validateSQLExpr(pRight, pSchema, numOfCols);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
  }

  return TSDB_CODE_SUCCESS;
}

static bool isValidExpr(tSQLExpr* pLeft, tSQLExpr* pRight, int32_t optr) {
  if (pLeft == NULL || (pRight == NULL && optr != TK_IN)) {
    return false;
  }

  /*
   * filter illegal expression in where clause:
   * 1. columnA = columnB
   * 2. count(*) > 12
   * 3. sum(columnA) > sum(columnB)
   * 4. 4 < 5,  'ABC'>'abc'
   *
   * However, columnA < 4+12 is valid
   */
  if ((pLeft->nSQLOptr == TK_ID && pRight->nSQLOptr == TK_ID) ||
      (pLeft->nSQLOptr >= TK_COUNT && pLeft->nSQLOptr <= TK_WAVG) ||
      (pRight->nSQLOptr >= TK_COUNT && pRight->nSQLOptr <= TK_WAVG) ||
      (pLeft->nSQLOptr >= TK_BOOL && pLeft->nSQLOptr <= TK_BINARY && pRight->nSQLOptr >= TK_BOOL &&
       pRight->nSQLOptr <= TK_BINARY)) {
    return false;
  }

  return true;
}

static int32_t getColumnFilterInfo(SSqlCmd* pCmd, int32_t colIdx, tSQLExpr* pExpr) {
  SMeterMeta* pMeterMeta = pCmd->pMeterMeta;
  SSchema*    pSchema = tsGetSchema(pMeterMeta);

2782 2783 2784 2785
  const char* msg = "nchar column not available for filter";
  const char* msg1 = "non binary column not support like operator";
  const char* msg2 = "binary column not support this operator";
  const char* msg3 = "column not support in operator";
H
hzcheng 已提交
2786 2787

  if (pSchema[colIdx].type == TSDB_DATA_TYPE_NCHAR) {
2788
    setErrMsg(pCmd, msg);
H
hzcheng 已提交
2789 2790 2791 2792
    return -1;
  }

  if (pExpr->nSQLOptr == TK_IN) {
2793
    setErrMsg(pCmd, msg3);
H
hzcheng 已提交
2794 2795 2796 2797 2798 2799 2800 2801 2802
    return -1;
  }

  SColumnBase* pColFilter = tscColumnInfoInsert(pCmd, colIdx);

  pColFilter->filterOnBinary = ((pSchema[colIdx].type == TSDB_DATA_TYPE_BINARY) ? 1 : 0);

  if (pColFilter->filterOnBinary) {
    if (pExpr->nSQLOptr != TK_EQ && pExpr->nSQLOptr != TK_NE && pExpr->nSQLOptr != TK_LIKE) {
2803
      setErrMsg(pCmd, msg2);
H
hzcheng 已提交
2804 2805 2806 2807
      return TSDB_CODE_INVALID_SQL;
    }
  } else {
    if (pExpr->nSQLOptr == TK_LIKE) {
2808
      setErrMsg(pCmd, msg1);
H
hzcheng 已提交
2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827
      return TSDB_CODE_INVALID_SQL;
    }
  }

  setColumnFilterInfo(pCmd, pColFilter, colIdx, pExpr);
  return TSDB_CODE_SUCCESS;
}

static int32_t handleExprInQueryCond(SSqlCmd* pCmd, bool* queryTimeRangeIsSet, char** queryStr, int64_t* stime,
                                     int64_t* etime, tSQLExpr* pExpr) {
  tSQLExpr* pLeft = pExpr->pLeft;
  tSQLExpr* pRight = pExpr->pRight;

  SMeterMeta* pMeterMeta = pCmd->pMeterMeta;
  SSchema*    pSchema = tsGetSchema(pMeterMeta);

  int32_t numOfCols = pMeterMeta->numOfColumns;
  int32_t numOfTags = pMeterMeta->numOfTags;

2828 2829 2830
  const char* msg = "meter query cannot use tags filter";
  const char* msg1 = "illegal column name";
  const char* msg2 = "invalid timestamp";
H
hzcheng 已提交
2831 2832 2833 2834 2835

  int32_t colIdx = getColumnIndexByName(&pLeft->colInfo, pSchema, numOfCols + numOfTags);
  bool    istbname = isTbnameToken(&pLeft->colInfo);

  if (colIdx < 0 && (!istbname)) {
2836
    setErrMsg(pCmd, msg1);
H
hzcheng 已提交
2837 2838 2839 2840 2841 2842
    return TSDB_CODE_INVALID_SQL;
  }

  if (colIdx == 0) {  // query on time range
    *queryTimeRangeIsSet = true;
    if (getTimeRange(stime, etime, pRight, pExpr->nSQLOptr, pMeterMeta->precision) != TSDB_CODE_SUCCESS) {
2843
      setErrMsg(pCmd, msg2);
H
hzcheng 已提交
2844 2845 2846 2847
      return TSDB_CODE_INVALID_SQL;
    }
  } else if (colIdx >= numOfCols || istbname) {  // query on tags
    if (UTIL_METER_IS_NOMRAL_METER(pCmd)) {
2848
      setErrMsg(pCmd, msg);
H
hzcheng 已提交
2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939
      return TSDB_CODE_INVALID_SQL;
    }
    return buildTagQueryCondString(pCmd, pExpr, queryStr);
  } else {  // query on other columns
    return getColumnFilterInfo(pCmd, colIdx, pExpr);
  }

  return TSDB_CODE_SUCCESS;
}

static void insertLeftParentheses(char** queryStr, char* p) {
  int32_t len = (*queryStr - p);
  memmove(p + 1, p, len);
  p[0] = '(';
  *queryStr += 1;
}

static void removeLeftParentheses(char** queryStr, char* p) {
  // remove the left parentheses
  memmove(p, p + 1, *queryStr - p - 1);
  *queryStr -= 1;
}

int32_t getQueryCondExprImpl(SSqlCmd* pCmd, tSQLExpr* pExpr, int64_t* stime, int64_t* etime, bool* queryTimeRangeIsSet,
                             char** queryStr) {
  if (pExpr == NULL) {
    return TSDB_CODE_SUCCESS;
  }

  tSQLExpr* pLeft = pExpr->pLeft;
  tSQLExpr* pRight = pExpr->pRight;

  if (!isValidExpr(pLeft, pRight, pExpr->nSQLOptr)) {
    return TSDB_CODE_INVALID_SQL;
  }

  if (pExpr->nSQLOptr == TK_AND || pExpr->nSQLOptr == TK_OR) {
    int64_t stime1 = 0, etime1 = INT64_MAX;
    bool    tmRangeIsSet = false;

    char*   p = *queryStr;
    int32_t ret = getQueryCondExprImpl(pCmd, pExpr->pLeft, &stime1, &etime1, &tmRangeIsSet, queryStr);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }

    if (tmRangeIsSet) {
      *stime = stime1;
      *etime = etime1;

      *queryTimeRangeIsSet = true;
    }

    if (p == *queryStr) {
      /*
       * query on timestamp or filter on normal columns
       * no data serialize to string
       *
       * do nothing
       */
    } else {  // serialize relational operator for tag filter operation
      if (pCmd->tagCond.type == TSQL_STABLE_QTYPE_SET) {
        /* using id in clause, and/or is not needed */

      } else {
        assert(pCmd->tagCond.type == TSQL_STABLE_QTYPE_COND);
        insertLeftParentheses(queryStr, p);

        char*   optr = (pExpr->nSQLOptr == TK_AND) ? "and" : "or";
        int32_t len = (pExpr->nSQLOptr == TK_AND) ? 3 : 2;
        strcpy(*queryStr, optr);

        *queryStr += len;
      }
    }

    int64_t stime2 = 0, etime2 = INT64_MAX;
    tmRangeIsSet = false;
    char* p2 = *queryStr;
    ret = getQueryCondExprImpl(pCmd, pExpr->pRight, &stime2, &etime2, &tmRangeIsSet, queryStr);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }

    if (tmRangeIsSet) {
      *queryTimeRangeIsSet = true;
      if (pExpr->nSQLOptr == TK_AND) {
        *stime = stime2 > (*stime) ? stime2 : (*stime);
        *etime = etime2 < (*etime) ? etime2 : (*etime);

      } else {
2940 2941
        const char* msg1 = "not support multi-segments query time ranges";
        setErrMsg(pCmd, msg1);
H
hzcheng 已提交
2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024
        return TSDB_CODE_INVALID_SQL;
      }
    }

    if (p != *queryStr) {  // either the left and right hand side has tags
                           // filter
      if (p2 == *queryStr && p != p2 && pCmd->tagCond.type == TSQL_STABLE_QTYPE_COND) {
        /*
         * has no tags filter info on the right hand side
         * has filter on the left hand side
         *
         * rollback string
         */
        int32_t len = (pExpr->nSQLOptr == TK_AND) ? 3 : 2;
        *queryStr -= len;

        removeLeftParentheses(queryStr, p);
      } else if (p2 != *queryStr && p == p2) {
        // do nothing
      } else {
        if (pCmd->tagCond.type == TSQL_STABLE_QTYPE_COND) {
          *(*queryStr) = ')';
          *queryStr += 1;
        }
      }
    }

    return TSDB_CODE_SUCCESS;
  }

  if (pLeft->nSQLOptr == TK_ID && (pRight->nSQLOptr == TK_INTEGER || pRight->nSQLOptr == TK_FLOAT ||
                                   pRight->nSQLOptr == TK_STRING || pRight->nSQLOptr == TK_BOOL)) {
    // do nothing
  } else if (pRight->nSQLOptr == TK_ID && (pLeft->nSQLOptr == TK_INTEGER || pLeft->nSQLOptr == TK_FLOAT ||
                                           pLeft->nSQLOptr == TK_STRING || pLeft->nSQLOptr == TK_BOOL)) {
    /*
     * exchange value of the left-handside and the value of the right-handside
     * to make sure that the value of filter expression always locates in right-handside and
     * the column-id is at the left hande side.
     */
    uint32_t optr = 0;
    switch (pExpr->nSQLOptr) {
      case TK_LE:
        optr = TK_GE;
        break;
      case TK_LT:
        optr = TK_GT;
        break;
      case TK_GT:
        optr = TK_LT;
        break;
      case TK_GE:
        optr = TK_LE;
        break;
      default:
        optr = pExpr->nSQLOptr;
    }

    pExpr->nSQLOptr = optr;

    tSQLExpr* pTmpExpr = pExpr->pLeft;
    pExpr->pLeft = pExpr->pRight;
    pExpr->pRight = pTmpExpr;
  }

  return handleExprInQueryCond(pCmd, queryTimeRangeIsSet, queryStr, stime, etime, pExpr);
}

int tableNameCompar(const void* lhs, const void* rhs) {
  char* left = *(char**)lhs;
  char* right = *(char**)rhs;

  int32_t ret = strcmp(left, right);

  if (ret == 0) {
    return 0;
  }

  return ret > 0 ? 1 : -1;
}

static int32_t setMetersIDForMetricQuery(SSqlObj* pSql, char* tmpTagCondBuf) {
  SSqlCmd* pCmd = &pSql->cmd;
3025
  const char* msg = "meter name too long";
H
hzcheng 已提交
3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067

  pCmd->tagCond.allocSize = 4096;
  pCmd->tagCond.pData = realloc(pCmd->tagCond.pData, pCmd->tagCond.allocSize);

  char db[TSDB_METER_ID_LEN] = {0};

  /* remove the duplicated input table names */
  int32_t num = 0;
  char**  segments = strsplit(tmpTagCondBuf, ",", &num);
  qsort(segments, num, POINTER_BYTES, tableNameCompar);

  int32_t j = 1;
  for (int32_t i = 1; i < num; ++i) {
    if (strcmp(segments[i], segments[i - 1]) != 0) {
      segments[j++] = segments[i];
    }
  }
  num = j;

  extractDBName(pCmd->name, db);
  SSQLToken tDB = {
      .z = db, .n = strlen(db), .type = TK_STRING,
  };

  char* acc = getAccountId(pSql);
  for (int32_t i = 0; i < num; ++i) {
    if (pCmd->tagCond.allocSize - pCmd->tagCond.len < (TSDB_METER_ID_LEN + 1)) {
      /* remain space is insufficient, buy more spaces */
      pCmd->tagCond.allocSize = (pCmd->tagCond.allocSize << 1);
      pCmd->tagCond.pData = realloc(pCmd->tagCond.pData, pCmd->tagCond.allocSize);
    }

    if (i >= 1) {
      pCmd->tagCond.pData[pCmd->tagCond.len++] = ',';
    }

    int32_t xlen = strlen(segments[i]);

    SSQLToken t = {.z = segments[i], .n = xlen, .type = TK_STRING};
    int32_t   ret = setObjFullName(pCmd->tagCond.pData + pCmd->tagCond.len, acc, &tDB, &t, &xlen);

    if (ret != TSDB_CODE_SUCCESS) {
3068
      setErrMsg(pCmd, msg);
H
hzcheng 已提交
3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079
      tfree(segments);
      return ret;
    }

    pCmd->tagCond.len += xlen;
  }

  tfree(segments);
  return TSDB_CODE_SUCCESS;
}

3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102
static bool validateFilterExpr(SSqlCmd* pCmd) {
  for (int32_t i = 0; i < pCmd->colList.numOfCols; ++i) {
    SColumnBase* pColBase = &pCmd->colList.pColList[i];

    if (pColBase->filterOn > 0) {
      int32_t lowerOptr = pColBase->lowerRelOptr;
      int32_t upperOptr = pColBase->upperRelOptr;

      if ((lowerOptr == TSDB_RELATION_LARGE_EQUAL || lowerOptr == TSDB_RELATION_LARGE) &&
          (upperOptr == TSDB_RELATION_LESS_EQUAL || upperOptr == TSDB_RELATION_LESS)) {
        continue;
      }

      // there must be at least two range, not support yet.
      if (lowerOptr * upperOptr != TSDB_RELATION_INVALID) {
        return false;
      }
    }
  }

  return true;
}

H
hzcheng 已提交
3103 3104 3105 3106 3107 3108 3109
int32_t buildQueryCond(SSqlObj* pSql, tSQLExpr* pExpr) {
  SSqlCmd* pCmd = &pSql->cmd;

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

3110 3111 3112
  const char* msg1 = "invalid expression";
  const char* msg2 = "meter is not allowed";
  const char* msg3 = "invalid filter expression";
H
hzcheng 已提交
3113 3114 3115 3116

  tSQLExpr* pLeft = pExpr->pLeft;
  tSQLExpr* pRight = pExpr->pRight;
  if (pLeft == NULL || pRight == NULL || (pLeft->nSQLOptr == TK_ID && pRight->nSQLOptr == TK_ID)) {
3117
    setErrMsg(pCmd, msg1);
H
hzcheng 已提交
3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142
    return TSDB_CODE_INVALID_SQL;
  }

  bool setTimeRange = false;

  /* tags query condition may be larger than 512bytes, therefore, we need to prepare enough large space */
  char  tmpTagCondBuf[TSDB_MAX_SQL_LEN] = {0};
  char* q = tmpTagCondBuf;

  pCmd->stime = 0;
  pCmd->etime = INT64_MAX;
  int32_t ret = getQueryCondExprImpl(pCmd, pExpr, &pCmd->stime, &pCmd->etime, &setTimeRange, &q);
  if (ret != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_INVALID_SQL;
  }

  // query condition for tags
  if (q == tmpTagCondBuf) {
    pCmd->tagCond.len = 0;
  } else {
    int32_t qlen = (q - tmpTagCondBuf) + 1;
    tmpTagCondBuf[qlen - 1] = 0;

    if (pCmd->tagCond.type == TSQL_STABLE_QTYPE_SET) {
      if (!UTIL_METER_IS_METRIC(pCmd)) {
3143
        setErrMsg(pCmd, msg2);
H
hzcheng 已提交
3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160
        return TSDB_CODE_INVALID_SQL;
      }

      ret = setMetersIDForMetricQuery(pSql, tmpTagCondBuf);
    } else {
      if (pCmd->tagCond.allocSize < qlen + 1) {
        pCmd->tagCond.allocSize = qlen + 1;
        pCmd->tagCond.pData = realloc(pCmd->tagCond.pData, pCmd->tagCond.allocSize);
      }

      strcpy(pCmd->tagCond.pData, tmpTagCondBuf);
      pCmd->tagCond.len = qlen;  // plus one null-terminated symbol
    }

    pCmd->tagCond.pData[pCmd->tagCond.len] = 0;
  }

3161
  if (!validateFilterExpr(pCmd)) {
3162
    setErrMsg(pCmd, msg3);
3163 3164 3165
    return TSDB_CODE_INVALID_SQL;
  }

H
hzcheng 已提交
3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257
  return ret;
}

int32_t getTimeRange(int64_t* stime, int64_t* etime, tSQLExpr* pRight, int32_t optr, int16_t timePrecision) {
  assert(pRight->nSQLOptr == TK_INTEGER || pRight->nSQLOptr == TK_FLOAT || pRight->nSQLOptr == TK_STRING ||
         pRight->nSQLOptr == TK_TIMESTAMP);

  int64_t val = 0;
  bool    parsed = false;
  if (pRight->val.nType == TSDB_DATA_TYPE_BINARY) {
    strdequote(pRight->val.pz);
    char* seg = strnchr(pRight->val.pz, '-', pRight->val.nLen);
    if (seg != NULL) {
      if (taosParseTime(pRight->val.pz, &val, pRight->val.nLen, TSDB_TIME_PRECISION_MICRO) == TSDB_CODE_SUCCESS) {
        parsed = true;
      } else {
        return TSDB_CODE_INVALID_SQL;
      }
    }
  } else if (pRight->nSQLOptr == TK_INTEGER && timePrecision == TSDB_TIME_PRECISION_MILLI) {
    /*
     * if the pRight->nSQLOptr == TK_INTEGER/TK_FLOAT, the value is adaptive, we
     * need the time precision of metermeta to transfer the value in MICROSECOND
     *
     * Additional check to avoid data overflow
     */
    if (pRight->val.i64Key <= INT64_MAX / 1000) {
      pRight->val.i64Key *= 1000;
    }
  } else if (pRight->nSQLOptr == TK_FLOAT && timePrecision == TSDB_TIME_PRECISION_MILLI) {
    pRight->val.dKey *= 1000;
  }

  if (!parsed) {
    /*
     * failed to parse timestamp in regular formation, try next
     * it may be a epoch time in string format
     */
    tVariantDump(&pRight->val, (char*)&val, TSDB_DATA_TYPE_BIGINT);

    /*
     * transfer it into MICROSECOND format if it is a string, since for
     * TK_INTEGER/TK_FLOAT the value has been transferred
     *
     * additional check to avoid data overflow
     */
    if (pRight->nSQLOptr == TK_STRING && timePrecision == TSDB_TIME_PRECISION_MILLI) {
      if (val <= INT64_MAX / 1000) {
        val *= 1000;
      }
    }
  }

  int32_t delta = 1;
  /* for millisecond, delta is 1ms=1000us */
  if (timePrecision == TSDB_TIME_PRECISION_MILLI) {
    delta *= 1000;
  }

  if (optr == TK_LE) {
    *etime = val;
  } else if (optr == TK_LT) {
    *etime = val - delta;
  } else if (optr == TK_GT) {
    *stime = val + delta;
  } else if (optr == TK_GE) {
    *stime = val;
  } else if (optr == TK_EQ) {
    *stime = val;
    *etime = *stime;
  }
  return TSDB_CODE_SUCCESS;
}

int32_t tsRewriteFieldNameIfNecessary(SSqlCmd* pCmd) {
  for (int32_t i = 0; i < pCmd->fieldsInfo.numOfOutputCols; ++i) {
    char* fieldName = tscFieldInfoGetField(pCmd, i)->name;
    for (int32_t j = 0; j < TSDB_COL_NAME_LEN && fieldName[j] != 0; ++j) {
      if (fieldName[j] == '(' || fieldName[j] == ')' || fieldName[j] == '*' || fieldName[j] == ',' ||
          fieldName[j] == '.' || fieldName[j] == '/' || fieldName[j] == '+' || fieldName[j] == '-' ||
          fieldName[j] == ' ') {
        fieldName[j] = '_';
      }
    }
    fieldName[TSDB_COL_NAME_LEN - 1] = 0;
  }

  // the column name may be identical, here check again
  for (int32_t i = 0; i < pCmd->fieldsInfo.numOfOutputCols; ++i) {
    char* fieldName = tscFieldInfoGetField(pCmd, i)->name;
    for (int32_t j = i + 1; j < pCmd->fieldsInfo.numOfOutputCols; ++j) {
      if (strncasecmp(fieldName, tscFieldInfoGetField(pCmd, j)->name, TSDB_COL_NAME_LEN) == 0) {
3258 3259
        const char* msg = "duplicated column name in new table";
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272
        return TSDB_CODE_INVALID_SQL;
      }
    }
  }

  return TSDB_CODE_SUCCESS;
}

int32_t setFillPolicy(SSqlCmd* pCmd, SQuerySQL* pQuerySQL) {
  tVariantList*     pFillToken = pQuerySQL->fillType;
  tVariantListItem* pItem = &pFillToken->a[0];

  const int32_t START_INTERPO_COL_IDX = 1;
3273 3274 3275
  const char* msg = "illegal value or data overflow";
  const char* msg1 = "value is expected";
  const char* msg2 = "invalid fill option";
H
hzcheng 已提交
3276 3277

  if (pItem->pVar.nType != TSDB_DATA_TYPE_BINARY) {
3278
    setErrMsg(pCmd, msg2);
H
hzcheng 已提交
3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298
    return TSDB_CODE_INVALID_SQL;
  }

  if (strncasecmp(pItem->pVar.pz, "none", 4) == 0 && pItem->pVar.nLen == 4) {
    pCmd->interpoType = TSDB_INTERPO_NONE;
  } else if (strncasecmp(pItem->pVar.pz, "null", 4) == 0 && pItem->pVar.nLen == 4) {
    pCmd->interpoType = TSDB_INTERPO_NULL;
    for (int32_t i = START_INTERPO_COL_IDX; i < pCmd->fieldsInfo.numOfOutputCols; ++i) {
      TAOS_FIELD* pFields = tscFieldInfoGetField(pCmd, i);
      setNull((char*)&pCmd->defaultVal[i], pFields->type, pFields->bytes);
    }
  } else if (strncasecmp(pItem->pVar.pz, "prev", 4) == 0 && pItem->pVar.nLen == 4) {
    pCmd->interpoType = TSDB_INTERPO_PREV;
  } else if (strncasecmp(pItem->pVar.pz, "linear", 6) == 0 && pItem->pVar.nLen == 6) {
    //         not support yet
    pCmd->interpoType = TSDB_INTERPO_LINEAR;
  } else if (strncasecmp(pItem->pVar.pz, "value", 5) == 0 && pItem->pVar.nLen == 5) {
    pCmd->interpoType = TSDB_INTERPO_SET_VALUE;

    if (pFillToken->nExpr == 1) {
3299
      setErrMsg(pCmd, msg1);
H
hzcheng 已提交
3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324
      return TSDB_CODE_INVALID_SQL;
    }

    int32_t startPos = 1;
    int32_t numOfFillVal = pFillToken->nExpr - 1;

    /* for point interpolation query, we do not have the timestamp column */
    if (tscIsPointInterpQuery(pCmd)) {
      startPos = 0;

      if (numOfFillVal > pCmd->fieldsInfo.numOfOutputCols) {
        numOfFillVal = pCmd->fieldsInfo.numOfOutputCols;
      }
    } else {
      numOfFillVal =
          (pFillToken->nExpr > pCmd->fieldsInfo.numOfOutputCols) ? pCmd->fieldsInfo.numOfOutputCols : pFillToken->nExpr;
    }

    int32_t j = 1;

    for (int32_t i = startPos; i < numOfFillVal; ++i, ++j) {
      TAOS_FIELD* pFields = tscFieldInfoGetField(pCmd, i);

      int32_t ret = tVariantDump(&pFillToken->a[j].pVar, (char*)&pCmd->defaultVal[i], pFields->type);
      if (ret != TSDB_CODE_SUCCESS) {
3325
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347
        return TSDB_CODE_INVALID_SQL;
      }

      if (pFields->type == TSDB_DATA_TYPE_BINARY || pFields->type == TSDB_DATA_TYPE_NCHAR) {
        setNull((char*)(&pCmd->defaultVal[i]), pFields->type, pFields->bytes);
      }
    }

    if ((pFillToken->nExpr < pCmd->fieldsInfo.numOfOutputCols) ||
        ((pFillToken->nExpr - 1 < pCmd->fieldsInfo.numOfOutputCols) && (tscIsPointInterpQuery(pCmd)))) {
      tVariantListItem* lastItem = &pFillToken->a[pFillToken->nExpr - 1];

      for (int32_t i = numOfFillVal; i < pCmd->fieldsInfo.numOfOutputCols; ++i) {
        TAOS_FIELD* pFields = tscFieldInfoGetField(pCmd, i);
        tVariantDump(&lastItem->pVar, (char*)&pCmd->defaultVal[i], pFields->type);

        if (pFields->type == TSDB_DATA_TYPE_BINARY || pFields->type == TSDB_DATA_TYPE_NCHAR) {
          setNull((char*)(&pCmd->defaultVal[i]), pFields->type, pFields->bytes);
        }
      }
    }
  } else {
3348
    setErrMsg(pCmd, msg2);
H
hzcheng 已提交
3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372
    return TSDB_CODE_INVALID_SQL;
  }

  return TSDB_CODE_SUCCESS;
}

static void setDefaultOrderInfo(SSqlCmd* pCmd) {
  /* set default timestamp order information for all queries */
  pCmd->order.order = TSQL_SO_ASC;

  if (isTopBottomQuery(pCmd)) {
    pCmd->order.order = TSQL_SO_ASC;
    pCmd->order.orderColId = PRIMARYKEY_TIMESTAMP_COL_INDEX;
  } else {
    pCmd->order.orderColId = -1;
  }

  /* for metric query, set default ascending order for group output */
  if (UTIL_METER_IS_METRIC(pCmd)) {
    pCmd->groupbyExpr.orderType = TSQL_SO_ASC;
  }
}

int32_t setOrderByClause(SSqlCmd* pCmd, SQuerySQL* pQuerySql, SSchema* pSchema, int32_t numOfCols) {
3373 3374 3375 3376
  const char* msg = "only support order by primary timestamp";
  const char* msg3 = "invalid column name";
  const char* msg5 = "only support order by primary timestamp and queried column";
  const char* msg6 = "only support order by primary timestamp and first tag in groupby clause";
H
hzcheng 已提交
3377 3378 3379 3380 3381 3382 3383 3384 3385 3386

  setDefaultOrderInfo(pCmd);

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

  tVariantList* pSortorder = pQuerySql->pSortOrder;
  if (UTIL_METER_IS_NOMRAL_METER(pCmd)) {
    if (pSortorder->nExpr > 1) {
3387
      setErrMsg(pCmd, msg);
H
hzcheng 已提交
3388 3389 3390 3391
      return TSDB_CODE_INVALID_SQL;
    }
  } else {
    if (pSortorder->nExpr > 2) {
3392
      setErrMsg(pCmd, msg6);
H
hzcheng 已提交
3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423
      return TSDB_CODE_INVALID_SQL;
    }
  }

  // handle the first part of order by
  tVariant* pVar = &pSortorder->a[0].pVar;

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

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

  if (UTIL_METER_IS_METRIC(pCmd)) {  // metric query
    SSchema* pTagSchema = tsGetTagSchema(pCmd->pMeterMeta);
    int32_t  columnIndex = getColumnIndexByName(&columnName, pTagSchema, pCmd->pMeterMeta->numOfTags);
    bool     orderByTags = false;
    bool     orderByTS = false;
    if (pCmd->groupbyExpr.tagIndex[0] == columnIndex) {
      if (columnIndex >= 0 || (strncasecmp(columnName.z, TSQL_TBNAME_L, 6) == 0)) {
        orderByTags = true;
      }
    }

    columnIndex = getColumnIndexByName(&columnName, pSchema, numOfCols);
    if (PRIMARYKEY_TIMESTAMP_COL_INDEX == columnIndex) {
      orderByTS = true;
    }

    if (!(orderByTags || orderByTS)) {
3424
      setErrMsg(pCmd, msg6);
H
hzcheng 已提交
3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444
      return TSDB_CODE_INVALID_SQL;
    } else {
      assert(!(orderByTags && orderByTS));
    }

    if (pSortorder->nExpr == 1) {
      if (orderByTags) {
        pCmd->groupbyExpr.orderIdx = columnIndex;
        pCmd->groupbyExpr.orderType = pQuerySql->pSortOrder->a[0].sortOrder;
      } else {
        pCmd->order.order = pSortorder->a[0].sortOrder;
        pCmd->order.orderColId = PRIMARYKEY_TIMESTAMP_COL_INDEX;
      }
    }

    if (pSortorder->nExpr == 2) {
      tVariant* pVar2 = &pSortorder->a[1].pVar;
      SSQLToken cname = {pVar2->nLen, pVar2->nType, pVar2->pz};
      columnIndex = getColumnIndexByName(&cname, pSchema, numOfCols);
      if (columnIndex != PRIMARYKEY_TIMESTAMP_COL_INDEX) {
3445
        setErrMsg(pCmd, msg5);
H
hzcheng 已提交
3446 3447 3448 3449 3450 3451 3452 3453 3454 3455
        return TSDB_CODE_INVALID_SQL;
      } else {
        pCmd->order.order = pSortorder->a[1].sortOrder;
        pCmd->order.orderColId = PRIMARYKEY_TIMESTAMP_COL_INDEX;
      }
    }

  } else {  // meter query
    int32_t columnIndex = getColumnIndexByName(&columnName, pSchema, numOfCols);
    if (columnIndex <= -1) {
3456
      setErrMsg(pCmd, msg3);
H
hzcheng 已提交
3457 3458 3459 3460
      return TSDB_CODE_INVALID_SQL;
    }

    if (columnIndex != PRIMARYKEY_TIMESTAMP_COL_INDEX && !isTopBottomQuery(pCmd)) {
3461
      setErrMsg(pCmd, msg5);
H
hzcheng 已提交
3462 3463 3464 3465 3466 3467 3468 3469 3470 3471
      return TSDB_CODE_INVALID_SQL;
    }

    if (isTopBottomQuery(pCmd) && pCmd->nAggTimeInterval >= 0) {
      /* order of top/bottom query in interval is not valid  */
      SSqlExpr* pExpr = tscSqlExprGet(pCmd, 0);
      assert(pExpr->sqlFuncId == TSDB_FUNC_TS);

      pExpr = tscSqlExprGet(pCmd, 1);
      if (pExpr->colInfo.colIdx != columnIndex && columnIndex != PRIMARYKEY_TIMESTAMP_COL_INDEX) {
3472
        setErrMsg(pCmd, msg);
H
hzcheng 已提交
3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492
        return TSDB_CODE_INVALID_SQL;
      }

      pCmd->order.order = pQuerySql->pSortOrder->a[0].sortOrder;
      pCmd->order.orderColId = pSchema[columnIndex].colId;
      return TSDB_CODE_SUCCESS;
    }

    pCmd->order.order = pQuerySql->pSortOrder->a[0].sortOrder;
  }

  return TSDB_CODE_SUCCESS;
}

int32_t setAlterTableInfo(SSqlObj* pSql, struct SSqlInfo* pInfo) {
  SSqlCmd* pCmd = &pSql->cmd;

  SAlterTableSQL* pAlterSQL = pInfo->pAlterInfo;
  pCmd->command = TSDB_SQL_ALTER_TABLE;

3493
  if (tscValidateName(&(pAlterSQL->name)) != TSDB_CODE_SUCCESS) {
3494 3495
  	const char* msg = "invalid table name";
    setErrMsg(pCmd, msg);
3496 3497
    return TSDB_CODE_INVALID_SQL;
  }
P
plum-lihui 已提交
3498

H
hzcheng 已提交
3499
  if (setMeterID(pSql, &(pAlterSQL->name)) != TSDB_CODE_SUCCESS) {
3500 3501
    const char* msg = "table name too long";
    setErrMsg(pCmd, msg);
H
hzcheng 已提交
3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515
    return TSDB_CODE_INVALID_SQL;
  }

  int32_t ret = tscGetMeterMeta(pSql, pCmd->name);
  if (ret != TSDB_CODE_SUCCESS) {
    return ret;
  }

  SMeterMeta* pMeterMeta = pCmd->pMeterMeta;
  SSchema*    pSchema = tsGetSchema(pMeterMeta);

  if (pInfo->sqlType == ALTER_TABLE_TAGS_ADD || pInfo->sqlType == ALTER_TABLE_TAGS_DROP ||
      pInfo->sqlType == ALTER_TABLE_TAGS_CHG) {
    if (UTIL_METER_IS_NOMRAL_METER(pCmd)) {
3516 3517
      const char* msg = "manipulation of tag available for metric";
      setErrMsg(pCmd, msg);
H
hzcheng 已提交
3518 3519 3520
      return TSDB_CODE_INVALID_SQL;
    }
  } else if ((pInfo->sqlType == ALTER_TABLE_TAGS_SET) && (UTIL_METER_IS_METRIC(pCmd))) {
3521 3522
    const char* msg = "set tag value only available for table";
    setErrMsg(pCmd, msg);
H
hzcheng 已提交
3523 3524 3525
    return TSDB_CODE_INVALID_SQL;
  } else if ((pInfo->sqlType == ALTER_TABLE_ADD_COLUMN || pInfo->sqlType == ALTER_TABLE_DROP_COLUMN) &&
             UTIL_METER_IS_CREATE_FROM_METRIC(pCmd)) {
3526 3527
    const char* msg = "column can only be modified by metric";
    setErrMsg(pCmd, msg);
H
hzcheng 已提交
3528 3529 3530 3531 3532 3533 3534 3535
    return TSDB_CODE_INVALID_SQL;
  }

  if (pInfo->sqlType == ALTER_TABLE_TAGS_ADD) {
    pCmd->count = TSDB_ALTER_TABLE_ADD_TAG_COLUMN;

    tFieldList* pFieldList = pAlterSQL->pAddColumns;
    if (pFieldList->nField > 1) {
3536 3537
      const char* msg = "only support add one tag";
      setErrMsg(pCmd, msg);
H
hzcheng 已提交
3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550
      return TSDB_CODE_INVALID_SQL;
    }

    if (!validateOneTags(pCmd, &pFieldList->p[0])) {
      return TSDB_CODE_INVALID_SQL;
    }

    tscFieldInfoSetValFromField(&pCmd->fieldsInfo, 0, &pFieldList->p[0]);
    pCmd->numOfCols = 1;  // only one column

  } else if (pInfo->sqlType == ALTER_TABLE_TAGS_DROP) {
    pCmd->count = TSDB_ALTER_TABLE_DROP_TAG_COLUMN;

3551 3552 3553 3554 3555
    const char* msg1 = "no tags can be dropped";
    const char* msg2 = "only support one tag";
    const char* msg3 = "tag name too long";
    const char* msg4 = "illegal tag name";
    const char* msg5 = "primary tag cannot be dropped";
H
hzcheng 已提交
3556 3557

    if (pMeterMeta->numOfTags == 1) {
3558
      setErrMsg(pCmd, msg1);
H
hzcheng 已提交
3559 3560 3561 3562 3563
      return TSDB_CODE_INVALID_SQL;
    }

    // numOfTags == 1
    if (pAlterSQL->varList->nExpr > 1) {
3564
      setErrMsg(pCmd, msg2);
H
hzcheng 已提交
3565 3566 3567 3568 3569
      return TSDB_CODE_INVALID_SQL;
    }

    tVariantListItem* pItem = &pAlterSQL->varList->a[0];
    if (pItem->pVar.nLen > TSDB_COL_NAME_LEN) {
3570
      setErrMsg(pCmd, msg3);
H
hzcheng 已提交
3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586
      return TSDB_CODE_INVALID_SQL;
    }

    int32_t idx = -1;
    for (int32_t i = 0; i < pMeterMeta->numOfTags; ++i) {
      int32_t tagIdx = i + pMeterMeta->numOfColumns;
      char*   tagName = pSchema[tagIdx].name;
      size_t  nLen = strlen(tagName);

      if ((strncasecmp(tagName, pItem->pVar.pz, nLen) == 0) && (pItem->pVar.nLen == nLen)) {
        idx = i;
        break;
      }
    }

    if (idx == -1) {
3587
      setErrMsg(pCmd, msg4);
H
hzcheng 已提交
3588 3589
      return TSDB_CODE_INVALID_SQL;
    } else if (idx == 0) {
3590
      setErrMsg(pCmd, msg5);
H
hzcheng 已提交
3591 3592 3593 3594 3595 3596 3597 3598 3599 3600
      return TSDB_CODE_INVALID_SQL;
    }

    char name[128] = {0};
    strncpy(name, pItem->pVar.pz, pItem->pVar.nLen);
    tscFieldInfoSetValue(&pCmd->fieldsInfo, 0, TSDB_DATA_TYPE_INT, name, tDataTypeDesc[TSDB_DATA_TYPE_INT].nSize);

    pCmd->numOfCols = 1;  // only one column

  } else if (pInfo->sqlType == ALTER_TABLE_TAGS_CHG) {
3601 3602
    const char* msg1 = "tag name too long";
    const char* msg2 = "invalid tag name";
3603

H
hzcheng 已提交
3604 3605 3606 3607 3608 3609
    pCmd->count = TSDB_ALTER_TABLE_CHANGE_TAG_COLUMN;
    tVariantList* pVarList = pAlterSQL->varList;
    if (pVarList->nExpr > 2) {
      return TSDB_CODE_INVALID_SQL;
    }

3610 3611 3612 3613
    tVariantListItem* pSrcItem = &pAlterSQL->varList->a[0];
    tVariantListItem* pDstItem = &pAlterSQL->varList->a[1];

    if (pSrcItem->pVar.nLen >= TSDB_COL_NAME_LEN || pDstItem->pVar.nLen >= TSDB_COL_NAME_LEN) {
3614
      setErrMsg(pCmd, msg1);
H
hzcheng 已提交
3615 3616 3617
      return TSDB_CODE_INVALID_SQL;
    }

3618
    if (pSrcItem->pVar.nType != TSDB_DATA_TYPE_BINARY || pDstItem->pVar.nType != TSDB_DATA_TYPE_BINARY) {
3619
      setErrMsg(pCmd, msg2);
3620 3621
      return TSDB_CODE_INVALID_SQL;
    }
H
hzcheng 已提交
3622 3623 3624 3625 3626 3627 3628 3629

    bool srcFound = false;
    bool dstFound = false;
    for (int32_t i = 0; i < pMeterMeta->numOfTags; ++i) {
      int32_t tagIdx = i + pMeterMeta->numOfColumns;
      char*   tagName = pSchema[tagIdx].name;

      size_t nameLen = strlen(tagName);
3630
      if ((!srcFound) && (strncasecmp(tagName, pSrcItem->pVar.pz, nameLen) == 0 && (pSrcItem->pVar.nLen == nameLen))) {
H
hzcheng 已提交
3631 3632 3633
        srcFound = true;
      }

3634 3635
      //todo extract method
      if ((!dstFound) && (strncasecmp(tagName, pDstItem->pVar.pz, nameLen) == 0 && (pDstItem->pVar.nLen == nameLen))) {
H
hzcheng 已提交
3636 3637 3638 3639 3640
        dstFound = true;
      }
    }

    if ((!srcFound) || dstFound) {
3641 3642
      const char* msg = "invalid tag name";
      setErrMsg(pCmd, msg);
H
hzcheng 已提交
3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665
      return TSDB_CODE_INVALID_SQL;
    }

    char name[128] = {0};
    strncpy(name, pVarList->a[0].pVar.pz, pVarList->a[0].pVar.nLen);
    tscFieldInfoSetValue(&pCmd->fieldsInfo, 0, TSDB_DATA_TYPE_INT, name, tDataTypeDesc[TSDB_DATA_TYPE_INT].nSize);

    memset(name, 0, tListLen(name));
    strncpy(name, pVarList->a[1].pVar.pz, pVarList->a[1].pVar.nLen);
    tscFieldInfoSetValue(&pCmd->fieldsInfo, 1, TSDB_DATA_TYPE_INT, name, tDataTypeDesc[TSDB_DATA_TYPE_INT].nSize);
    pCmd->numOfCols = 2;

  } else if (pInfo->sqlType == ALTER_TABLE_TAGS_SET) {
    pCmd->count = TSDB_ALTER_TABLE_UPDATE_TAG_VAL;

    // Note: update can only be applied to meter not metric.
    // the following is handle display tags value for meters created according to metric
    char* pTagValue = tsGetTagsValue(pCmd->pMeterMeta);

    tVariantList* pVarList = pAlterSQL->varList;
    tVariant*     pTagName = &pVarList->a[0].pVar;

    if (pTagName->nLen > TSDB_COL_NAME_LEN) {
3666 3667
      const char* msg = "tag name too long";
      setErrMsg(pCmd, msg);
H
hzcheng 已提交
3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683
      return TSDB_CODE_INVALID_SQL;
    }

    int32_t  tagsIndex = -1;
    SSchema* pTagsSchema = tsGetTagSchema(pCmd->pMeterMeta);
    for (int32_t i = 0; i < pCmd->pMeterMeta->numOfTags; ++i) {
      if (strcmp(pTagName->pz, pTagsSchema[i].name) == 0 && strlen(pTagsSchema[i].name) == pTagName->nLen) {
        tagsIndex = i;
        tVariantDump(&pVarList->a[1].pVar, pCmd->payload, pTagsSchema[i].type);
        break;
      }

      pTagValue += pTagsSchema[i].bytes;
    }

    if (tagsIndex == -1) {
3684 3685
      const char* msg = "invalid tag name";
      setErrMsg(pCmd, msg);
H
hzcheng 已提交
3686 3687 3688 3689 3690 3691
      return TSDB_CODE_INVALID_SQL;
    }

    // validate the length of binary
    if (pTagsSchema[tagsIndex].type == TSDB_DATA_TYPE_BINARY &&
        pVarList->a[1].pVar.nLen > pTagsSchema[tagsIndex].bytes) {
3692 3693
      const char* msg = "tag value too long";
      setErrMsg(pCmd, msg);
H
hzcheng 已提交
3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706
      return TSDB_CODE_INVALID_SQL;
    }

    char name[128] = {0};
    strncpy(name, pTagName->pz, pTagName->nLen);
    tscFieldInfoSetValue(&pCmd->fieldsInfo, 0, TSDB_DATA_TYPE_INT, name, tDataTypeDesc[TSDB_DATA_TYPE_INT].nSize);

    pCmd->numOfCols = 1;
  } else if (pInfo->sqlType == ALTER_TABLE_ADD_COLUMN) {
    pCmd->count = TSDB_ALTER_TABLE_ADD_COLUMN;

    tFieldList* pFieldList = pAlterSQL->pAddColumns;
    if (pFieldList->nField > 1) {
3707 3708
      const char* msg = "only support add one column";
      setErrMsg(pCmd, msg);
H
hzcheng 已提交
3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721
      return TSDB_CODE_INVALID_SQL;
    }

    if (!validateOneColumn(pCmd, &pFieldList->p[0])) {
      return TSDB_CODE_INVALID_SQL;
    }

    tscFieldInfoSetValFromField(&pCmd->fieldsInfo, 0, &pFieldList->p[0]);
    pCmd->numOfCols = 1;  // only one column

  } else if (pInfo->sqlType == ALTER_TABLE_DROP_COLUMN) {
    pCmd->count = TSDB_ALTER_TABLE_DROP_COLUMN;

3722 3723 3724 3725 3726
    const char* msg1 = "no columns can be dropped";
    const char* msg2 = "only support one column";
    const char* msg3 = "column name too long";
    const char* msg4 = "illegal column name";
    const char* msg5 = "primary timestamp column cannot be dropped";
H
hzcheng 已提交
3727 3728

    if (pMeterMeta->numOfColumns == TSDB_MIN_COLUMNS) {  //
3729
      setErrMsg(pCmd, msg1);
H
hzcheng 已提交
3730 3731 3732 3733
      return TSDB_CODE_INVALID_SQL;
    }

    if (pAlterSQL->varList->nExpr > 1) {
3734
      setErrMsg(pCmd, msg2);
H
hzcheng 已提交
3735 3736 3737 3738 3739
      return TSDB_CODE_INVALID_SQL;
    }

    tVariantListItem* pItem = &pAlterSQL->varList->a[0];
    if (pItem->pVar.nLen > TSDB_COL_NAME_LEN) {
3740
      setErrMsg(pCmd, msg3);
H
hzcheng 已提交
3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755
      return TSDB_CODE_INVALID_SQL;
    }

    int32_t idx = -1;
    for (int32_t i = 0; i < pMeterMeta->numOfColumns; ++i) {
      char*  colName = pSchema[i].name;
      size_t len = strlen(colName);

      if ((strncasecmp(colName, pItem->pVar.pz, len) == 0) && (len == pItem->pVar.nLen)) {
        idx = i;
        break;
      }
    }

    if (idx == -1) {
3756
      setErrMsg(pCmd, msg4);
H
hzcheng 已提交
3757 3758
      return TSDB_CODE_INVALID_SQL;
    } else if (idx == 0) {
3759
      setErrMsg(pCmd, msg5);
H
hzcheng 已提交
3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773
      return TSDB_CODE_INVALID_SQL;
    }

    char name[128] = {0};
    strncpy(name, pItem->pVar.pz, pItem->pVar.nLen);
    tscFieldInfoSetValue(&pCmd->fieldsInfo, 0, TSDB_DATA_TYPE_INT, name, tDataTypeDesc[TSDB_DATA_TYPE_INT].nSize);

    pCmd->numOfCols = 1;  // only one column
  }

  return TSDB_CODE_SUCCESS;
}

int32_t validateSqlFunctionInStreamSql(SSqlCmd* pCmd) {
3774 3775
  const char* msg0 = "sample interval can not be less than 10ms.";
  const char* msg1 = "functions not allowed in select clause";
H
hzcheng 已提交
3776 3777

  if (pCmd->nAggTimeInterval != 0 && pCmd->nAggTimeInterval < 10) {
3778
    setErrMsg(pCmd, msg0);
H
hzcheng 已提交
3779 3780 3781 3782 3783 3784
    return TSDB_CODE_INVALID_SQL;
  }

  for (int32_t i = 0; i < pCmd->fieldsInfo.numOfOutputCols; ++i) {
    int32_t functId = tscSqlExprGet(pCmd, i)->sqlFuncId;
    if (!IS_STREAM_QUERY_VALID(aAggs[functId].nStatus)) {
3785
      setErrMsg(pCmd, msg1);
H
hzcheng 已提交
3786 3787 3788 3789 3790 3791 3792 3793 3794
      return TSDB_CODE_INVALID_SQL;
    }
  }

  return TSDB_CODE_SUCCESS;
}

int32_t validateFunctionsInIntervalOrGroupbyQuery(SSqlCmd* pCmd) {
  bool isProjectionFunction = false;
3795
  const char* msg = "column projection is not compatible with interval";
H
hzcheng 已提交
3796 3797 3798 3799 3800 3801 3802 3803 3804 3805

  // multi-output set/ todo refactor
  for (int32_t k = 0; k < pCmd->fieldsInfo.numOfOutputCols; ++k) {
    SSqlExpr* pExpr = tscSqlExprGet(pCmd, k);
    if (pExpr->sqlFuncId == TSDB_FUNC_PRJ || pExpr->sqlFuncId == TSDB_FUNC_TAGPRJ ||
        pExpr->sqlFuncId == TSDB_FUNC_DIFF || pExpr->sqlFuncId == TSDB_FUNC_ARITHM) {
      isProjectionFunction = true;
    }
  }
  if (pCmd->metricQuery == 0 || isProjectionFunction == true) {
3806
    setErrMsg(pCmd, msg);
H
hzcheng 已提交
3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906
  }

  return isProjectionFunction == true ? TSDB_CODE_INVALID_SQL : TSDB_CODE_SUCCESS;
}

typedef struct SDNodeDynConfOption {
  char*   name;
  int32_t len;
} SDNodeDynConfOption;

int32_t validateDNodeConfig(tDCLSQL* pOptions) {
  if (pOptions->nTokens < 2 || pOptions->nTokens > 3) {
    return TSDB_CODE_INVALID_SQL;
  }

  SDNodeDynConfOption DNODE_DYNAMIC_CFG_OPTIONS[13] = {
      {"resetLog", 8},      {"resetQueryCache", 15}, {"dDebugFlag", 10},       {"taosDebugFlag", 13},
      {"tmrDebugFlag", 12}, {"cDebugFlag", 10},      {"uDebugFlag", 10},       {"mDebugFlag", 10},
      {"sdbDebugFlag", 12}, {"httpDebugFlag", 13},   {"monitorDebugFlag", 16}, {"qDebugflag", 10},
      {"debugFlag", 9}};

  SSQLToken* pOptionToken = &pOptions->a[1];

  if (pOptions->nTokens == 2) {
    // reset log and reset query cache does not need value
    for (int32_t i = 0; i < 2; ++i) {
      SDNodeDynConfOption* pOption = &DNODE_DYNAMIC_CFG_OPTIONS[i];
      if ((strncasecmp(pOption->name, pOptionToken->z, pOptionToken->n) == 0) && (pOption->len == pOptionToken->n)) {
        return TSDB_CODE_SUCCESS;
      }
    }
  } else {
    SSQLToken* pValToken = &pOptions->a[2];

    int32_t val = strtol(pValToken->z, NULL, 10);
    if (val < 131 || val > 199) {
      /* options value is out of valid range */
      return TSDB_CODE_INVALID_SQL;
    }

    for (int32_t i = 2; i < tListLen(DNODE_DYNAMIC_CFG_OPTIONS); ++i) {
      SDNodeDynConfOption* pOption = &DNODE_DYNAMIC_CFG_OPTIONS[i];

      if ((strncasecmp(pOption->name, pOptionToken->z, pOptionToken->n) == 0) && (pOption->len == pOptionToken->n)) {
        /* options is valid */
        return TSDB_CODE_SUCCESS;
      }
    }
  }

  return TSDB_CODE_INVALID_SQL;
}

int32_t validateColumnName(char* name) {
  bool ret = isKeyWord(name, strlen(name));
  if (ret) {
    return TSDB_CODE_INVALID_SQL;
  }

  SSQLToken token = {
      .z = name,
  };
  token.n = tSQLGetToken(name, &token.type);

  if (token.type != TK_STRING && token.type != TK_ID) {
    return TSDB_CODE_INVALID_SQL;
  }

  if (token.type == TK_STRING) {
    strdequote(token.z);
    strtrim(token.z);
    token.n = (uint32_t)strlen(token.z);

    int32_t k = tSQLGetToken(token.z, &token.type);
    if (k != token.n) {
      return TSDB_CODE_INVALID_SQL;
    }

    return validateColumnName(token.z);
  } else {
    if (isNumber(&token)) {
      return TSDB_CODE_INVALID_SQL;
    }
  }

  return TSDB_CODE_SUCCESS;
}

bool hasTimestampForPointInterpQuery(SSqlCmd* pCmd) {
  if (!tscIsPointInterpQuery(pCmd)) {
    return true;
  }

  return (pCmd->stime == pCmd->etime) && (pCmd->stime != 0);
}

int32_t setLimitOffsetValueInfo(SSqlObj* pSql, SQuerySQL* pQuerySql) {
  SSqlCmd* pCmd = &pSql->cmd;
  bool     isMetric = UTIL_METER_IS_METRIC(pCmd);

3907 3908 3909 3910
  const char* msg0 = "soffset can not be less than 0";
  const char* msg1 = "offset can not be less than 0";
  const char* msg2 = "slimit/soffset only available for STable query";
  const char* msg3 = "function not supported on table";
H
hzcheng 已提交
3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933

  // handle the limit offset value, validate the limit
  pCmd->limit = pQuerySql->limit;
  pCmd->glimit = pQuerySql->glimit;

  if (isMetric) {
    bool    queryOnTags = false;
    int32_t ret = tscQueryOnlyMetricTags(pCmd, &queryOnTags);
    if (ret != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_INVALID_SQL;
    }

    if (queryOnTags == true) {  // local handle the metric tag query
      pCmd->command = TSDB_SQL_RETRIEVE_TAGS;
    }

    if (pCmd->glimit.limit == 0 || pCmd->limit.limit == 0) {
      tscTrace("%p limit 0, no output result", pSql);
      pCmd->command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
      return TSDB_CODE_SUCCESS;
    }

    if (pCmd->glimit.offset < 0) {
3934
      setErrMsg(pCmd, msg0);
H
hzcheng 已提交
3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962
      return TSDB_CODE_INVALID_SQL;
    }

    /*
     * get the distribution of all meters among available vnodes that satisfy query condition from mnode ,
     * then launching multiple async-queries on referenced vnodes, which is the first-stage query operation]
     */
    int32_t code = tscGetMetricMeta(pSql, pCmd->name);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    /*
     * Query results are empty. Therefore, the result is filled with 0 if count function is employed in selection clause.
     *
     * The fill of empty result is required only when interval clause is absent.
     */
    SMetricMeta* pMetricMeta = pCmd->pMetricMeta;
    if (pCmd->pMeterMeta == NULL || pMetricMeta == NULL || pMetricMeta->numOfVnodes == 0 ||
        pMetricMeta->numOfMeters == 0) {
      tscTrace("%p no table in metricmeta, no output result", pSql);
      pCmd->command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
    }

    // keep original limitation value in globalLimit
    pCmd->globalLimit = pCmd->limit.limit;
  } else {
    if (pCmd->glimit.limit != -1 || pCmd->glimit.offset != 0) {
3963
      setErrMsg(pCmd, msg2);
H
hzcheng 已提交
3964 3965 3966 3967 3968 3969
      return TSDB_CODE_INVALID_SQL;
    }

    for (int32_t i = 0; i < pCmd->fieldsInfo.numOfOutputCols; ++i) {
      SSqlExpr* pExpr = tscSqlExprGet(pCmd, i);
      if (pExpr->colInfo.colIdx == -1) {
3970
        setErrMsg(pCmd, msg3);
H
hzcheng 已提交
3971 3972 3973 3974 3975 3976 3977 3978 3979 3980
        return TSDB_CODE_INVALID_SQL;
      }
    }

    if (pCmd->limit.limit == 0) {
      tscTrace("%p limit 0, no output result", pSql);
      pCmd->command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
    }

    if (pCmd->limit.offset < 0) {
3981
      setErrMsg(pCmd, msg1);
H
hzcheng 已提交
3982 3983 3984 3985 3986 3987
      return TSDB_CODE_INVALID_SQL;
    }
  }

  return TSDB_CODE_SUCCESS;
}
3988 3989 3990 3991 3992 3993 3994 3995 3996

static void setCreateDBOption(SCreateDbMsg* pMsg, SCreateDBInfo* pCreateDb) {
  pMsg->precision = TSDB_TIME_PRECISION_MILLI;  // millisecond by default

  pMsg->daysToKeep = htonl(-1);
  pMsg->daysToKeep1 = htonl(-1);
  pMsg->daysToKeep2 = htonl(-1);

  pMsg->blocksPerMeter = (pCreateDb->numOfBlocksPerTable == 0) ? htons(-1) : htons(pCreateDb->numOfBlocksPerTable);
3997
  pMsg->compression = (pCreateDb->compressionLevel == 0) ? -1 : pCreateDb->compressionLevel;
3998

3999
  pMsg->commitLog = (pCreateDb->commitLog == 0) ? -1 : pCreateDb->commitLog;
4000 4001 4002 4003 4004 4005 4006 4007 4008 4009
  pMsg->commitTime = (pCreateDb->commitTime == 0) ? htonl(-1) : htonl(pCreateDb->commitTime);
  pMsg->maxSessions = (pCreateDb->tablesPerVnode == 0) ? htonl(-1) : htonl(pCreateDb->tablesPerVnode);
  pMsg->cacheNumOfBlocks.fraction = (pCreateDb->numOfAvgCacheBlocks == 0) ? -1 : pCreateDb->numOfAvgCacheBlocks;
  pMsg->cacheBlockSize = (pCreateDb->cacheBlockSize == 0) ? htonl(-1) : htonl(pCreateDb->cacheBlockSize);
  pMsg->rowsInFileBlock = (pCreateDb->rowPerFileBlock == 0) ? htonl(-1) : htonl(pCreateDb->rowPerFileBlock);
  pMsg->daysPerFile = (pCreateDb->daysPerFile == 0) ? htonl(-1) : htonl(pCreateDb->daysPerFile);
  pMsg->replications = (pCreateDb->replica == 0) ? -1 : pCreateDb->replica;
}

int32_t parseCreateDBOptions(SCreateDBInfo* pCreateDbSql, SSqlCmd* pCmd) {
4010 4011
  const char* msg0 = "invalid number of options";
  const char* msg1 = "invalid time precision";
4012 4013 4014 4015 4016 4017

  SCreateDbMsg *pMsg = (SCreateDbMsg *) (pCmd->payload + tsRpcHeadSize + sizeof(SMgmtHead));
  setCreateDBOption(pMsg, pCreateDbSql);

  if (pCreateDbSql->keep != NULL) {
    switch (pCreateDbSql->keep->nExpr) {
S
slguan 已提交
4018 4019
      case 1:
        pMsg->daysToKeep = htonl(pCreateDbSql->keep->a[0].pVar.i64Key);
4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032
        break;
      case 2: {
        pMsg->daysToKeep = htonl(pCreateDbSql->keep->a[0].pVar.i64Key);
        pMsg->daysToKeep1 = htonl(pCreateDbSql->keep->a[1].pVar.i64Key);
        break;
      }
      case 3: {
        pMsg->daysToKeep = htonl(pCreateDbSql->keep->a[0].pVar.i64Key);
        pMsg->daysToKeep1 = htonl(pCreateDbSql->keep->a[1].pVar.i64Key);
        pMsg->daysToKeep2 = htonl(pCreateDbSql->keep->a[2].pVar.i64Key);
        break;
      }
      default: {
4033
        setErrMsg(pCmd, msg0);
4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050
        return TSDB_CODE_INVALID_SQL;
      }
    }
  }

  SSQLToken *pToken = &pCreateDbSql->precision;
  if (pToken->n > 0) {
    pToken->n = strdequote(pToken->z);

    if (strncmp(pToken->z, TSDB_TIME_PRECISION_MILLI_STR, pToken->n) == 0 &&
        strlen(TSDB_TIME_PRECISION_MILLI_STR) == pToken->n) {
      // time precision for this db: million second
      pMsg->precision = TSDB_TIME_PRECISION_MILLI;
    } else if (strncmp(pToken->z, TSDB_TIME_PRECISION_MICRO_STR, pToken->n) == 0 &&
        strlen(TSDB_TIME_PRECISION_MICRO_STR) == pToken->n) {
      pMsg->precision = TSDB_TIME_PRECISION_MICRO;
    } else {
4051
      setErrMsg(pCmd, msg1);
4052 4053 4054 4055 4056
      return TSDB_CODE_INVALID_SQL;
    }
  }

  return TSDB_CODE_SUCCESS;
H
huili 已提交
4057
}