tscSQLParser.c 188.9 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

S
slguan 已提交
19
#include "os.h"
H
hzcheng 已提交
20
#include "taos.h"
S
slguan 已提交
21
#include "taosmsg.h"
H
hzcheng 已提交
22
#include "tstoken.h"
H
hjxilinx 已提交
23
#include "tstrbuild.h"
H
hjxilinx 已提交
24
#include "ttime.h"
H
hzcheng 已提交
25

H
hjxilinx 已提交
26
#include "tscSQLParser.h"
H
hzcheng 已提交
27 28 29
#include "tscUtil.h"
#include "tschemautil.h"
#include "tsclient.h"
H
hjxilinx 已提交
30

S
slguan 已提交
31 32 33 34 35 36 37 38
#define DEFAULT_PRIMARY_TIMESTAMP_COL_NAME "_c0"

// -1 is tbname column index, so here use the -2 as the initial value
#define COLUMN_INDEX_INITIAL_VAL (-2)
#define COLUMN_INDEX_INITIALIZER \
  { COLUMN_INDEX_INITIAL_VAL, COLUMN_INDEX_INITIAL_VAL }
#define COLUMN_INDEX_VALIDE(index) (((index).tableIndex >= 0) && ((index).columnIndex >= TSDB_TBNAME_COLUMN_INDEX))
#define TBNAME_LIST_SEP ","
H
hzcheng 已提交
39 40

typedef struct SColumnList {
S
slguan 已提交
41 42
  int32_t      num;
  SColumnIndex ids[TSDB_MAX_COLUMNS];
H
hzcheng 已提交
43 44
} SColumnList;

S
slguan 已提交
45 46 47 48 49 50
typedef struct SColumnIdListRes {
  SSchema*    pSchema;
  int32_t     numOfCols;
  SColumnList list;
} SColumnIdListRes;

51
static SSqlExpr* doAddProjectCol(SQueryInfo* pQueryInfo, int32_t outputIndex, int32_t colIdx, int32_t tableIndex);
H
hzcheng 已提交
52 53

static int32_t setShowInfo(SSqlObj* pSql, SSqlInfo* pInfo);
H
hjxilinx 已提交
54
static char*   getAccountId(SSqlObj* pSql);
H
hzcheng 已提交
55

H
hjxilinx 已提交
56
static bool has(tFieldList* pFieldList, int32_t startIdx, const char* name);
H
hzcheng 已提交
57 58 59 60 61
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);

62
static int32_t setObjFullName(char* fullName, const char* account, SSQLToken* pDB, SSQLToken* tableName, int32_t* len);
H
hzcheng 已提交
63

H
hjxilinx 已提交
64
static void getColumnName(tSQLExprItem* pItem, char* resultFieldName, int32_t nameLength);
H
hzcheng 已提交
65 66
static void getRevisedName(char* resultFieldName, int32_t functionId, int32_t maxLen, char* columnName);

67
static int32_t addExprAndResultField(SQueryInfo* pQueryInfo, int32_t colIdx, tSQLExprItem* pItem);
68 69
static int32_t insertResultField(SQueryInfo* pQueryInfo, int32_t outputIndex, SColumnList* pIdList, int16_t bytes,
                                 int8_t type, char* fieldName);
S
slguan 已提交
70
static int32_t changeFunctionID(int32_t optr, int16_t* functionId);
H
hjxilinx 已提交
71
static int32_t parseSelectClause(SSqlCmd* pCmd, tSQLExprList* pSelection, bool isMetric);
H
hzcheng 已提交
72

73
static bool validateIpAddress(const char* ip, size_t size);
74 75 76
static bool hasUnsupportFunctionsForMetricQuery(SQueryInfo* pQueryInfo);
static bool functionCompatibleCheck(SQueryInfo* pQueryInfo);
static void setColumnOffsetValueInResultset(SQueryInfo* pQueryInfo);
H
hzcheng 已提交
77

78
static int32_t parseGroupbyClause(SQueryInfo* pQueryInfo, tVariantList* pList, SSqlCmd* pCmd);
H
hzcheng 已提交
79

80 81
static int32_t parseIntervalClause(SQueryInfo* pQueryInfo, SQuerySQL* pQuerySql);
static int32_t setSlidingClause(SQueryInfo* pQueryInfo, SQuerySQL* pQuerySql);
H
hzcheng 已提交
82

83
static int32_t addProjectionExprAndResultField(SQueryInfo* pQueryInfo, tSQLExprItem* pItem);
H
hzcheng 已提交
84

S
slguan 已提交
85
static int32_t parseWhereClause(SSqlObj* pSql, tSQLExpr** pExpr);
86 87
static int32_t parseFillClause(SQueryInfo* pQueryInfo, SQuerySQL* pQuerySQL);
static int32_t parseOrderbyClause(SQueryInfo* pQueryInfo, SQuerySQL* pQuerySql, SSchema* pSchema, int32_t numOfCols);
H
hzcheng 已提交
88

89
static int32_t tsRewriteFieldNameIfNecessary(SQueryInfo* pQueryInfo);
H
hzcheng 已提交
90
static int32_t setAlterTableInfo(SSqlObj* pSql, struct SSqlInfo* pInfo);
91
static int32_t validateSqlFunctionInStreamSql(SQueryInfo* pQueryInfo);
S
slguan 已提交
92
static int32_t buildArithmeticExprString(tSQLExpr* pExpr, char** exprString);
93
static int32_t validateFunctionsInIntervalOrGroupbyQuery(SQueryInfo* pQueryInfo);
S
slguan 已提交
94
static int32_t validateArithmeticSQLExpr(tSQLExpr* pExpr, SSchema* pSchema, int32_t numOfCols, SColumnIdListRes* pList);
H
hzcheng 已提交
95
static int32_t validateDNodeConfig(tDCLSQL* pOptions);
S
slguan 已提交
96
static int32_t validateLocalConfig(tDCLSQL* pOptions);
H
hzcheng 已提交
97 98
static int32_t validateColumnName(char* name);
static int32_t setKillInfo(SSqlObj* pSql, struct SSqlInfo* pInfo);
S
slguan 已提交
99

H
hjxilinx 已提交
100
static bool validateOneTags(SSqlCmd* pCmd, TAOS_FIELD* pTagField);
101 102
static bool hasTimestampForPointInterpQuery(SQueryInfo* pQueryInfo);
static void updateTagColumnIndex(SQueryInfo* pQueryInfo, int32_t tableIndex);
S
slguan 已提交
103

104
static int32_t parseLimitClause(SSqlObj* pSql, int32_t subClauseIndex, SQuerySQL* pQuerySql);
H
hjxilinx 已提交
105
static int32_t parseCreateDBOptions(SSqlCmd* pCmd, SCreateDBInfo* pCreateDbSql);
106
static int32_t getColumnIndexByNameEx(SSQLToken* pToken, SQueryInfo* pQueryInfo, SColumnIndex* pIndex);
107
static int32_t getTableIndexByName(SSQLToken* pToken, SQueryInfo* pQueryInfo, SColumnIndex* pIndex);
S
slguan 已提交
108 109
static int32_t optrToString(tSQLExpr* pExpr, char** exprString);

110 111 112
static int32_t getMeterIndex(SSQLToken* pTableToken, SQueryInfo* pQueryInfo, SColumnIndex* pIndex);
static int32_t doFunctionsCompatibleCheck(SSqlCmd* pCmd, SQueryInfo* pQueryInfo);
static int32_t doLocalQueryProcess(SQuerySQL* pQuerySql, SSqlCmd* pCmd, int32_t subClauseIndex);
H
hjxilinx 已提交
113
static int32_t tscCheckCreateDbParams(SSqlCmd* pCmd, SCreateDbMsg* pCreate);
H
hjxilinx 已提交
114

S
slguan 已提交
115
static SColumnList getColumnList(int32_t num, int16_t tableIndex, int32_t columnIndex);
H
hjxilinx 已提交
116

117
static int32_t doCheckForCreateTable(SSqlObj* pSql, int32_t subClauseIndex, SSqlInfo* pInfo);
118 119 120 121
static int32_t doCheckForCreateFromStable(SSqlObj* pSql, SSqlInfo* pInfo);
static int32_t doCheckForStream(SSqlObj* pSql, SSqlInfo* pInfo);
static int32_t doCheckForQuery(SSqlObj* pSql, SQuerySQL* pQuerySql, int32_t index);

H
hjxilinx 已提交
122 123 124 125
/*
 * Used during parsing query sql. Since the query sql usually small in length, error position
 * is not needed in the final error message.
 */
126 127
static int32_t invalidSqlErrMsg(char* dstBuffer, const char* errMsg) {
  return tscInvalidSQLErrMsg(dstBuffer, errMsg, NULL);
H
hjxilinx 已提交
128 129
}

130
static int32_t tscQueryOnlyMetricTags(SQueryInfo* pQueryInfo, bool* queryOnMetricTags) {
131
  assert(QUERY_IS_STABLE_QUERY(pQueryInfo->type));
H
hzcheng 已提交
132 133

  *queryOnMetricTags = true;
134 135
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
H
hzcheng 已提交
136

S
slguan 已提交
137 138
    if (pExpr->functionId != TSDB_FUNC_TAGPRJ &&
        !(pExpr->functionId == TSDB_FUNC_COUNT && pExpr->colInfo.colIdx == TSDB_TBNAME_COLUMN_INDEX)) {
H
hzcheng 已提交
139 140 141 142 143 144 145 146
      *queryOnMetricTags = false;
      break;
    }
  }

  return TSDB_CODE_SUCCESS;
}

147
static int setColumnFilterInfoForTimestamp(SQueryInfo* pQueryInfo, tVariant* pVar) {
S
slguan 已提交
148 149 150 151 152
  int64_t     time = 0;
  const char* msg = "invalid timestamp";

  strdequote(pVar->pz);
  char*           seg = strnchr(pVar->pz, '-', pVar->nLen, false);
153
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
S
slguan 已提交
154 155 156

  if (seg != NULL) {
    if (taosParseTime(pVar->pz, &time, pVar->nLen, pMeterMetaInfo->pMeterMeta->precision) != TSDB_CODE_SUCCESS) {
157
      return invalidSqlErrMsg(pQueryInfo->msg, msg);
S
slguan 已提交
158 159 160
    }
  } else {
    if (tVariantDump(pVar, (char*)&time, TSDB_DATA_TYPE_BIGINT)) {
161
      return invalidSqlErrMsg(pQueryInfo->msg, msg);
S
slguan 已提交
162 163 164 165 166 167 168 169 170
    }
  }

  tVariantDestroy(pVar);
  tVariantCreateFromBinary(pVar, (char*)&time, 0, TSDB_DATA_TYPE_BIGINT);

  return TSDB_CODE_SUCCESS;
}

171 172 173 174 175 176
static int32_t handlePassword(SSqlCmd* pCmd, SSQLToken* pPwd) {
  const char* msg1 = "password can not be empty";
  const char* msg2 = "name or password too long";
  const char* msg3 = "password needs single quote marks enclosed";

  if (pPwd->type != TK_STRING) {
177
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
178 179 180 181 182 183 184
  }

  strdequote(pPwd->z);
  strtrim(pPwd->z);  // trim space before and after passwords
  pPwd->n = strlen(pPwd->z);

  if (pPwd->n <= 0) {
185
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
186 187 188
  }

  if (pPwd->n > TSDB_PASSWORD_LEN) {
189
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
190 191 192 193 194
  }

  return TSDB_CODE_SUCCESS;
}

H
hzcheng 已提交
195 196 197 198 199 200
// 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;
  }

201
  SSqlCmd*    pCmd = &(pSql->cmd);
202
  SQueryInfo* pQueryInfo = NULL;
H
hzcheng 已提交
203

204
  if (!pInfo->valid) {
205
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), pInfo->pzErrMsg);
H
hzcheng 已提交
206 207
  }

208
  int32_t code = tscGetQueryInfoDetailSafely(pCmd, 0, &pQueryInfo);
209 210

  assert(pQueryInfo->numOfTables == 0);
211
  SMeterMetaInfo* pMeterMetaInfo = tscAddEmptyMeterMetaInfo(pQueryInfo);
212

213 214 215 216 217 218 219 220
  pCmd->command = pInfo->type;

  switch (pInfo->type) {
    case TSDB_SQL_DROP_TABLE:
    case TSDB_SQL_DROP_USER:
    case TSDB_SQL_DROP_ACCT:
    case TSDB_SQL_DROP_DNODE:
    case TSDB_SQL_DROP_DB: {
221 222
      const char* msg1 = "invalid ip address";
      const char* msg2 = "invalid name";
223
      const char* msg3 = "param name too long";
H
hzcheng 已提交
224 225

      SSQLToken* pzName = &pInfo->pDCLInfo->a[0];
226
      if ((pInfo->type != TSDB_SQL_DROP_DNODE) && (tscValidateName(pzName) != TSDB_CODE_SUCCESS)) {
227
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
H
hzcheng 已提交
228 229
      }

230 231
      if (pInfo->type == TSDB_SQL_DROP_DB) {
        assert(pInfo->pDCLInfo->nTokens == 1);
H
hzcheng 已提交
232

233
        code = setObjFullName(pMeterMetaInfo->name, getAccountId(pSql), pzName, NULL, NULL);
H
hzcheng 已提交
234
        if (code != TSDB_CODE_SUCCESS) {
235
          return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
H
hzcheng 已提交
236 237
        }

238 239
      } else if (pInfo->type == TSDB_SQL_DROP_TABLE) {
        assert(pInfo->pDCLInfo->nTokens == 1);
H
hzcheng 已提交
240

241
        if (setMeterID(pMeterMetaInfo, pzName, pSql) != TSDB_CODE_SUCCESS) {
242
          return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
H
hzcheng 已提交
243
        }
244 245
      } else if (pInfo->type == TSDB_SQL_DROP_DNODE) {
        if (!validateIpAddress(pzName->z, pzName->n)) {
246
          return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
H
hzcheng 已提交
247 248
        }

249 250 251
        strncpy(pMeterMetaInfo->name, pzName->z, pzName->n);
      } else {  // drop user
        if (pzName->n > TSDB_USER_LEN) {
252
          return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
H
hzcheng 已提交
253 254
        }

S
slguan 已提交
255
        strncpy(pMeterMetaInfo->name, pzName->z, pzName->n);
H
hzcheng 已提交
256 257
      }

258 259
      break;
    }
H
hzcheng 已提交
260

261 262 263
    case TSDB_SQL_USE_DB: {
      const char* msg = "invalid db name";
      SSQLToken*  pToken = &pInfo->pDCLInfo->a[0];
S
slguan 已提交
264 265

      if (tscValidateName(pToken) != TSDB_CODE_SUCCESS) {
266
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hzcheng 已提交
267 268
      }

S
slguan 已提交
269
      int32_t ret = setObjFullName(pMeterMetaInfo->name, getAccountId(pSql), pToken, NULL, NULL);
H
hzcheng 已提交
270
      if (ret != TSDB_CODE_SUCCESS) {
271
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hzcheng 已提交
272 273 274 275 276
      }

      break;
    }

277 278
    case TSDB_SQL_RESET_CACHE: {
      return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
279 280
    }

281 282 283
    case TSDB_SQL_SHOW: {
      if (setShowInfo(pSql, pInfo) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
284 285
      }

286 287 288 289 290 291 292 293
      break;
    }

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

294
      SCreateDBInfo* pCreateDB = &(pInfo->pDCLInfo->dbOpt);
H
hzcheng 已提交
295
      if (tscValidateName(&pCreateDB->dbname) != TSDB_CODE_SUCCESS) {
296
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
H
hzcheng 已提交
297 298
      }

S
slguan 已提交
299
      int32_t ret = setObjFullName(pMeterMetaInfo->name, getAccountId(pSql), &(pCreateDB->dbname), NULL, NULL);
H
hzcheng 已提交
300
      if (ret != TSDB_CODE_SUCCESS) {
301
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
H
hzcheng 已提交
302 303
      }

H
hjxilinx 已提交
304
      if (parseCreateDBOptions(pCmd, pCreateDB) != TSDB_CODE_SUCCESS) {
305
        return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
306 307 308 309 310
      }

      break;
    }

311
    case TSDB_SQL_CREATE_DNODE: {  // todo parse hostname
S
slguan 已提交
312 313
      const char* msg = "invalid ip address";

314
      if (pInfo->pDCLInfo->nTokens > 1) {
315
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
S
slguan 已提交
316 317
      }

318 319
      SSQLToken* pIpAddr = &pInfo->pDCLInfo->a[0];
      if (!validateIpAddress(pIpAddr->z, pIpAddr->n)) {
320
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
S
slguan 已提交
321 322 323 324 325
      }

      break;
    }

326 327 328 329 330
    case TSDB_SQL_CREATE_ACCT:
    case TSDB_SQL_ALTER_ACCT: {
      const char* msg1 = "invalid state option, available options[no, r, w, all]";
      const char* msg2 = "invalid user/account name";
      const char* msg3 = "name too long";
H
hzcheng 已提交
331

332 333
      SSQLToken* pName = &pInfo->pDCLInfo->user.user;
      SSQLToken* pPwd = &pInfo->pDCLInfo->user.passwd;
H
hzcheng 已提交
334

335 336
      if (handlePassword(pCmd, pPwd) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
337 338
      }

339
      if (pName->n > TSDB_USER_LEN) {
340
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
H
hzcheng 已提交
341 342
      }

343
      if (tscValidateName(pName) != TSDB_CODE_SUCCESS) {
344
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
H
hzcheng 已提交
345 346 347
      }

      SCreateAcctSQL* pAcctOpt = &pInfo->pDCLInfo->acctOpt;
348
      if (pAcctOpt->stat.n > 0) {
H
hzcheng 已提交
349 350 351 352 353
        if (pAcctOpt->stat.z[0] == 'r' && pAcctOpt->stat.n == 1) {
        } else if (pAcctOpt->stat.z[0] == 'w' && pAcctOpt->stat.n == 1) {
        } else if (strncmp(pAcctOpt->stat.z, "all", 3) == 0 && pAcctOpt->stat.n == 3) {
        } else if (strncmp(pAcctOpt->stat.z, "no", 2) == 0 && pAcctOpt->stat.n == 2) {
        } else {
354
          return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
H
hzcheng 已提交
355 356
        }
      }
357

H
hzcheng 已提交
358 359 360
      break;
    }

361
    case TSDB_SQL_DESCRIBE_TABLE: {
S
slguan 已提交
362
      SSQLToken*  pToken = &pInfo->pDCLInfo->a[0];
363
      const char* msg2 = "table name is too long";
H
hjxilinx 已提交
364
      const char* msg1 = "invalid table name";
H
hzcheng 已提交
365

S
slguan 已提交
366
      if (tscValidateName(pToken) != TSDB_CODE_SUCCESS) {
367
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
368
      }
S
slguan 已提交
369

H
hzcheng 已提交
370
      if (pToken->n > TSDB_METER_NAME_LEN) {
371
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
H
hzcheng 已提交
372 373
      }

374
      if (setMeterID(pMeterMetaInfo, pToken, pSql) != TSDB_CODE_SUCCESS) {
375
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
H
hzcheng 已提交
376 377
      }

378
      return tscGetMeterMeta(pSql, pMeterMetaInfo);
H
hzcheng 已提交
379 380
    }

381
    case TSDB_SQL_CFG_DNODE: {
382 383
      const char* msg1 = "invalid ip address";
      const char* msg2 = "invalid configure options or values";
H
hzcheng 已提交
384

385 386 387
      /* validate the ip address */
      tDCLSQL* pDCL = pInfo->pDCLInfo;
      if (!validateIpAddress(pDCL->a[0].z, pDCL->a[0].n)) {
388
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
H
hzcheng 已提交
389 390
      }

391 392
      /* validate the parameter names and options */
      if (validateDNodeConfig(pDCL) != TSDB_CODE_SUCCESS) {
393
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
H
hzcheng 已提交
394 395
      }

396 397
      char* pMsg = pCmd->payload + tsRpcHeadSize;
      pMsg += sizeof(SMgmtHead);
H
hzcheng 已提交
398

399 400
      SCfgMsg* pCfg = (SCfgMsg*)pMsg;
      strncpy(pCfg->ip, pDCL->a[0].z, pDCL->a[0].n);
H
hzcheng 已提交
401

402
      strncpy(pCfg->config, pDCL->a[1].z, pDCL->a[1].n);
H
hzcheng 已提交
403

404 405 406 407
      if (pDCL->nTokens == 3) {
        pCfg->config[pDCL->a[1].n] = ' ';  // add sep
        strncpy(&pCfg->config[pDCL->a[1].n + 1], pDCL->a[2].z, pDCL->a[2].n);
      }
H
hzcheng 已提交
408

409 410
      break;
    }
H
hzcheng 已提交
411

412 413 414 415 416 417
    case TSDB_SQL_CREATE_USER:
    case TSDB_SQL_ALTER_USER: {
      const char* msg5 = "invalid user rights";
      const char* msg7 = "not support options";
      const char* msg2 = "invalid user/account name";
      const char* msg3 = "name too long";
H
hzcheng 已提交
418

419 420
      pCmd->command = pInfo->type;
      tDCLSQL* pDCL = pInfo->pDCLInfo;
H
hzcheng 已提交
421

422 423 424
      SUserInfo* pUser = &pInfo->pDCLInfo->user;
      SSQLToken* pName = &pUser->user;
      SSQLToken* pPwd = &pUser->passwd;
H
hzcheng 已提交
425

426
      if (pName->n > TSDB_USER_LEN) {
427
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
428
      }
H
hzcheng 已提交
429

430
      if (tscValidateName(pName) != TSDB_CODE_SUCCESS) {
431
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
432
      }
H
hzcheng 已提交
433

434 435 436 437 438 439 440 441
      if (pCmd->command == TSDB_SQL_CREATE_USER) {
        if (handlePassword(pCmd, pPwd) != TSDB_CODE_SUCCESS) {
          return TSDB_CODE_INVALID_SQL;
        }
      } else {
        if (pUser->type == TSDB_ALTER_USER_PASSWD) {
          if (handlePassword(pCmd, pPwd) != TSDB_CODE_SUCCESS) {
            return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
442
          }
443 444
        } else if (pUser->type == TSDB_ALTER_USER_PRIVILEGES) {
          assert(pPwd == NULL);
H
hzcheng 已提交
445

446
          if (strncasecmp(pUser->privilege.z, "super", 5) == 0 && pDCL->a[1].n == 5) {
H
hzcheng 已提交
447 448 449 450 451 452
            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 {
453
            return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg5);
H
hzcheng 已提交
454 455
          }
        } else {
456
          return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg7);
H
hzcheng 已提交
457 458
        }
      }
459

H
hzcheng 已提交
460 461
      break;
    }
462 463

    case TSDB_SQL_CFG_LOCAL: {
S
slguan 已提交
464 465 466 467 468
      tDCLSQL*    pDCL = pInfo->pDCLInfo;
      const char* msg = "invalid configure options or values";

      // validate the parameter names and options
      if (validateLocalConfig(pDCL) != TSDB_CODE_SUCCESS) {
469
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
S
slguan 已提交
470 471 472 473 474 475 476
      }

      strncpy(pCmd->payload, pDCL->a[0].z, pDCL->a[0].n);
      if (pDCL->nTokens == 2) {
        pCmd->payload[pDCL->a[0].n] = ' ';  // add sep
        strncpy(&pCmd->payload[pDCL->a[0].n + 1], pDCL->a[1].z, pDCL->a[1].n);
      }
H
hzcheng 已提交
477 478 479 480

      break;
    }

481 482
    case TSDB_SQL_CREATE_TABLE: {
      SCreateTableSQL* pCreateTable = pInfo->pCreateTableInfo;
H
hzcheng 已提交
483

484
      if (pCreateTable->type == TSQL_CREATE_TABLE || pCreateTable->type == TSQL_CREATE_STABLE) {
485
        if ((code = doCheckForCreateTable(pSql, 0, pInfo)) != TSDB_CODE_SUCCESS) {
486
          return code;
H
hzcheng 已提交
487 488
        }

489 490 491
      } else if (pCreateTable->type == TSQL_CREATE_TABLE_FROM_STABLE) {
        if ((code = doCheckForCreateFromStable(pSql, pInfo)) != TSDB_CODE_SUCCESS) {
          return code;
H
hzcheng 已提交
492 493
        }

494 495 496
      } else if (pCreateTable->type == TSQL_CREATE_STREAM) {
        if ((code = doCheckForStream(pSql, pInfo)) != TSDB_CODE_SUCCESS) {
          return code;
S
slguan 已提交
497
        }
H
hzcheng 已提交
498 499 500 501 502
      }

      break;
    }

503
    case TSDB_SQL_SELECT: {
504 505 506
      assert(pCmd->numOfClause == 1);

      for (int32_t i = pCmd->numOfClause; i < pInfo->subclauseInfo.numOfClause; ++i) {
507 508 509 510
        SQueryInfo* pqi = NULL;
        if ((code = tscGetQueryInfoDetailSafely(pCmd, i, &pqi)) != TSDB_CODE_SUCCESS) {
          return code;
        }
511 512 513 514
      }

      assert(pCmd->numOfClause == pInfo->subclauseInfo.numOfClause);
      for (int32_t i = 0; i < pInfo->subclauseInfo.numOfClause; ++i) {
515
        SQuerySQL* pQuerySql = pInfo->subclauseInfo.pClause[i];
516

517 518
        if ((code = doCheckForQuery(pSql, pQuerySql, i)) != TSDB_CODE_SUCCESS) {
          return code;
H
hzcheng 已提交
519 520
        }
      }
521 522

      return TSDB_CODE_SUCCESS;  // do not build query message here
523
    }
H
hzcheng 已提交
524

525 526 527
    case TSDB_SQL_ALTER_TABLE: {
      if ((code = setAlterTableInfo(pSql, pInfo)) != TSDB_CODE_SUCCESS) {
        return code;
H
hzcheng 已提交
528 529 530 531 532
      }

      break;
    }

533 534 535 536
    case TSDB_SQL_KILL_QUERY:
    case TSDB_SQL_KILL_STREAM:
    case TSDB_SQL_KILL_CONNECTION: {
      if ((code = setKillInfo(pSql, pInfo)) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
537 538 539 540 541 542 543
        return code;
      }

      break;
    }

    default:
544
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), "not support sql expression");
H
hzcheng 已提交
545 546
  }

547
  return tscBuildMsg[pCmd->command](pSql, pInfo);
H
hzcheng 已提交
548 549
}

S
slguan 已提交
550 551 552 553
/*
 * if the top/bottom exists, only tags columns, tbname column, and primary timestamp column
 * are available.
 */
554 555 556
static bool isTopBottomQuery(SQueryInfo* pQueryInfo) {
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    int32_t functionId = tscSqlExprGet(pQueryInfo, i)->functionId;
S
slguan 已提交
557 558 559 560

    if (functionId == TSDB_FUNC_TOP || functionId == TSDB_FUNC_BOTTOM) {
      return true;
    }
H
hzcheng 已提交
561 562
  }

S
slguan 已提交
563
  return false;
H
hzcheng 已提交
564 565
}

566
int32_t parseIntervalClause(SQueryInfo* pQueryInfo, SQuerySQL* pQuerySql) {
S
slguan 已提交
567 568
  const char* msg1 = "invalid query expression";
  const char* msg2 = "interval cannot be less than 10 ms";
569

570
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
S
slguan 已提交
571

H
hjxilinx 已提交
572
  if (pQuerySql->interval.type == 0 || pQuerySql->interval.n == 0) {
H
hzcheng 已提交
573 574 575 576 577
    return TSDB_CODE_SUCCESS;
  }

  // interval is not null
  SSQLToken* t = &pQuerySql->interval;
578
  if (getTimestampInUsFromStr(t->z, t->n, &pQueryInfo->nAggTimeInterval) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
579 580 581 582
    return TSDB_CODE_INVALID_SQL;
  }

  /* revised the time precision according to the flag */
S
slguan 已提交
583
  if (pMeterMetaInfo->pMeterMeta->precision == TSDB_TIME_PRECISION_MILLI) {
584
    pQueryInfo->nAggTimeInterval = pQueryInfo->nAggTimeInterval / 1000;
H
hzcheng 已提交
585 586 587
  }

  /* parser has filter the illegal type, no need to check here */
588
  pQueryInfo->intervalTimeUnit = pQuerySql->interval.z[pQuerySql->interval.n - 1];
H
hzcheng 已提交
589 590

  // interval cannot be less than 10 milliseconds
591 592
  if (pQueryInfo->nAggTimeInterval < tsMinIntervalTime) {
    return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
593 594 595
  }

  // for top/bottom + interval query, we do not add additional timestamp column in the front
596
  if (isTopBottomQuery(pQueryInfo)) {
H
hzcheng 已提交
597 598 599
    return TSDB_CODE_SUCCESS;
  }

S
slguan 已提交
600
  // check the invalid sql expresssion: select count(tbname)/count(tag1)/count(tag2) from super_table interval(1d);
601 602
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
603
    if (pExpr->functionId == TSDB_FUNC_COUNT && TSDB_COL_IS_TAG(pExpr->colInfo.flag)) {
604
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
605 606 607 608
    }
  }

  // need to add timestamp column in result set, if interval is existed
609
  uint64_t uid = tscSqlExprGet(pQueryInfo, 0)->uid;
S
slguan 已提交
610 611

  int32_t tableIndex = COLUMN_INDEX_INITIAL_VAL;
612 613
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
    pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, i);
S
slguan 已提交
614 615 616 617 618 619 620 621 622 623 624
    if (pMeterMetaInfo->pMeterMeta->uid == uid) {
      tableIndex = i;
      break;
    }
  }

  if (tableIndex == COLUMN_INDEX_INITIAL_VAL) {
    return TSDB_CODE_INVALID_SQL;
  }

  SColumnIndex index = {tableIndex, PRIMARYKEY_TIMESTAMP_COL_INDEX};
625
  tscSqlExprInsert(pQueryInfo, 0, TSDB_FUNC_TS, &index, TSDB_DATA_TYPE_TIMESTAMP, TSDB_KEYSIZE, TSDB_KEYSIZE);
H
hzcheng 已提交
626

S
slguan 已提交
627
  SColumnList ids = getColumnList(1, 0, PRIMARYKEY_TIMESTAMP_COL_INDEX);
628

629
  return insertResultField(pQueryInfo, 0, &ids, TSDB_KEYSIZE, TSDB_DATA_TYPE_TIMESTAMP, aAggs[TSDB_FUNC_TS].aName);
H
hzcheng 已提交
630 631
}

632
int32_t setSlidingClause(SQueryInfo* pQueryInfo, SQuerySQL* pQuerySql) {
633 634
  const char* msg0 = "sliding value too small";
  const char* msg1 = "sliding value no larger than the interval value";
H
hzcheng 已提交
635

636
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
S
slguan 已提交
637
  SSQLToken*      pSliding = &pQuerySql->sliding;
H
hzcheng 已提交
638 639

  if (pSliding->n != 0) {
640
    getTimestampInUsFromStr(pSliding->z, pSliding->n, &pQueryInfo->nSlidingTime);
S
slguan 已提交
641
    if (pMeterMetaInfo->pMeterMeta->precision == TSDB_TIME_PRECISION_MILLI) {
642
      pQueryInfo->nSlidingTime /= 1000;
H
hzcheng 已提交
643 644
    }

645 646
    if (pQueryInfo->nSlidingTime < tsMinSlidingTime) {
      return invalidSqlErrMsg(pQueryInfo->msg, msg0);
H
hzcheng 已提交
647 648
    }

649 650
    if (pQueryInfo->nSlidingTime > pQueryInfo->nAggTimeInterval) {
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
651 652 653 654 655 656
    }
  }

  return TSDB_CODE_SUCCESS;
}

657
int32_t setMeterID(SMeterMetaInfo* pMeterMetaInfo, SSQLToken* pzTableName, SSqlObj* pSql) {
658
  const char* msg = "name too long";
H
hzcheng 已提交
659

660 661
  SSqlCmd* pCmd = &pSql->cmd;
  int32_t  code = TSDB_CODE_SUCCESS;
S
slguan 已提交
662

663 664 665 666 667 668 669
  // backup the old name in pMeterMetaInfo
  size_t size = strlen(pMeterMetaInfo->name);
  char* oldName = NULL;
  if (size > 0) {
    oldName = strdup(pMeterMetaInfo->name);
  }
  
H
hzcheng 已提交
670
  if (hasSpecifyDB(pzTableName)) {
671
    // db has been specified in sql string so we ignore current db path
S
slguan 已提交
672 673
    code = setObjFullName(pMeterMetaInfo->name, getAccountId(pSql), NULL, pzTableName, NULL);
  } else {  // get current DB name first, then set it into path
H
hzcheng 已提交
674 675 676
    SSQLToken t = {0};
    getCurrentDBName(pSql, &t);

S
slguan 已提交
677
    code = setObjFullName(pMeterMetaInfo->name, NULL, &t, pzTableName, NULL);
H
hzcheng 已提交
678 679
  }

S
slguan 已提交
680
  if (code != TSDB_CODE_SUCCESS) {
681
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hzcheng 已提交
682 683
  }

684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
  if (code != TSDB_CODE_SUCCESS) {
    free(oldName);
    return code;
  }
  
  /*
   * the old name exists and is not equalled to the new name. Release the metermeta/metricmeta
   * that are corresponding to the old name for the new table name.
   */
  if (size > 0) {
    if (strncasecmp(oldName, pMeterMetaInfo->name, tListLen(pMeterMetaInfo->name)) != 0) {
      tscClearMeterMetaInfo(pMeterMetaInfo, false);
    }
  } else {
    assert(pMeterMetaInfo->pMeterMeta == NULL && pMeterMetaInfo->pMetricMeta == NULL);
  }
  
  tfree(oldName);
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
703 704 705 706 707
}

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

708 709 710 711 712 713 714
  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 已提交
715 716 717

  // number of fields no less than 2
  if (pFieldList->nField <= 1 || pFieldList->nField > TSDB_MAX_COLUMNS) {
718
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hzcheng 已提交
719 720 721 722 723
    return false;
  }

  // first column must be timestamp
  if (pFieldList->p[0].type != TSDB_DATA_TYPE_TIMESTAMP) {
724
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
H
hzcheng 已提交
725 726 727 728 729 730 731 732 733 734
    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) {
735
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
H
hzcheng 已提交
736 737 738 739 740 741 742
    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) {
743
      invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg4);
H
hzcheng 已提交
744 745 746 747 748
      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))) {
749
      invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg5);
H
hzcheng 已提交
750 751 752 753
      return false;
    }

    if (validateColumnName(pField->name) != TSDB_CODE_SUCCESS) {
754
      invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg6);
H
hzcheng 已提交
755 756 757 758
      return false;
    }

    if (has(pFieldList, i + 1, pFieldList->p[i].name) == true) {
759
      invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
H
hzcheng 已提交
760 761 762 763 764 765 766 767 768 769
      return false;
    }
  }

  return true;
}

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

770 771 772 773 774 775 776
  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 已提交
777 778 779

  // number of fields at least 1
  if (pTagsList->nField < 1 || pTagsList->nField > TSDB_MAX_TAGS) {
780
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
H
hzcheng 已提交
781 782 783 784 785 786 787 788 789 790
    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) {
791
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
H
hzcheng 已提交
792 793 794 795 796 797
    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) {
798
      invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
H
hzcheng 已提交
799 800 801 802 803 804 805
      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) {
806
      invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg4);
H
hzcheng 已提交
807 808 809 810
      return false;
    }

    if (pTagsList->p[i].type < TSDB_DATA_TYPE_BOOL || pTagsList->p[i].type > TSDB_DATA_TYPE_NCHAR) {
811
      invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg5);
H
hzcheng 已提交
812 813 814 815 816
      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)) {
817
      invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg7);
H
hzcheng 已提交
818 819 820 821
      return false;
    }

    if (validateColumnName(pTagsList->p[i].name) != TSDB_CODE_SUCCESS) {
822
      invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg6);
H
hzcheng 已提交
823 824 825 826
      return false;
    }

    if (has(pTagsList, i + 1, pTagsList->p[i].name) == true) {
827
      invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
H
hzcheng 已提交
828 829 830 831 832 833 834 835 836 837 838
      return false;
    }
  }

  return true;
}

/*
 * tags name /column name is truncated in sql.y
 */
bool validateOneTags(SSqlCmd* pCmd, TAOS_FIELD* pTagField) {
839 840 841 842 843 844
  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 已提交
845

846
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfo(pCmd, 0, 0);
S
slguan 已提交
847
  SMeterMeta*     pMeterMeta = pMeterMetaInfo->pMeterMeta;
H
hzcheng 已提交
848 849 850 851 852 853

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

854
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hzcheng 已提交
855 856 857 858 859
    return false;
  }

  // no timestamp allowable
  if (pTagField->type == TSDB_DATA_TYPE_TIMESTAMP) {
860
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
H
hzcheng 已提交
861 862 863 864
    return false;
  }

  if (pTagField->type < TSDB_DATA_TYPE_BOOL && pTagField->type > TSDB_DATA_TYPE_NCHAR) {
865
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg6);
H
hzcheng 已提交
866 867 868
    return false;
  }

S
slguan 已提交
869
  SSchema* pTagSchema = tsGetTagSchema(pMeterMetaInfo->pMeterMeta);
H
hzcheng 已提交
870 871 872 873 874 875 876 877
  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) {
878
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
H
hzcheng 已提交
879 880 881 882 883
    return false;
  }

  // tags name can not be a keyword
  if (validateColumnName(pTagField->name) != TSDB_CODE_SUCCESS) {
884
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg4);
H
hzcheng 已提交
885 886 887 888 889
    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) {
890
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg5);
H
hzcheng 已提交
891 892 893 894 895 896 897 898
    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) {
899
      invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
H
hzcheng 已提交
900 901 902 903 904 905 906 907
      return false;
    }
  }

  return true;
}

bool validateOneColumn(SSqlCmd* pCmd, TAOS_FIELD* pColField) {
908 909 910 911 912 913
  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 已提交
914

915
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfo(pCmd, 0, 0);
S
slguan 已提交
916
  SMeterMeta*     pMeterMeta = pMeterMetaInfo->pMeterMeta;
H
hzcheng 已提交
917 918 919 920

  // no more max columns
  if (pMeterMeta->numOfColumns >= TSDB_MAX_COLUMNS ||
      pMeterMeta->numOfTags + pMeterMeta->numOfColumns >= TSDB_MAX_COLUMNS) {
921
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
H
hzcheng 已提交
922 923 924 925
    return false;
  }

  if (pColField->type < TSDB_DATA_TYPE_BOOL || pColField->type > TSDB_DATA_TYPE_NCHAR) {
926
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg4);
H
hzcheng 已提交
927 928 929 930
    return false;
  }

  if (validateColumnName(pColField->name) != TSDB_CODE_SUCCESS) {
931
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg5);
H
hzcheng 已提交
932 933 934 935 936 937 938 939 940 941 942
    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) {
943
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg6);
H
hzcheng 已提交
944 945 946 947 948
    return false;
  }

  // length less than TSDB_MAX_BYTES_PER_ROW
  if (nLen + pColField->bytes > TSDB_MAX_BYTES_PER_ROW) {
949
    invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
H
hzcheng 已提交
950 951 952 953 954 955
    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) {
956
      invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
H
hzcheng 已提交
957 958 959 960 961 962 963 964
      return false;
    }
  }

  return true;
}

/* is contained in pFieldList or not */
H
hjxilinx 已提交
965
static bool has(tFieldList* pFieldList, int32_t startIdx, const char* name) {
H
hzcheng 已提交
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
  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;
}

991
int32_t setObjFullName(char* fullName, const char* account, SSQLToken* pDB, SSQLToken* tableName, int32_t* xlen) {
H
hzcheng 已提交
992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033
  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;
  }

  if (xlen != NULL) {
    *xlen = totalLen;
  }
S
slguan 已提交
1034 1035 1036 1037 1038

  if (totalLen < TSDB_METER_ID_LEN) {
    fullName[totalLen] = 0;
  }

H
hzcheng 已提交
1039 1040 1041
  return (totalLen <= TSDB_METER_ID_LEN) ? TSDB_CODE_SUCCESS : TSDB_CODE_INVALID_SQL;
}

S
slguan 已提交
1042
static void extractColumnNameFromString(tSQLExprItem* pItem) {
H
hzcheng 已提交
1043
  if (pItem->pNode->nSQLOptr == TK_STRING) {
S
slguan 已提交
1044
    pItem->pNode->val.nLen = strdequote(pItem->pNode->val.pz);
H
hzcheng 已提交
1045 1046 1047 1048
    pItem->pNode->nSQLOptr = TK_ID;

    SSQLToken* pIdToken = &pItem->pNode->colInfo;
    pIdToken->type = TK_ID;
S
slguan 已提交
1049 1050
    pIdToken->z = pItem->pNode->val.pz;
    pIdToken->n = pItem->pNode->val.nLen;
H
hzcheng 已提交
1051 1052 1053
  }
}

1054
int32_t parseSelectClause(SSqlCmd* pCmd, tSQLExprList* pSelection, bool isSTable) {
H
hzcheng 已提交
1055 1056
  assert(pSelection != NULL && pCmd != NULL);

1057 1058 1059
  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";
1060 1061
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

H
hzcheng 已提交
1062
  for (int32_t i = 0; i < pSelection->nExpr; ++i) {
1063
    int32_t       outputIndex = pQueryInfo->fieldsInfo.numOfOutputCols;
H
hzcheng 已提交
1064 1065
    tSQLExprItem* pItem = &pSelection->a[i];

S
slguan 已提交
1066 1067 1068
    // project on all fields
    if (pItem->pNode->nSQLOptr == TK_ALL || pItem->pNode->nSQLOptr == TK_ID || pItem->pNode->nSQLOptr == TK_STRING) {
      // it is actually a function, but the function name is invalid
H
hzcheng 已提交
1069 1070 1071 1072
      if (pItem->pNode->nSQLOptr == TK_ID && (pItem->pNode->colInfo.z == NULL && pItem->pNode->colInfo.n == 0)) {
        return TSDB_CODE_INVALID_SQL;
      }

S
slguan 已提交
1073 1074
      // if the name of column is quoted, remove it and set the right information for later process
      extractColumnNameFromString(pItem);
1075

1076
      pQueryInfo->type |= TSDB_QUERY_TYPE_PROJECTION_QUERY;
S
slguan 已提交
1077 1078

      // select table_name1.field_name1, table_name2.field_name2  from table_name1, table_name2
1079
      if (addProjectionExprAndResultField(pQueryInfo, pItem) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
1080
        return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
1081 1082
      }
    } else if (pItem->pNode->nSQLOptr >= TK_COUNT && pItem->pNode->nSQLOptr <= TK_LAST_ROW) {
S
slguan 已提交
1083
      // sql function in selection clause, append sql function info in pSqlCmd structure sequentially
1084
      if (addExprAndResultField(pQueryInfo, outputIndex, pItem) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
1085 1086 1087 1088
        return TSDB_CODE_INVALID_SQL;
      }

    } else if (pItem->pNode->nSQLOptr >= TK_PLUS && pItem->pNode->nSQLOptr <= TK_REM) {
S
slguan 已提交
1089
      // arithmetic function in select
1090
      SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
S
slguan 已提交
1091 1092 1093 1094 1095 1096
      SSchema*        pSchema = tsGetSchema(pMeterMetaInfo->pMeterMeta);

      SColumnIdListRes columnList = {.pSchema = pSchema, .numOfCols = pMeterMetaInfo->pMeterMeta->numOfColumns};

      int32_t ret =
          validateArithmeticSQLExpr(pItem->pNode, pSchema, pMeterMetaInfo->pMeterMeta->numOfColumns, &columnList);
H
hzcheng 已提交
1097
      if (ret != TSDB_CODE_SUCCESS) {
1098
        return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
1099 1100 1101 1102 1103
      }

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

S
slguan 已提交
1104
      if (buildArithmeticExprString(pItem->pNode, &p) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
1105 1106 1107 1108
        return TSDB_CODE_INVALID_SQL;
      }

      // expr string is set as the parameter of function
S
slguan 已提交
1109
      SColumnIndex index = {0};
1110
      SSqlExpr*    pExpr = tscSqlExprInsert(pQueryInfo, outputIndex, TSDB_FUNC_ARITHM, &index, TSDB_DATA_TYPE_DOUBLE,
S
slguan 已提交
1111 1112
                                         sizeof(double), sizeof(double));
      addExprParams(pExpr, arithmeticExprStr, TSDB_DATA_TYPE_BINARY, strlen(arithmeticExprStr), 0);
H
hzcheng 已提交
1113 1114 1115 1116 1117 1118 1119 1120

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

1121
      insertResultField(pQueryInfo, i, &columnList.list, sizeof(double), TSDB_DATA_TYPE_DOUBLE, pExpr->aliasName);
H
hzcheng 已提交
1122 1123 1124 1125 1126
    } else {
      /*
       * not support such expression
       * e.g., select 12+5 from table_name
       */
1127
      return invalidSqlErrMsg(pQueryInfo->msg, msg3);
H
hzcheng 已提交
1128 1129
    }

1130
    if (pQueryInfo->fieldsInfo.numOfOutputCols > TSDB_MAX_COLUMNS) {
H
hzcheng 已提交
1131 1132 1133 1134
      return TSDB_CODE_INVALID_SQL;
    }
  }

1135 1136
  if (!functionCompatibleCheck(pQueryInfo)) {
    return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
1137 1138
  }

1139 1140 1141
  if (isSTable) {
    pQueryInfo->type |= TSDB_QUERY_TYPE_STABLE_QUERY;
    SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
H
hzcheng 已提交
1142

1143
    if (tscQueryMetricTags(pQueryInfo)) {  // local handle the metric tag query
H
hzcheng 已提交
1144
      pCmd->command = TSDB_SQL_RETRIEVE_TAGS;
S
slguan 已提交
1145
      pCmd->count = pMeterMetaInfo->pMeterMeta->numOfColumns;  // the number of meter schema, tricky.
H
hzcheng 已提交
1146 1147 1148 1149 1150 1151
    }

    /*
     * transfer sql functions that need secondary merge into another format
     * in dealing with metric queries such as: count/first/last
     */
1152
    tscTansformSQLFunctionForSTableQuery(pQueryInfo);
H
hzcheng 已提交
1153

1154
    if (hasUnsupportFunctionsForMetricQuery(pQueryInfo)) {
H
hzcheng 已提交
1155 1156 1157 1158 1159 1160 1161
      return TSDB_CODE_INVALID_SQL;
    }
  }

  return TSDB_CODE_SUCCESS;
}

1162
int32_t insertResultField(SQueryInfo* pQueryInfo, int32_t outputIndex, SColumnList* pIdList, int16_t bytes, int8_t type,
H
hzcheng 已提交
1163
                          char* fieldName) {
S
slguan 已提交
1164
  for (int32_t i = 0; i < pIdList->num; ++i) {
1165
    tscColumnBaseInfoInsert(pQueryInfo, &(pIdList->ids[i]));
H
hzcheng 已提交
1166 1167
  }

1168
  tscFieldInfoSetValue(&pQueryInfo->fieldsInfo, outputIndex, type, fieldName, bytes);
H
hzcheng 已提交
1169 1170 1171
  return TSDB_CODE_SUCCESS;
}

1172 1173 1174
SSqlExpr* doAddProjectCol(SQueryInfo* pQueryInfo, int32_t outputIndex, int32_t colIdx, int32_t tableIndex) {
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, tableIndex);
  SMeterMeta*     pMeterMeta = pMeterMetaInfo->pMeterMeta;
H
hzcheng 已提交
1175

S
slguan 已提交
1176 1177
  SSchema* pSchema = tsGetColumnSchema(pMeterMeta, colIdx);
  int32_t  numOfCols = pMeterMeta->numOfColumns;
H
hzcheng 已提交
1178

S
slguan 已提交
1179
  int16_t functionId = (int16_t)((colIdx >= numOfCols) ? TSDB_FUNC_TAGPRJ : TSDB_FUNC_PRJ);
H
hzcheng 已提交
1180

S
slguan 已提交
1181
  if (functionId == TSDB_FUNC_TAGPRJ) {
1182 1183
    addRequiredTagColumn(pQueryInfo, colIdx - numOfCols, tableIndex);
    pQueryInfo->type = TSDB_QUERY_TYPE_STABLE_QUERY;
S
slguan 已提交
1184
  } else {
1185
    pQueryInfo->type = TSDB_QUERY_TYPE_PROJECTION_QUERY;
H
hzcheng 已提交
1186 1187
  }

S
slguan 已提交
1188 1189
  SColumnIndex index = {tableIndex, colIdx};
  SSqlExpr*    pExpr =
1190
      tscSqlExprInsert(pQueryInfo, outputIndex, functionId, &index, pSchema->type, pSchema->bytes, pSchema->bytes);
S
slguan 已提交
1191 1192

  return pExpr;
H
hzcheng 已提交
1193 1194
}

1195 1196
void addRequiredTagColumn(SQueryInfo* pQueryInfo, int32_t tagColIndex, int32_t tableIndex) {
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, tableIndex);
S
slguan 已提交
1197 1198 1199

  if (pMeterMetaInfo->numOfTags == 0 || pMeterMetaInfo->tagColumnIndex[pMeterMetaInfo->numOfTags - 1] < tagColIndex) {
    pMeterMetaInfo->tagColumnIndex[pMeterMetaInfo->numOfTags++] = tagColIndex;
H
hzcheng 已提交
1200
  } else {  // find the appropriate position
S
slguan 已提交
1201 1202
    for (int32_t i = 0; i < pMeterMetaInfo->numOfTags; ++i) {
      if (tagColIndex > pMeterMetaInfo->tagColumnIndex[i]) {
H
hzcheng 已提交
1203
        continue;
S
slguan 已提交
1204
      } else if (tagColIndex == pMeterMetaInfo->tagColumnIndex[i]) {
H
hzcheng 已提交
1205 1206
        break;
      } else {
S
slguan 已提交
1207 1208
        memmove(&pMeterMetaInfo->tagColumnIndex[i + 1], &pMeterMetaInfo->tagColumnIndex[i],
                sizeof(pMeterMetaInfo->tagColumnIndex[0]) * (pMeterMetaInfo->numOfTags - i));
H
hzcheng 已提交
1209

S
slguan 已提交
1210 1211 1212
        pMeterMetaInfo->tagColumnIndex[i] = tagColIndex;

        pMeterMetaInfo->numOfTags++;
H
hzcheng 已提交
1213 1214 1215 1216 1217 1218
        break;
      }
    }
  }

  // plus one means tbname
S
slguan 已提交
1219
  assert(tagColIndex >= -1 && tagColIndex < TSDB_MAX_TAGS && pMeterMetaInfo->numOfTags <= TSDB_MAX_TAGS + 1);
H
hzcheng 已提交
1220 1221
}

1222 1223
static void addProjectQueryCol(SQueryInfo* pQueryInfo, int32_t startPos, SColumnIndex* pIndex, tSQLExprItem* pItem) {
  SSqlExpr* pExpr = doAddProjectCol(pQueryInfo, startPos, pIndex->columnIndex, pIndex->tableIndex);
H
hzcheng 已提交
1224

1225 1226
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, pIndex->tableIndex);
  SMeterMeta*     pMeterMeta = pMeterMetaInfo->pMeterMeta;
H
hzcheng 已提交
1227

S
slguan 已提交
1228
  SSchema* pSchema = tsGetColumnSchema(pMeterMeta, pIndex->columnIndex);
H
hzcheng 已提交
1229

S
slguan 已提交
1230
  char* colName = (pItem->aliasName == NULL) ? pSchema->name : pItem->aliasName;
H
hzcheng 已提交
1231

S
slguan 已提交
1232 1233 1234
  SColumnList ids = {0};
  ids.num = 1;
  ids.ids[0] = *pIndex;
H
hzcheng 已提交
1235

S
slguan 已提交
1236 1237 1238
  if (pIndex->columnIndex >= pMeterMeta->numOfColumns || pIndex->columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
    ids.num = 0;
  }
H
hzcheng 已提交
1239

1240
  insertResultField(pQueryInfo, startPos, &ids, pExpr->resBytes, pExpr->resType, colName);
S
slguan 已提交
1241
}
H
hzcheng 已提交
1242

1243 1244 1245 1246
void tscAddSpecialColumnForSelect(SQueryInfo* pQueryInfo, int32_t outputColIndex, int16_t functionId,
                                  SColumnIndex* pIndex, SSchema* pColSchema, int16_t flag) {
  SSqlExpr* pExpr = tscSqlExprInsert(pQueryInfo, outputColIndex, functionId, pIndex, pColSchema->type,
                                     pColSchema->bytes, pColSchema->bytes);
H
hzcheng 已提交
1247

S
slguan 已提交
1248 1249 1250 1251
  SColumnList ids = getColumnList(1, pIndex->tableIndex, pIndex->columnIndex);
  if (TSDB_COL_IS_TAG(flag)) {
    ids.num = 0;
  }
H
hzcheng 已提交
1252

1253
  insertResultField(pQueryInfo, outputColIndex, &ids, pColSchema->bytes, pColSchema->type, pColSchema->name);
S
slguan 已提交
1254 1255 1256

  pExpr->colInfo.flag = flag;
  if (TSDB_COL_IS_TAG(flag)) {
1257
    addRequiredTagColumn(pQueryInfo, pIndex->columnIndex, pIndex->tableIndex);
S
slguan 已提交
1258 1259 1260
  }
}

1261 1262
static int32_t doAddProjectionExprAndResultFields(SQueryInfo* pQueryInfo, SColumnIndex* pIndex, int32_t startPos) {
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, pIndex->tableIndex);
S
slguan 已提交
1263 1264 1265 1266 1267

  int32_t     numOfTotalColumns = 0;
  SMeterMeta* pMeterMeta = pMeterMetaInfo->pMeterMeta;
  SSchema*    pSchema = tsGetSchema(pMeterMeta);

1268
  if (UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {
S
slguan 已提交
1269 1270 1271 1272 1273 1274
    numOfTotalColumns = pMeterMeta->numOfColumns + pMeterMeta->numOfTags;
  } else {
    numOfTotalColumns = pMeterMeta->numOfColumns;
  }

  for (int32_t j = 0; j < numOfTotalColumns; ++j) {
1275
    doAddProjectCol(pQueryInfo, startPos + j, j, pIndex->tableIndex);
S
slguan 已提交
1276 1277 1278 1279 1280 1281 1282 1283

    pIndex->columnIndex = j;
    SColumnList ids = {0};
    ids.ids[0] = *pIndex;

    // tag columns do not add to source list
    ids.num = (j >= pMeterMeta->numOfColumns) ? 0 : 1;

1284
    insertResultField(pQueryInfo, startPos + j, &ids, pSchema[j].bytes, pSchema[j].type, pSchema[j].name);
S
slguan 已提交
1285 1286 1287 1288 1289
  }

  return numOfTotalColumns;
}

1290
int32_t addProjectionExprAndResultField(SQueryInfo* pQueryInfo, tSQLExprItem* pItem) {
S
slguan 已提交
1291 1292 1293
  const char* msg0 = "invalid column name";
  const char* msg1 = "tag for table query is not allowed";

1294
  int32_t startPos = pQueryInfo->fieldsInfo.numOfOutputCols;
S
slguan 已提交
1295 1296 1297

  if (pItem->pNode->nSQLOptr == TK_ALL) {  // project on all fields
    SColumnIndex index = COLUMN_INDEX_INITIALIZER;
1298
    if (getTableIndexByName(&pItem->pNode->colInfo, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
1299 1300 1301 1302 1303
      return TSDB_CODE_INVALID_SQL;
    }

    // all meters columns are required
    if (index.tableIndex == COLUMN_INDEX_INITIAL_VAL) {  // all table columns are required.
1304
      for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
S
slguan 已提交
1305
        index.tableIndex = i;
1306
        int32_t inc = doAddProjectionExprAndResultFields(pQueryInfo, &index, startPos);
S
slguan 已提交
1307
        startPos += inc;
H
hzcheng 已提交
1308 1309
      }
    } else {
1310
      doAddProjectionExprAndResultFields(pQueryInfo, &index, startPos);
S
slguan 已提交
1311 1312 1313 1314
    }
  } else if (pItem->pNode->nSQLOptr == TK_ID) {  // simple column projection query
    SColumnIndex index = COLUMN_INDEX_INITIALIZER;

1315 1316
    if (getColumnIndexByNameEx(&pItem->pNode->colInfo, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
      return invalidSqlErrMsg(pQueryInfo->msg, msg0);
S
slguan 已提交
1317
    }
H
hzcheng 已提交
1318

S
slguan 已提交
1319
    if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
H
hjxilinx 已提交
1320
      SSchema colSchema = {.type = TSDB_DATA_TYPE_BINARY, .bytes = TSDB_METER_NAME_LEN};
S
slguan 已提交
1321
      strcpy(colSchema.name, TSQL_TBNAME_L);
1322

1323 1324
      pQueryInfo->type = TSDB_QUERY_TYPE_STABLE_QUERY;
      tscAddSpecialColumnForSelect(pQueryInfo, startPos, TSDB_FUNC_TAGPRJ, &index, &colSchema, true);
S
slguan 已提交
1325
    } else {
1326
      SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index.tableIndex);
S
slguan 已提交
1327
      SMeterMeta*     pMeterMeta = pMeterMetaInfo->pMeterMeta;
H
hzcheng 已提交
1328

S
slguan 已提交
1329
      if (index.columnIndex >= pMeterMeta->numOfColumns && UTIL_METER_IS_NOMRAL_METER(pMeterMetaInfo)) {
1330
        return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
1331 1332
      }

1333
      addProjectQueryCol(pQueryInfo, startPos, &index, pItem);
H
hzcheng 已提交
1334 1335 1336 1337 1338 1339 1340 1341
    }
  } else {
    return TSDB_CODE_INVALID_SQL;
  }

  return TSDB_CODE_SUCCESS;
}

1342
static int32_t setExprInfoForFunctions(SQueryInfo* pQueryInfo, SSchema* pSchema, int32_t functionID, char* aliasName,
S
slguan 已提交
1343
                                       int32_t resColIdx, SColumnIndex* pColIndex) {
H
hzcheng 已提交
1344 1345 1346
  int16_t type = 0;
  int16_t bytes = 0;

S
slguan 已提交
1347
  char        columnName[TSDB_COL_NAME_LEN] = {0};
1348
  const char* msg1 = "not support column types";
H
hzcheng 已提交
1349 1350

  if (functionID == TSDB_FUNC_SPREAD) {
S
slguan 已提交
1351 1352 1353
    if (pSchema[pColIndex->columnIndex].type == TSDB_DATA_TYPE_BINARY ||
        pSchema[pColIndex->columnIndex].type == TSDB_DATA_TYPE_NCHAR ||
        pSchema[pColIndex->columnIndex].type == TSDB_DATA_TYPE_BOOL) {
1354
      invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
1355 1356 1357 1358 1359 1360
      return -1;
    } else {
      type = TSDB_DATA_TYPE_DOUBLE;
      bytes = tDataTypeDesc[type].nSize;
    }
  } else {
S
slguan 已提交
1361 1362
    type = pSchema[pColIndex->columnIndex].type;
    bytes = pSchema[pColIndex->columnIndex].bytes;
H
hzcheng 已提交
1363 1364 1365 1366 1367
  }

  if (aliasName != NULL) {
    strcpy(columnName, aliasName);
  } else {
S
slguan 已提交
1368
    getRevisedName(columnName, functionID, TSDB_COL_NAME_LEN, pSchema[pColIndex->columnIndex].name);
H
hzcheng 已提交
1369 1370
  }

1371
  tscSqlExprInsert(pQueryInfo, resColIdx, functionID, pColIndex, type, bytes, bytes);
H
hzcheng 已提交
1372

S
slguan 已提交
1373 1374
  // for point interpolation/last_row query, we need the timestamp column to be loaded
  SColumnIndex index = {.tableIndex = pColIndex->tableIndex, .columnIndex = PRIMARYKEY_TIMESTAMP_COL_INDEX};
H
hzcheng 已提交
1375
  if (functionID == TSDB_FUNC_INTERP || functionID == TSDB_FUNC_LAST_ROW) {
1376
    tscColumnBaseInfoInsert(pQueryInfo, &index);
H
hzcheng 已提交
1377 1378
  }

S
slguan 已提交
1379
  SColumnList ids = getColumnList(1, pColIndex->tableIndex, pColIndex->columnIndex);
1380
  insertResultField(pQueryInfo, resColIdx, &ids, bytes, type, columnName);
H
hzcheng 已提交
1381 1382 1383 1384

  return TSDB_CODE_SUCCESS;
}

1385
int32_t addExprAndResultField(SQueryInfo* pQueryInfo, int32_t colIdx, tSQLExprItem* pItem) {
S
slguan 已提交
1386 1387 1388
  SMeterMetaInfo* pMeterMetaInfo = NULL;
  int32_t         optr = pItem->pNode->nSQLOptr;

1389
  const char* msg1 = "not support column types";
S
slguan 已提交
1390
  const char* msg2 = "invalid parameters";
1391
  const char* msg3 = "illegal column name";
S
slguan 已提交
1392
  const char* msg4 = "invalid table name";
1393
  const char* msg5 = "parameter is out of range [0, 100]";
S
slguan 已提交
1394
  const char* msg6 = "function applied to tags not allowed";
H
hzcheng 已提交
1395 1396 1397 1398 1399

  switch (optr) {
    case TK_COUNT: {
      if (pItem->pNode->pParam != NULL && pItem->pNode->pParam->nExpr != 1) {
        /* more than one parameter for count() function */
1400
        return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
1401 1402 1403 1404
      }

      int16_t functionID = 0;
      if (changeFunctionID(optr, &functionID) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
1405
        return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
1406 1407
      }

S
slguan 已提交
1408
      SColumnIndex index = COLUMN_INDEX_INITIALIZER;
H
hzcheng 已提交
1409 1410 1411 1412

      if (pItem->pNode->pParam != NULL) {
        SSQLToken* pToken = &pItem->pNode->pParam->a[0].pNode->colInfo;
        if (pToken->z == NULL || pToken->n == 0) {
1413
          return invalidSqlErrMsg(pQueryInfo->msg, msg3);
H
hzcheng 已提交
1414 1415
        }

S
slguan 已提交
1416 1417 1418 1419 1420 1421
        tSQLExprItem* pParamElem = &pItem->pNode->pParam->a[0];
        if (pParamElem->pNode->nSQLOptr == TK_ALL) {
          // select table.*
          // check if the table name is valid or not
          SSQLToken tmpToken = pParamElem->pNode->colInfo;

1422 1423
          if (getTableIndexByName(&tmpToken, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
            return invalidSqlErrMsg(pQueryInfo->msg, msg4);
S
slguan 已提交
1424 1425 1426 1427
          }

          index = (SColumnIndex){0, PRIMARYKEY_TIMESTAMP_COL_INDEX};
          int32_t size = tDataTypeDesc[TSDB_DATA_TYPE_BIGINT].nSize;
1428
          tscSqlExprInsert(pQueryInfo, colIdx, functionID, &index, TSDB_DATA_TYPE_BIGINT, size, size);
H
hzcheng 已提交
1429
        } else {
S
slguan 已提交
1430
          // count the number of meters created according to the metric
1431 1432
          if (getColumnIndexByNameEx(pToken, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
            return invalidSqlErrMsg(pQueryInfo->msg, msg3);
S
slguan 已提交
1433 1434
          }

1435
          pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index.tableIndex);
S
slguan 已提交
1436 1437 1438 1439

          // count tag is equalled to count(tbname)
          if (index.columnIndex >= pMeterMetaInfo->pMeterMeta->numOfColumns) {
            index.columnIndex = TSDB_TBNAME_COLUMN_INDEX;
H
hzcheng 已提交
1440 1441
          }

S
slguan 已提交
1442
          int32_t size = tDataTypeDesc[TSDB_DATA_TYPE_BIGINT].nSize;
1443
          tscSqlExprInsert(pQueryInfo, colIdx, functionID, &index, TSDB_DATA_TYPE_BIGINT, size, size);
H
hzcheng 已提交
1444
        }
S
slguan 已提交
1445 1446 1447 1448
      } else {  // count(*) is equalled to count(primary_timestamp_key)
        index = (SColumnIndex){0, PRIMARYKEY_TIMESTAMP_COL_INDEX};

        int32_t size = tDataTypeDesc[TSDB_DATA_TYPE_BIGINT].nSize;
1449
        tscSqlExprInsert(pQueryInfo, colIdx, functionID, &index, TSDB_DATA_TYPE_BIGINT, size, size);
H
hzcheng 已提交
1450 1451 1452 1453 1454 1455
      }

      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.
S
slguan 已提交
1456 1457
      SColumnList ids = getColumnList(1, index.tableIndex, index.columnIndex);

1458
      insertResultField(pQueryInfo, colIdx, &ids, sizeof(int64_t), TSDB_DATA_TYPE_BIGINT, columnName);
S
slguan 已提交
1459
      return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1460 1461 1462
    }
    case TK_SUM:
    case TK_AVG:
S
slguan 已提交
1463
    case TK_TWA:
H
hzcheng 已提交
1464 1465 1466 1467 1468 1469 1470 1471 1472
    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 */
1473
        return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
1474 1475 1476 1477
      }

      tSQLExprItem* pParamElem = &(pItem->pNode->pParam->a[0]);
      if (pParamElem->pNode->nSQLOptr != TK_ALL && pParamElem->pNode->nSQLOptr != TK_ID) {
1478
        return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
1479 1480
      }

S
slguan 已提交
1481
      SColumnIndex index = COLUMN_INDEX_INITIALIZER;
1482
      if ((getColumnIndexByNameEx(&pParamElem->pNode->colInfo, pQueryInfo, &index) != TSDB_CODE_SUCCESS) ||
1483
          index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
1484
        return invalidSqlErrMsg(pQueryInfo->msg, msg3);
H
hzcheng 已提交
1485 1486 1487
      }

      // 2. check if sql function can be applied on this column data type
1488
      pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index.tableIndex);
S
slguan 已提交
1489 1490 1491
      SSchema* pSchema = tsGetColumnSchema(pMeterMetaInfo->pMeterMeta, index.columnIndex);
      int16_t  colType = pSchema->type;

H
hjxilinx 已提交
1492
      if (colType <= TSDB_DATA_TYPE_BOOL || colType >= TSDB_DATA_TYPE_BINARY) {
1493
        return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
1494 1495 1496 1497 1498 1499 1500
      }

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

      int16_t resultType = 0;
      int16_t resultSize = 0;
S
slguan 已提交
1501
      int16_t intermediateResSize = 0;
H
hzcheng 已提交
1502 1503 1504

      int16_t functionID = 0;
      if (changeFunctionID(optr, &functionID) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
1505
        return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
1506 1507
      }

S
slguan 已提交
1508 1509 1510 1511
      if (getResultDataInfo(pSchema->type, pSchema->bytes, functionID, 0, &resultType, &resultSize,
                            &intermediateResSize, 0, false) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
      }
H
hzcheng 已提交
1512

S
slguan 已提交
1513
      // set the first column ts for diff query
H
hzcheng 已提交
1514 1515
      if (optr == TK_DIFF) {
        colIdx += 1;
S
slguan 已提交
1516
        SColumnIndex indexTS = {.tableIndex = index.tableIndex, .columnIndex = 0};
1517 1518
        tscSqlExprInsert(pQueryInfo, 0, TSDB_FUNC_TS_DUMMY, &indexTS, TSDB_DATA_TYPE_TIMESTAMP, TSDB_KEYSIZE,
                         TSDB_KEYSIZE);
H
hzcheng 已提交
1519

S
slguan 已提交
1520
        SColumnList ids = getColumnList(1, 0, 0);
1521
        insertResultField(pQueryInfo, 0, &ids, TSDB_KEYSIZE, TSDB_DATA_TYPE_TIMESTAMP, aAggs[TSDB_FUNC_TS_DUMMY].aName);
H
hzcheng 已提交
1522 1523
      }

S
slguan 已提交
1524 1525
      // functions can not be applied to tags
      if (index.columnIndex >= pMeterMetaInfo->pMeterMeta->numOfColumns) {
1526
        return invalidSqlErrMsg(pQueryInfo->msg, msg6);
S
slguan 已提交
1527 1528
      }

1529
      SSqlExpr* pExpr = tscSqlExprInsert(pQueryInfo, colIdx, functionID, &index, resultType, resultSize, resultSize);
H
hzcheng 已提交
1530 1531 1532 1533 1534 1535 1536 1537

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

S
slguan 已提交
1538
        addExprParams(pExpr, val, TSDB_DATA_TYPE_DOUBLE, DOUBLE_BYTES, 0);
H
hzcheng 已提交
1539 1540 1541 1542 1543 1544

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

S
slguan 已提交
1545
        addExprParams(pExpr, val, TSDB_DATA_TYPE_DOUBLE, sizeof(double), 0);
H
hzcheng 已提交
1546 1547
      }

S
slguan 已提交
1548 1549 1550 1551
      SColumnList ids = {0};
      ids.num = 1;
      ids.ids[0] = index;

1552
      insertResultField(pQueryInfo, colIdx, &ids, pExpr->resBytes, pExpr->resType, columnName);
H
hzcheng 已提交
1553

S
slguan 已提交
1554
      return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
    }
    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) {
1568
          return invalidSqlErrMsg(pQueryInfo->msg, msg3);
H
hzcheng 已提交
1569 1570 1571 1572 1573 1574 1575
        }

        /* 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) {
1576
            return invalidSqlErrMsg(pQueryInfo->msg, msg3);
H
hzcheng 已提交
1577 1578
          }

S
slguan 已提交
1579 1580 1581 1582 1583 1584
          SColumnIndex index = COLUMN_INDEX_INITIALIZER;

          if (pParamElem->pNode->nSQLOptr == TK_ALL) {
            // select table.*
            SSQLToken tmpToken = pParamElem->pNode->colInfo;

1585 1586
            if (getTableIndexByName(&tmpToken, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
              return invalidSqlErrMsg(pQueryInfo->msg, msg4);
S
slguan 已提交
1587 1588
            }

1589
            pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index.tableIndex);
S
slguan 已提交
1590 1591 1592 1593
            SSchema* pSchema = tsGetSchema(pMeterMetaInfo->pMeterMeta);

            for (int32_t j = 0; j < pMeterMetaInfo->pMeterMeta->numOfColumns; ++j) {
              index.columnIndex = j;
1594
              if (setExprInfoForFunctions(pQueryInfo, pSchema, functionID, pItem->aliasName, colIdx++, &index) != 0) {
S
slguan 已提交
1595 1596 1597
                return TSDB_CODE_INVALID_SQL;
              }
            }
H
hzcheng 已提交
1598

S
slguan 已提交
1599
          } else {
1600 1601
            if (getColumnIndexByNameEx(&pParamElem->pNode->colInfo, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
              return invalidSqlErrMsg(pQueryInfo->msg, msg3);
S
slguan 已提交
1602 1603
            }

1604
            pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index.tableIndex);
S
slguan 已提交
1605 1606 1607 1608
            SSchema* pSchema = tsGetSchema(pMeterMetaInfo->pMeterMeta);

            // functions can not be applied to tags
            if (index.columnIndex >= pMeterMetaInfo->pMeterMeta->numOfColumns) {
1609
              return invalidSqlErrMsg(pQueryInfo->msg, msg6);
S
slguan 已提交
1610 1611
            }

1612
            if (setExprInfoForFunctions(pQueryInfo, pSchema, functionID, pItem->aliasName, colIdx + i, &index) != 0) {
S
slguan 已提交
1613 1614
              return TSDB_CODE_INVALID_SQL;
            }
H
hzcheng 已提交
1615 1616 1617
          }
        }

S
slguan 已提交
1618 1619 1620 1621
        return TSDB_CODE_SUCCESS;
      } else {  // select * from xxx
        int32_t numOfFields = 0;

1622 1623
        for (int32_t j = 0; j < pQueryInfo->numOfTables; ++j) {
          pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, j);
S
slguan 已提交
1624 1625 1626 1627
          SSchema* pSchema = tsGetSchema(pMeterMetaInfo->pMeterMeta);

          for (int32_t i = 0; i < pMeterMetaInfo->pMeterMeta->numOfColumns; ++i) {
            SColumnIndex index = {.tableIndex = j, .columnIndex = i};
1628 1629
            if (setExprInfoForFunctions(pQueryInfo, pSchema, functionID, pItem->aliasName, colIdx + i + j, &index) !=
                0) {
S
slguan 已提交
1630 1631
              return TSDB_CODE_INVALID_SQL;
            }
H
hzcheng 已提交
1632
          }
S
slguan 已提交
1633 1634

          numOfFields += pMeterMetaInfo->pMeterMeta->numOfColumns;
H
hzcheng 已提交
1635 1636
        }

S
slguan 已提交
1637
        return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1638 1639 1640 1641 1642 1643 1644 1645 1646
      }
    }
    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 */
1647
        return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
1648 1649 1650 1651
      }

      tSQLExprItem* pParamElem = &(pItem->pNode->pParam->a[0]);
      if (pParamElem->pNode->nSQLOptr != TK_ID) {
1652
        return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
1653 1654 1655 1656 1657
      }

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

S
slguan 已提交
1658
      SColumnIndex index = COLUMN_INDEX_INITIALIZER;
1659 1660
      if (getColumnIndexByNameEx(&pParamElem->pNode->colInfo, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
        return invalidSqlErrMsg(pQueryInfo->msg, msg3);
S
slguan 已提交
1661 1662
      }

1663
      pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index.tableIndex);
S
slguan 已提交
1664 1665 1666 1667
      SSchema* pSchema = tsGetSchema(pMeterMetaInfo->pMeterMeta);

      // functions can not be applied to tags
      if (index.columnIndex >= pMeterMetaInfo->pMeterMeta->numOfColumns) {
1668
        return invalidSqlErrMsg(pQueryInfo->msg, msg6);
H
hzcheng 已提交
1669 1670 1671
      }

      // 2. valid the column type
S
slguan 已提交
1672
      int16_t colType = pSchema[index.columnIndex].type;
H
hzcheng 已提交
1673
      if (colType == TSDB_DATA_TYPE_BOOL || colType >= TSDB_DATA_TYPE_BINARY) {
1674
        return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
1675 1676 1677 1678
      }

      // 3. valid the parameters
      if (pParamElem[1].pNode->nSQLOptr == TK_ID) {
1679
        return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
1680 1681 1682 1683
      }

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

S
slguan 已提交
1684 1685
      int8_t  resultType = pSchema[index.columnIndex].type;
      int16_t resultSize = pSchema[index.columnIndex].bytes;
H
hzcheng 已提交
1686

H
hjxilinx 已提交
1687 1688
      char    val[8] = {0};
      int32_t numOfAddedColumn = 1;
H
hzcheng 已提交
1689 1690 1691 1692
      if (optr == TK_PERCENTILE || optr == TK_APERCENTILE) {
        tVariantDump(pVariant, val, TSDB_DATA_TYPE_DOUBLE);

        double dp = *((double*)val);
S
slguan 已提交
1693
        if (dp < 0 || dp > TOP_BOTTOM_QUERY_LIMIT) {
1694
          return invalidSqlErrMsg(pQueryInfo->msg, msg5);
H
hzcheng 已提交
1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
        }

        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) {
S
slguan 已提交
1707
          return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
1708 1709
        }

1710
        SSqlExpr* pExpr = tscSqlExprInsert(pQueryInfo, colIdx, functionId, &index, resultType, resultSize, resultSize);
S
slguan 已提交
1711
        addExprParams(pExpr, val, TSDB_DATA_TYPE_DOUBLE, sizeof(double), 0);
H
hzcheng 已提交
1712 1713 1714 1715 1716
      } else {
        tVariantDump(pVariant, val, TSDB_DATA_TYPE_BIGINT);

        int64_t nTop = *((int32_t*)val);
        if (nTop <= 0 || nTop > 100) {  // todo use macro
1717
          return invalidSqlErrMsg(pQueryInfo->msg, msg5);
H
hzcheng 已提交
1718 1719 1720 1721
        }

        int16_t functionId = 0;
        if (changeFunctionID(optr, &functionId) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
1722
          return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
1723
        }
S
slguan 已提交
1724

H
hzcheng 已提交
1725
        // set the first column ts for top/bottom query
S
slguan 已提交
1726
        SColumnIndex index1 = {0, PRIMARYKEY_TIMESTAMP_COL_INDEX};
1727
        tscSqlExprInsert(pQueryInfo, 0, TSDB_FUNC_TS, &index1, TSDB_DATA_TYPE_TIMESTAMP, TSDB_KEYSIZE, TSDB_KEYSIZE);
S
slguan 已提交
1728 1729 1730

        const int32_t TS_COLUMN_INDEX = 0;
        SColumnList   ids = getColumnList(1, 0, TS_COLUMN_INDEX);
1731
        insertResultField(pQueryInfo, TS_COLUMN_INDEX, &ids, TSDB_KEYSIZE, TSDB_DATA_TYPE_TIMESTAMP,
S
slguan 已提交
1732
                          aAggs[TSDB_FUNC_TS].aName);
H
hzcheng 已提交
1733 1734 1735 1736

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

1737
        SSqlExpr* pExpr = tscSqlExprInsert(pQueryInfo, colIdx, functionId, &index, resultType, resultSize, resultSize);
S
slguan 已提交
1738
        addExprParams(pExpr, val, TSDB_DATA_TYPE_BIGINT, sizeof(int64_t), 0);
H
hzcheng 已提交
1739 1740
      }

S
slguan 已提交
1741
      SColumnList ids = getColumnList(1, 0, index.columnIndex);
1742
      insertResultField(pQueryInfo, colIdx, &ids, resultSize, resultType, columnName);
S
slguan 已提交
1743 1744

      return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1745 1746
    }
    default:
S
slguan 已提交
1747
      return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
1748 1749 1750
  }
}

S
slguan 已提交
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
// todo refactor
static SColumnList getColumnList(int32_t num, int16_t tableIndex, int32_t columnIndex) {
  assert(num == 1 && columnIndex >= -1 && tableIndex >= 0);

  SColumnList columnList = {0};
  columnList.num = num;

  int32_t index = num - 1;
  columnList.ids[index].tableIndex = tableIndex;
  columnList.ids[index].columnIndex = columnIndex;

  return columnList;
}

H
hzcheng 已提交
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777
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);
}

S
slguan 已提交
1778 1779 1780 1781 1782 1783 1784 1785 1786
static bool isTablenameToken(SSQLToken* token) {
  SSQLToken tmpToken = *token;
  SSQLToken tableToken = {0};

  extractTableNameFromToken(&tmpToken, &tableToken);

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

1787 1788
static int16_t doGetColumnIndex(SQueryInfo* pQueryInfo, int32_t index, SSQLToken* pToken) {
  SMeterMeta* pMeterMeta = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index)->pMeterMeta;
S
slguan 已提交
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807

  int32_t  numOfCols = pMeterMeta->numOfColumns + pMeterMeta->numOfTags;
  SSchema* pSchema = tsGetSchema(pMeterMeta);

  int16_t columnIndex = COLUMN_INDEX_INITIAL_VAL;

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

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

  return columnIndex;
}

1808
int32_t doGetColumnIndexByName(SSQLToken* pToken, SQueryInfo* pQueryInfo, SColumnIndex* pIndex) {
S
slguan 已提交
1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
  const char* msg0 = "ambiguous column name";
  const char* msg1 = "invalid column name";

  if (isTablenameToken(pToken)) {
    pIndex->columnIndex = TSDB_TBNAME_COLUMN_INDEX;
  } else if (strncasecmp(pToken->z, DEFAULT_PRIMARY_TIMESTAMP_COL_NAME, pToken->n) == 0) {
    pIndex->columnIndex = PRIMARYKEY_TIMESTAMP_COL_INDEX;
  } else {
    // not specify the table name, try to locate the table index by column name
    if (pIndex->tableIndex == COLUMN_INDEX_INITIAL_VAL) {
1819 1820
      for (int16_t i = 0; i < pQueryInfo->numOfTables; ++i) {
        int16_t colIndex = doGetColumnIndex(pQueryInfo, i, pToken);
S
slguan 已提交
1821 1822 1823

        if (colIndex != COLUMN_INDEX_INITIAL_VAL) {
          if (pIndex->columnIndex != COLUMN_INDEX_INITIAL_VAL) {
1824
            return invalidSqlErrMsg(pQueryInfo->msg, msg0);
S
slguan 已提交
1825 1826 1827 1828 1829 1830 1831
          } else {
            pIndex->tableIndex = i;
            pIndex->columnIndex = colIndex;
          }
        }
      }
    } else {  // table index is valid, get the column index
1832
      int16_t colIndex = doGetColumnIndex(pQueryInfo, pIndex->tableIndex, pToken);
S
slguan 已提交
1833 1834 1835 1836 1837 1838
      if (colIndex != COLUMN_INDEX_INITIAL_VAL) {
        pIndex->columnIndex = colIndex;
      }
    }

    if (pIndex->columnIndex == COLUMN_INDEX_INITIAL_VAL) {
1839
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
1840 1841 1842 1843 1844 1845 1846 1847 1848 1849
    }
  }

  if (COLUMN_INDEX_VALIDE(*pIndex)) {
    return TSDB_CODE_SUCCESS;
  } else {
    return TSDB_CODE_INVALID_SQL;
  }
}

1850
int32_t getMeterIndex(SSQLToken* pTableToken, SQueryInfo* pQueryInfo, SColumnIndex* pIndex) {
S
slguan 已提交
1851
  if (pTableToken->n == 0) {  // only one table and no table name prefix in column name
1852
    if (pQueryInfo->numOfTables == 1) {
S
slguan 已提交
1853 1854 1855 1856 1857 1858 1859 1860 1861
      pIndex->tableIndex = 0;
    }

    return TSDB_CODE_SUCCESS;
  }

  pIndex->tableIndex = COLUMN_INDEX_INITIAL_VAL;
  char tableName[TSDB_METER_ID_LEN + 1] = {0};

1862 1863
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
    SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, i);
H
hjxilinx 已提交
1864
    extractTableName(pMeterMetaInfo->name, tableName);
S
slguan 已提交
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878

    if (strncasecmp(tableName, pTableToken->z, pTableToken->n) == 0 && strlen(tableName) == pTableToken->n) {
      pIndex->tableIndex = i;
      break;
    }
  }

  if (pIndex->tableIndex < 0) {
    return TSDB_CODE_INVALID_SQL;
  }

  return TSDB_CODE_SUCCESS;
}

1879
int32_t getTableIndexByName(SSQLToken* pToken, SQueryInfo* pQueryInfo, SColumnIndex* pIndex) {
S
slguan 已提交
1880 1881 1882
  SSQLToken tableToken = {0};
  extractTableNameFromToken(pToken, &tableToken);

1883
  if (getMeterIndex(&tableToken, pQueryInfo, pIndex) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
1884
    return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
1885 1886
  }

S
slguan 已提交
1887 1888
  return TSDB_CODE_SUCCESS;
}
H
hzcheng 已提交
1889

1890
int32_t getColumnIndexByNameEx(SSQLToken* pToken, SQueryInfo* pQueryInfo, SColumnIndex* pIndex) {
1891
  if (pQueryInfo->pMeterInfo == NULL || pQueryInfo->numOfTables == 0) {
S
slguan 已提交
1892
    return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
1893 1894
  }

S
slguan 已提交
1895 1896
  SSQLToken tmpToken = *pToken;

1897
  if (getTableIndexByName(&tmpToken, pQueryInfo, pIndex) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
1898
    return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
1899 1900
  }

1901
  return doGetColumnIndexByName(&tmpToken, pQueryInfo, pIndex);
H
hzcheng 已提交
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
}

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;
S
slguan 已提交
1951 1952
    case TK_TWA:
      *functionId = TSDB_FUNC_TWA;
H
hzcheng 已提交
1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
      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;
}

int32_t setShowInfo(SSqlObj* pSql, struct SSqlInfo* pInfo) {
S
slguan 已提交
1968
  SSqlCmd*        pCmd = &pSql->cmd;
1969
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfo(pCmd, 0, 0);
S
slguan 已提交
1970

H
hzcheng 已提交
1971 1972
  pCmd->command = TSDB_SQL_SHOW;

1973
  const char* msg1 = "invalid name";
1974
  const char* msg2 = "pattern filter string too long";
1975 1976 1977 1978
  const char* msg3 = "database name too long";
  const char* msg4 = "invalid ip address";
  const char* msg5 = "database name is empty";
  const char* msg6 = "pattern string is empty";
H
hzcheng 已提交
1979 1980 1981 1982 1983

  /*
   * database prefix in pInfo->pDCLInfo->a[0]
   * wildcard in like clause in pInfo->pDCLInfo->a[1]
   */
1984 1985 1986
  SShowInfo* pShowInfo = &pInfo->pDCLInfo->showOpt;
  int16_t    showType = pShowInfo->showType;
  if (showType == TSDB_MGMT_TABLE_TABLE || showType == TSDB_MGMT_TABLE_METRIC || showType == TSDB_MGMT_TABLE_VGROUP) {
H
hzcheng 已提交
1987
    // db prefix in tagCond, show table conds in payload
1988 1989 1990
    SSQLToken* pDbPrefixToken = &pShowInfo->prefix;
    if (pDbPrefixToken->type != 0) {
      assert(pDbPrefixToken->n >= 0);
H
hzcheng 已提交
1991 1992

      if (pDbPrefixToken->n > TSDB_DB_NAME_LEN) {  // db name is too long
1993
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
H
hzcheng 已提交
1994 1995
      }

1996
      if (pDbPrefixToken->n <= 0) {
1997
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg5);
H
hzcheng 已提交
1998 1999
      }

2000
      if (tscValidateName(pDbPrefixToken) != TSDB_CODE_SUCCESS) {
2001
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
H
hzcheng 已提交
2002 2003
      }

2004
      int32_t ret = setObjFullName(pMeterMetaInfo->name, getAccountId(pSql), pDbPrefixToken, NULL, NULL);
H
hzcheng 已提交
2005
      if (ret != TSDB_CODE_SUCCESS) {
2006
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
H
hzcheng 已提交
2007
      }
2008
    }
H
hzcheng 已提交
2009

2010 2011 2012 2013
    // show table/stable like 'xxxx', set the like pattern for show tables
    SSQLToken* pPattern = &pShowInfo->pattern;
    if (pPattern->type != 0) {
      pPattern->n = strdequote(pPattern->z);
S
slguan 已提交
2014

2015
      if (pPattern->n <= 0) {
2016
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg6);
2017
      }
H
hzcheng 已提交
2018

2019
      if (pCmd->payloadLen > TSDB_METER_NAME_LEN) {
2020
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
H
hzcheng 已提交
2021 2022
      }
    }
2023 2024
  } else if (showType == TSDB_MGMT_TABLE_VNODES) {
    if (pShowInfo->prefix.type == 0) {
2025
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), "No specified ip of dnode");
L
lihui 已提交
2026 2027
    }

L
lihui 已提交
2028
    // show vnodes may be ip addr of dnode in payload
2029 2030
    SSQLToken* pDnodeIp = &pShowInfo->prefix;
    if (pDnodeIp->n > TSDB_IPv4ADDR_LEN) {  // ip addr is too long
2031
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
2032
    }
L
lihui 已提交
2033

2034
    if (!validateIpAddress(pDnodeIp->z, pDnodeIp->n)) {
2035
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg4);
L
lihui 已提交
2036
    }
H
hzcheng 已提交
2037 2038 2039 2040 2041 2042
  }

  return TSDB_CODE_SUCCESS;
}

int32_t setKillInfo(SSqlObj* pSql, struct SSqlInfo* pInfo) {
2043 2044
  const char* msg1 = "invalid ip address";
  const char* msg2 = "invalid port";
H
hzcheng 已提交
2045

2046 2047
  SSqlCmd* pCmd = &pSql->cmd;
  pCmd->command = pInfo->type;
H
hzcheng 已提交
2048

2049 2050
  SSQLToken* ip = &(pInfo->pDCLInfo->ip);
  if (ip->n > TSDB_KILL_MSG_LEN) {
H
hzcheng 已提交
2051 2052 2053
    return TSDB_CODE_INVALID_SQL;
  }

2054
  strncpy(pCmd->payload, ip->z, ip->n);
H
hzcheng 已提交
2055 2056 2057

  const char delim = ':';

2058 2059 2060 2061
  char* ipStr = strtok(ip->z, &delim);
  char* portStr = strtok(NULL, &delim);

  if (!validateIpAddress(ipStr, strlen(ipStr))) {
H
hzcheng 已提交
2062 2063
    memset(pCmd->payload, 0, tListLen(pCmd->payload));

2064
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
H
hzcheng 已提交
2065 2066
  }

L
lihui 已提交
2067
  uint16_t port = (uint16_t)strtol(portStr, NULL, 10);
H
hzcheng 已提交
2068 2069
  if (port <= 0 || port > 65535) {
    memset(pCmd->payload, 0, tListLen(pCmd->payload));
2070
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
H
hzcheng 已提交
2071 2072 2073 2074 2075
  }

  return TSDB_CODE_SUCCESS;
}

2076 2077 2078 2079 2080 2081 2082 2083 2084
bool validateIpAddress(const char* ip, size_t size) {
  char tmp[128] = {0};  // buffer to build null-terminated string
  assert(size < 128);

  strncpy(tmp, ip, size);

  in_addr_t ipAddr = inet_addr(tmp);

  return ipAddr != INADDR_NONE;
H
hzcheng 已提交
2085 2086
}

2087
int32_t tscTansformSQLFunctionForSTableQuery(SQueryInfo* pQueryInfo) {
2088
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
S
slguan 已提交
2089

2090
  if (pMeterMetaInfo->pMeterMeta == NULL || !UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {
S
slguan 已提交
2091
    return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
2092 2093
  }

S
slguan 已提交
2094
  assert(pMeterMetaInfo->pMeterMeta->numOfTags >= 0);
H
hzcheng 已提交
2095 2096 2097

  int16_t bytes = 0;
  int16_t type = 0;
S
slguan 已提交
2098
  int16_t intermediateBytes = 0;
H
hzcheng 已提交
2099

2100 2101 2102
  for (int32_t k = 0; k < pQueryInfo->fieldsInfo.numOfOutputCols; ++k) {
    SSqlExpr*   pExpr = tscSqlExprGet(pQueryInfo, k);
    TAOS_FIELD* pField = tscFieldInfoGetField(pQueryInfo, k);
H
hzcheng 已提交
2103

S
slguan 已提交
2104 2105 2106 2107 2108 2109 2110 2111
    int16_t functionId = aAggs[pExpr->functionId].stableFuncId;

    if ((functionId >= TSDB_FUNC_SUM && functionId <= TSDB_FUNC_TWA) ||
        (functionId >= TSDB_FUNC_FIRST_DST && functionId <= TSDB_FUNC_LAST_DST)) {
      if (getResultDataInfo(pField->type, pField->bytes, functionId, pExpr->param[0].i64Key, &type, &bytes,
                            &intermediateBytes, 0, true) != TSDB_CODE_SUCCESS) {
        return TSDB_CODE_INVALID_SQL;
      }
H
hzcheng 已提交
2112

2113
      tscSqlExprUpdate(pQueryInfo, k, functionId, pExpr->colInfo.colIdx, TSDB_DATA_TYPE_BINARY, bytes);
S
slguan 已提交
2114 2115
      // todo refactor
      pExpr->interResBytes = intermediateBytes;
H
hzcheng 已提交
2116 2117 2118
    }
  }

2119
  tscFieldInfoUpdateOffset(pQueryInfo);
S
slguan 已提交
2120
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
2121 2122 2123
}

/* transfer the field-info back to original input format */
2124 2125 2126
void tscRestoreSQLFunctionForMetricQuery(SQueryInfo* pQueryInfo) {
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
  if (!UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {
H
hzcheng 已提交
2127 2128 2129
    return;
  }

2130 2131 2132
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr*   pExpr = tscSqlExprGet(pQueryInfo, i);
    TAOS_FIELD* pField = tscFieldInfoGetField(pQueryInfo, i);
H
hzcheng 已提交
2133

S
slguan 已提交
2134 2135
    if ((pExpr->functionId >= TSDB_FUNC_FIRST_DST && pExpr->functionId <= TSDB_FUNC_LAST_DST) ||
        (pExpr->functionId >= TSDB_FUNC_SUM && pExpr->functionId <= TSDB_FUNC_MAX)) {
H
hzcheng 已提交
2136 2137 2138 2139 2140 2141
      pExpr->resBytes = pField->bytes;
      pExpr->resType = pField->type;
    }
  }
}

2142
bool hasUnsupportFunctionsForMetricQuery(SQueryInfo* pQueryInfo) {
S
slguan 已提交
2143
  const char* msg1 = "TWA not allowed to apply to super table directly";
H
hjxilinx 已提交
2144
  const char* msg2 = "TWA only support group by tbname for super table query";
H
hzcheng 已提交
2145

S
slguan 已提交
2146
  // filter sql function not supported by metric query yet.
2147 2148
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    int32_t functionId = tscSqlExprGet(pQueryInfo, i)->functionId;
S
slguan 已提交
2149 2150
    if ((aAggs[functionId].nStatus & TSDB_FUNCSTATE_METRIC) == 0) {
      return true;
H
hzcheng 已提交
2151 2152 2153
    }
  }

2154 2155 2156
  if (tscIsTWAQuery(pQueryInfo)) {
    if (pQueryInfo->groupbyExpr.numOfGroupCols == 0) {
      invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
2157 2158
      return true;
    }
H
hzcheng 已提交
2159

2160 2161 2162
    if (pQueryInfo->groupbyExpr.numOfGroupCols != 1 ||
        pQueryInfo->groupbyExpr.columnInfo[0].colIdx != TSDB_TBNAME_COLUMN_INDEX) {
      invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
2163 2164 2165
      return true;
    }
  }
S
slguan 已提交
2166

H
hzcheng 已提交
2167 2168 2169
  return false;
}

2170
static bool functionCompatibleCheck(SQueryInfo* pQueryInfo) {
H
hzcheng 已提交
2171
  int32_t startIdx = 0;
2172
  int32_t functionID = tscSqlExprGet(pQueryInfo, startIdx)->functionId;
S
slguan 已提交
2173 2174

  // ts function can be simultaneously used with any other functions.
H
hzcheng 已提交
2175
  if (functionID == TSDB_FUNC_TS || functionID == TSDB_FUNC_TS_DUMMY) {
S
slguan 已提交
2176
    startIdx++;
H
hzcheng 已提交
2177 2178
  }

2179
  int32_t factor = funcCompatDefList[tscSqlExprGet(pQueryInfo, startIdx)->functionId];
H
hzcheng 已提交
2180 2181 2182

  // diff function cannot be executed with other function
  // arithmetic function can be executed with other arithmetic functions
2183 2184
  for (int32_t i = startIdx + 1; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
2185 2186 2187 2188 2189 2190 2191

    int16_t functionId = pExpr->functionId;
    if (functionId == TSDB_FUNC_TAGPRJ || functionId == TSDB_FUNC_TAG || functionId == TSDB_FUNC_TS) {
      continue;
    }

    if (functionId == TSDB_FUNC_PRJ && pExpr->colInfo.colId == PRIMARYKEY_TIMESTAMP_COL_INDEX) {
S
slguan 已提交
2192 2193 2194 2195
      continue;
    }

    if (funcCompatDefList[functionId] != factor) {
H
hzcheng 已提交
2196 2197 2198 2199 2200 2201 2202
      return false;
    }
  }

  return true;
}

2203 2204
void updateTagColumnIndex(SQueryInfo* pQueryInfo, int32_t tableIndex) {
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, tableIndex);
S
slguan 已提交
2205

H
hjxilinx 已提交
2206 2207 2208 2209
  /*
   * update tags column index for group by tags
   * group by columns belong to this table
   */
2210 2211 2212
  if (pQueryInfo->groupbyExpr.numOfGroupCols > 0 && pQueryInfo->groupbyExpr.tableIndex == tableIndex) {
    for (int32_t i = 0; i < pQueryInfo->groupbyExpr.numOfGroupCols; ++i) {
      int32_t index = pQueryInfo->groupbyExpr.columnInfo[i].colIdx;
H
hjxilinx 已提交
2213

H
hjxilinx 已提交
2214 2215 2216
      for (int32_t j = 0; j < pMeterMetaInfo->numOfTags; ++j) {
        int32_t tagColIndex = pMeterMetaInfo->tagColumnIndex[j];
        if (tagColIndex == index) {
2217
          pQueryInfo->groupbyExpr.columnInfo[i].colIdx = j;
H
hjxilinx 已提交
2218 2219
          break;
        }
H
hzcheng 已提交
2220 2221 2222 2223 2224
      }
    }
  }

  // update tags column index for expression
2225 2226
  for (int32_t i = 0; i < pQueryInfo->exprsInfo.numOfExprs; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
H
hjxilinx 已提交
2227

S
slguan 已提交
2228
    if (!TSDB_COL_IS_TAG(pExpr->colInfo.flag)) {  // not tags, continue
H
hzcheng 已提交
2229 2230
      continue;
    }
H
hjxilinx 已提交
2231

H
hjxilinx 已提交
2232 2233 2234 2235
    // not belongs to this table
    if (pExpr->uid != pMeterMetaInfo->pMeterMeta->uid) {
      continue;
    }
H
hzcheng 已提交
2236

S
slguan 已提交
2237 2238
    for (int32_t j = 0; j < pMeterMetaInfo->numOfTags; ++j) {
      if (pExpr->colInfo.colIdx == pMeterMetaInfo->tagColumnIndex[j]) {
H
hzcheng 已提交
2239 2240 2241 2242 2243
        pExpr->colInfo.colIdx = j;
        break;
      }
    }
  }
H
hjxilinx 已提交
2244

H
hjxilinx 已提交
2245
  // update join condition tag column index
2246
  SJoinInfo* pJoinInfo = &pQueryInfo->tagCond.joinInfo;
H
hjxilinx 已提交
2247 2248 2249
  if (!pJoinInfo->hasJoin) {  // not join query
    return;
  }
H
hjxilinx 已提交
2250

H
hjxilinx 已提交
2251
  assert(pJoinInfo->left.uid != pJoinInfo->right.uid);
H
hjxilinx 已提交
2252

H
hjxilinx 已提交
2253 2254
  // the join condition expression node belongs to this table(super table)
  if (pMeterMetaInfo->pMeterMeta->uid == pJoinInfo->left.uid) {
H
hjxilinx 已提交
2255
    for (int32_t i = 0; i < pMeterMetaInfo->numOfTags; ++i) {
H
hjxilinx 已提交
2256 2257 2258 2259 2260
      if (pJoinInfo->left.tagCol == pMeterMetaInfo->tagColumnIndex[i]) {
        pJoinInfo->left.tagCol = i;
      }
    }
  }
H
hjxilinx 已提交
2261

H
hjxilinx 已提交
2262
  if (pMeterMetaInfo->pMeterMeta->uid == pJoinInfo->right.uid) {
H
hjxilinx 已提交
2263
    for (int32_t i = 0; i < pMeterMetaInfo->numOfTags; ++i) {
H
hjxilinx 已提交
2264 2265 2266 2267 2268
      if (pJoinInfo->right.tagCol == pMeterMetaInfo->tagColumnIndex[i]) {
        pJoinInfo->right.tagCol = i;
      }
    }
  }
H
hzcheng 已提交
2269 2270
}

2271
int32_t parseGroupbyClause(SQueryInfo* pQueryInfo, tVariantList* pList, SSqlCmd* pCmd) {
2272 2273
  const char* msg1 = "too many columns in group by clause";
  const char* msg2 = "invalid column name in group by clause";
H
hjxilinx 已提交
2274
  const char* msg3 = "group by columns must belong to one table";
S
slguan 已提交
2275 2276 2277
  const char* msg7 = "not support group by expression";
  const char* msg8 = "not allowed column type for group by";
  const char* msg9 = "tags not allowed for table query";
H
hzcheng 已提交
2278

S
slguan 已提交
2279 2280
  // todo : handle two meter situation
  SMeterMetaInfo* pMeterMetaInfo = NULL;
H
hzcheng 已提交
2281 2282 2283 2284 2285

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

2286
  pQueryInfo->groupbyExpr.numOfGroupCols = pList->nExpr;
H
hzcheng 已提交
2287
  if (pList->nExpr > TSDB_MAX_TAGS) {
2288
    return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
2289 2290
  }

S
slguan 已提交
2291 2292
  SMeterMeta* pMeterMeta = NULL;
  SSchema*    pSchema = NULL;
H
hjxilinx 已提交
2293
  SSchema     s = tsGetTbnameColumnSchema();
H
hzcheng 已提交
2294

S
slguan 已提交
2295
  int32_t tableIndex = COLUMN_INDEX_INITIAL_VAL;
H
hzcheng 已提交
2296 2297 2298 2299 2300

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

S
slguan 已提交
2301
    SColumnIndex index = COLUMN_INDEX_INITIALIZER;
H
hzcheng 已提交
2302

2303 2304
    if (getColumnIndexByNameEx(&token, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
      return invalidSqlErrMsg(pQueryInfo->msg, msg2);
S
slguan 已提交
2305
    }
H
hzcheng 已提交
2306

S
slguan 已提交
2307
    if (tableIndex != index.tableIndex && tableIndex >= 0) {
2308
      return invalidSqlErrMsg(pQueryInfo->msg, msg3);
H
hzcheng 已提交
2309 2310
    }

S
slguan 已提交
2311
    tableIndex = index.tableIndex;
H
hzcheng 已提交
2312

2313
    pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index.tableIndex);
S
slguan 已提交
2314
    pMeterMeta = pMeterMetaInfo->pMeterMeta;
H
hzcheng 已提交
2315

S
slguan 已提交
2316 2317 2318 2319 2320
    if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
      pSchema = &s;
    } else {
      pSchema = tsGetColumnSchema(pMeterMeta, index.columnIndex);
    }
H
hzcheng 已提交
2321

S
slguan 已提交
2322 2323 2324
    bool groupTag = false;
    if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX || index.columnIndex >= pMeterMeta->numOfColumns) {
      groupTag = true;
H
hzcheng 已提交
2325 2326
    }

S
slguan 已提交
2327
    if (groupTag) {
2328 2329
      if (!UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {
        return invalidSqlErrMsg(pQueryInfo->msg, msg9);
S
slguan 已提交
2330 2331 2332 2333 2334 2335 2336
      }

      int32_t relIndex = index.columnIndex;
      if (index.columnIndex != TSDB_TBNAME_COLUMN_INDEX) {
        relIndex -= pMeterMeta->numOfColumns;
      }

2337
      pQueryInfo->groupbyExpr.columnInfo[i] =
S
slguan 已提交
2338
          (SColIndexEx){.colIdx = relIndex, .flag = TSDB_COL_TAG, .colId = pSchema->colId};  // relIndex;
2339
      addRequiredTagColumn(pQueryInfo, pQueryInfo->groupbyExpr.columnInfo[i].colIdx, index.tableIndex);
S
slguan 已提交
2340 2341
    } else {
      // check if the column type is valid, here only support the bool/tinyint/smallint/bigint group by
2342
      if (pSchema->type > TSDB_DATA_TYPE_BINARY) {
2343
        return invalidSqlErrMsg(pQueryInfo->msg, msg8);
S
slguan 已提交
2344 2345
      }

2346 2347
      tscColumnBaseInfoInsert(pQueryInfo, &index);
      pQueryInfo->groupbyExpr.columnInfo[i] =
S
slguan 已提交
2348
          (SColIndexEx){.colIdx = index.columnIndex, .flag = TSDB_COL_NORMAL, .colId = pSchema->colId};  // relIndex;
2349
      pQueryInfo->groupbyExpr.orderType = TSQL_SO_ASC;
S
slguan 已提交
2350 2351

      if (i == 0 && pList->nExpr > 1) {
2352
        return invalidSqlErrMsg(pQueryInfo->msg, msg7);
S
slguan 已提交
2353
      }
H
hzcheng 已提交
2354 2355 2356
    }
  }

2357
  pQueryInfo->groupbyExpr.tableIndex = tableIndex;
S
slguan 已提交
2358

H
hzcheng 已提交
2359 2360 2361
  return TSDB_CODE_SUCCESS;
}

2362 2363 2364
void setColumnOffsetValueInResultset(SQueryInfo* pQueryInfo) {
  if (QUERY_IS_STABLE_QUERY(pQueryInfo->type)) {
    tscFieldInfoUpdateOffset(pQueryInfo);
H
hzcheng 已提交
2365
  } else {
2366
    tscFieldInfoCalOffset(pQueryInfo);
H
hzcheng 已提交
2367 2368 2369
  }
}

S
slguan 已提交
2370 2371 2372 2373
static SColumnFilterInfo* addColumnFilterInfo(SColumnBase* pColumn) {
  if (pColumn == NULL) {
    return NULL;
  }
2374

S
slguan 已提交
2375 2376 2377 2378
  int32_t size = pColumn->numOfFilters + 1;
  char*   tmp = realloc(pColumn->filterInfo, sizeof(SColumnFilterInfo) * (size));
  if (tmp != NULL) {
    pColumn->filterInfo = (SColumnFilterInfo*)tmp;
2379 2380
  }

S
slguan 已提交
2381
  pColumn->numOfFilters++;
2382

S
slguan 已提交
2383 2384 2385 2386
  SColumnFilterInfo* pColFilterInfo = &pColumn->filterInfo[pColumn->numOfFilters - 1];
  memset(pColFilterInfo, 0, sizeof(SColumnFilterInfo));

  return pColFilterInfo;
2387 2388
}

2389 2390
static int32_t doExtractColumnFilterInfo(SQueryInfo* pQueryInfo, SColumnFilterInfo* pColumnFilter,
                                         SColumnIndex* columnIndex, tSQLExpr* pExpr) {
S
slguan 已提交
2391
  const char* msg = "not supported filter condition";
H
hzcheng 已提交
2392

S
slguan 已提交
2393
  tSQLExpr*       pRight = pExpr->pRight;
2394
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, columnIndex->tableIndex);
H
hzcheng 已提交
2395

S
slguan 已提交
2396
  SSchema* pSchema = tsGetColumnSchema(pMeterMetaInfo->pMeterMeta, columnIndex->columnIndex);
H
hzcheng 已提交
2397

S
slguan 已提交
2398
  int16_t colType = pSchema->type;
2399
  if (colType >= TSDB_DATA_TYPE_TINYINT && colType <= TSDB_DATA_TYPE_BIGINT) {
H
hzcheng 已提交
2400 2401 2402
    colType = TSDB_DATA_TYPE_BIGINT;
  } else if (colType == TSDB_DATA_TYPE_FLOAT || colType == TSDB_DATA_TYPE_DOUBLE) {
    colType = TSDB_DATA_TYPE_DOUBLE;
2403
  } else if ((colType == TSDB_DATA_TYPE_TIMESTAMP) && (TSDB_DATA_TYPE_BINARY == pRight->val.nType)) {
2404
    int retVal = setColumnFilterInfoForTimestamp(pQueryInfo, &pRight->val);
2405 2406 2407
    if (TSDB_CODE_SUCCESS != retVal) {
      return retVal;
    }
H
hzcheng 已提交
2408 2409 2410
  }

  if (pExpr->nSQLOptr == TK_LE || pExpr->nSQLOptr == TK_LT) {
S
slguan 已提交
2411 2412
    tVariantDump(&pRight->val, (char*)&pColumnFilter->upperBndd, colType);
  } else {  // TK_GT,TK_GE,TK_EQ,TK_NE are based on the pColumn->lowerBndd
H
hzcheng 已提交
2413
    if (colType == TSDB_DATA_TYPE_BINARY) {
S
slguan 已提交
2414 2415
      pColumnFilter->pz = (int64_t)calloc(1, pRight->val.nLen + 1);
      pColumnFilter->len = pRight->val.nLen;
H
hzcheng 已提交
2416

S
slguan 已提交
2417 2418 2419 2420 2421 2422 2423 2424 2425
      tVariantDump(&pRight->val, (char*)pColumnFilter->pz, colType);
    } else if (colType == TSDB_DATA_TYPE_NCHAR) {
      // pRight->val.nLen + 1 is larger than the actual nchar string length
      pColumnFilter->pz = (int64_t)calloc(1, (pRight->val.nLen + 1) * TSDB_NCHAR_SIZE);

      tVariantDump(&pRight->val, (char*)pColumnFilter->pz, colType);

      size_t len = wcslen((wchar_t*)pColumnFilter->pz);
      pColumnFilter->len = len * TSDB_NCHAR_SIZE;
H
hzcheng 已提交
2426
    } else {
S
slguan 已提交
2427
      tVariantDump(&pRight->val, (char*)&pColumnFilter->lowerBndd, colType);
H
hzcheng 已提交
2428 2429 2430 2431 2432
    }
  }

  switch (pExpr->nSQLOptr) {
    case TK_LE:
S
slguan 已提交
2433
      pColumnFilter->upperRelOptr = TSDB_RELATION_LESS_EQUAL;
H
hzcheng 已提交
2434 2435
      break;
    case TK_LT:
S
slguan 已提交
2436
      pColumnFilter->upperRelOptr = TSDB_RELATION_LESS;
H
hzcheng 已提交
2437 2438
      break;
    case TK_GT:
S
slguan 已提交
2439
      pColumnFilter->lowerRelOptr = TSDB_RELATION_LARGE;
H
hzcheng 已提交
2440 2441
      break;
    case TK_GE:
S
slguan 已提交
2442
      pColumnFilter->lowerRelOptr = TSDB_RELATION_LARGE_EQUAL;
H
hzcheng 已提交
2443 2444
      break;
    case TK_EQ:
S
slguan 已提交
2445
      pColumnFilter->lowerRelOptr = TSDB_RELATION_EQUAL;
H
hzcheng 已提交
2446 2447
      break;
    case TK_NE:
S
slguan 已提交
2448
      pColumnFilter->lowerRelOptr = TSDB_RELATION_NOT_EQUAL;
H
hzcheng 已提交
2449 2450
      break;
    case TK_LIKE:
S
slguan 已提交
2451
      pColumnFilter->lowerRelOptr = TSDB_RELATION_LIKE;
H
hzcheng 已提交
2452
      break;
S
slguan 已提交
2453
    default:
2454
      return invalidSqlErrMsg(pQueryInfo->msg, msg);
H
hzcheng 已提交
2455
  }
S
slguan 已提交
2456

2457
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
2458 2459
}

S
slguan 已提交
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
typedef struct SCondExpr {
  tSQLExpr* pTagCond;
  tSQLExpr* pTimewindow;

  tSQLExpr* pColumnCond;

  tSQLExpr* pTableCond;
  int16_t   relType;  // relation between table name in expression and other tag
                      // filter condition expression, TK_AND or TK_OR
  int16_t tableCondIndex;

  tSQLExpr* pJoinExpr;  // join condition
  bool      tsJoin;
} SCondExpr;
H
hzcheng 已提交
2474

S
slguan 已提交
2475 2476 2477
static int32_t getTimeRange(int64_t* stime, int64_t* etime, tSQLExpr* pRight, int32_t optr, int16_t timePrecision);

static int32_t tSQLExprNodeToString(tSQLExpr* pExpr, char** str) {
H
hzcheng 已提交
2478
  if (pExpr->nSQLOptr == TK_ID) {  // column name
S
slguan 已提交
2479 2480
    strncpy(*str, pExpr->colInfo.z, pExpr->colInfo.n);
    *str += pExpr->colInfo.n;
H
hzcheng 已提交
2481 2482

  } else if (pExpr->nSQLOptr >= TK_BOOL && pExpr->nSQLOptr <= TK_STRING) {  // value
S
slguan 已提交
2483 2484
    *str += tVariantToString(&pExpr->val, *str);

H
hzcheng 已提交
2485
  } else {
S
slguan 已提交
2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504
    assert(false);
  }

  return TSDB_CODE_SUCCESS;
}

static bool isExprLeafNode(tSQLExpr* pExpr) {
  return (pExpr->pRight == NULL && pExpr->pLeft == NULL) &&
         (pExpr->nSQLOptr == TK_ID || (pExpr->nSQLOptr >= TK_BOOL && pExpr->nSQLOptr <= TK_NCHAR) ||
          pExpr->nSQLOptr == TK_SET);
}

static bool isExprDirectParentOfLeaftNode(tSQLExpr* pExpr) {
  return (pExpr->pLeft != NULL && pExpr->pRight != NULL) &&
         (isExprLeafNode(pExpr->pLeft) && isExprLeafNode(pExpr->pRight));
}

static int32_t tSQLExprLeafToString(tSQLExpr* pExpr, bool addParentheses, char** output) {
  if (!isExprDirectParentOfLeaftNode(pExpr)) {
H
hzcheng 已提交
2505 2506 2507
    return TSDB_CODE_INVALID_SQL;
  }

S
slguan 已提交
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
  tSQLExpr* pLeft = pExpr->pLeft;
  tSQLExpr* pRight = pExpr->pRight;

  if (addParentheses) {
    *(*output) = '(';
    *output += 1;
  }

  tSQLExprNodeToString(pLeft, output);
  if (optrToString(pExpr, output) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_INVALID_SQL;
  }

  tSQLExprNodeToString(pRight, output);

  if (addParentheses) {
    *(*output) = ')';
    *output += 1;
  }

H
hzcheng 已提交
2528 2529 2530 2531
  return TSDB_CODE_SUCCESS;
}

static int32_t optrToString(tSQLExpr* pExpr, char** exprString) {
S
slguan 已提交
2532 2533 2534 2535
  const char* le = "<=";
  const char* ge = ">=";
  const char* ne = "<>";
  const char* likeOptr = "LIKE";
H
hzcheng 已提交
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

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

H
hjxilinx 已提交
2592
static int32_t tablenameListToString(tSQLExpr* pExpr, /*char* str*/ SStringBuilder* sb) {
H
hzcheng 已提交
2593 2594 2595 2596 2597
  tSQLExprList* pList = pExpr->pParam;
  if (pList->nExpr <= 0) {
    return TSDB_CODE_INVALID_SQL;
  }

S
slguan 已提交
2598
  if (pList->nExpr > 0) {
H
hjxilinx 已提交
2599
    taosStringBuilderAppendStringLen(sb, QUERY_COND_REL_PREFIX_IN, QUERY_COND_REL_PREFIX_IN_LEN);
S
slguan 已提交
2600 2601
  }

H
hzcheng 已提交
2602 2603
  for (int32_t i = 0; i < pList->nExpr; ++i) {
    tSQLExpr* pSub = pList->a[i].pNode;
H
hjxilinx 已提交
2604
    taosStringBuilderAppendStringLen(sb, pSub->val.pz, pSub->val.nLen);
S
slguan 已提交
2605 2606

    if (i < pList->nExpr - 1) {
H
hjxilinx 已提交
2607
      taosStringBuilderAppendString(sb, TBNAME_LIST_SEP);
S
slguan 已提交
2608
    }
H
hzcheng 已提交
2609 2610 2611 2612 2613 2614 2615 2616 2617

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

  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
2618
static int32_t tablenameCondToString(tSQLExpr* pExpr, /*char* str*/ SStringBuilder* sb) {
H
hjxilinx 已提交
2619 2620
  taosStringBuilderAppendStringLen(sb, QUERY_COND_REL_PREFIX_LIKE, QUERY_COND_REL_PREFIX_LIKE_LEN);
  taosStringBuilderAppendString(sb, pExpr->val.pz);
S
slguan 已提交
2621 2622

  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
2623 2624
}

S
slguan 已提交
2625 2626 2627 2628 2629 2630
enum {
  TSQL_EXPR_TS = 0,
  TSQL_EXPR_TAG = 1,
  TSQL_EXPR_COLUMN = 2,
  TSQL_EXPR_TBNAME = 3,
};
H
hzcheng 已提交
2631

2632 2633
static int32_t extractColumnFilterInfo(SQueryInfo* pQueryInfo, SColumnIndex* pIndex, tSQLExpr* pExpr, int32_t sqlOptr) {
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, pIndex->tableIndex);
S
slguan 已提交
2634 2635 2636

  SMeterMeta* pMeterMeta = pMeterMetaInfo->pMeterMeta;
  SSchema*    pSchema = tsGetColumnSchema(pMeterMeta, pIndex->columnIndex);
H
hzcheng 已提交
2637

S
slguan 已提交
2638 2639 2640
  const char* msg1 = "non binary column not support like operator";
  const char* msg2 = "binary column not support this operator";

2641
  SColumnBase*       pColumn = tscColumnBaseInfoInsert(pQueryInfo, pIndex);
S
slguan 已提交
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666
  SColumnFilterInfo* pColFilter = NULL;

  /*
   * in case of TK_AND filter condition, we first find the corresponding column and build the query condition together
   * the already existed condition.
   */
  if (sqlOptr == TK_AND) {
    // this is a new filter condition on this column
    if (pColumn->numOfFilters == 0) {
      pColFilter = addColumnFilterInfo(pColumn);
    } else {  // update the existed column filter information, find the filter info here
      pColFilter = &pColumn->filterInfo[0];
    }
  } else if (sqlOptr == TK_OR) {
    // TODO fixme: failed to invalid the filter expression: "col1 = 1 OR col2 = 2"
    pColFilter = addColumnFilterInfo(pColumn);
  } else {  // error;
    return TSDB_CODE_INVALID_SQL;
  }

  pColFilter->filterOnBinary =
      ((pSchema->type == TSDB_DATA_TYPE_BINARY || pSchema->type == TSDB_DATA_TYPE_NCHAR) ? 1 : 0);

  if (pColFilter->filterOnBinary) {
    if (pExpr->nSQLOptr != TK_EQ && pExpr->nSQLOptr != TK_NE && pExpr->nSQLOptr != TK_LIKE) {
2667
      return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
2668
    }
S
slguan 已提交
2669 2670
  } else {
    if (pExpr->nSQLOptr == TK_LIKE) {
2671
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
2672
    }
S
slguan 已提交
2673 2674 2675
  }

  pColumn->colIndex = *pIndex;
2676
  return doExtractColumnFilterInfo(pQueryInfo, pColFilter, pIndex, pExpr);
S
slguan 已提交
2677 2678
}

2679
static void relToString(tSQLExpr* pExpr, char** str) {
S
slguan 已提交
2680 2681 2682 2683 2684
  assert(pExpr->nSQLOptr == TK_AND || pExpr->nSQLOptr == TK_OR);

  const char* or = "OR";
  const char*and = "AND";

2685
  //    if (pQueryInfo->tagCond.relType == TSQL_STABLE_QTYPE_COND) {
S
slguan 已提交
2686 2687 2688 2689 2690 2691 2692 2693 2694
  if (pExpr->nSQLOptr == TK_AND) {
    strcpy(*str, and);
    *str += strlen(and);
  } else {
    strcpy(*str, or);
    *str += strlen(or);
  }
}

2695
static int32_t getTagCondString(tSQLExpr* pExpr, char** str) {
S
slguan 已提交
2696 2697 2698 2699 2700 2701 2702
  if (pExpr == NULL) {
    return TSDB_CODE_SUCCESS;
  }

  if (!isExprDirectParentOfLeaftNode(pExpr)) {
    *(*str) = '(';
    *str += 1;
H
hzcheng 已提交
2703

2704
    int32_t ret = getTagCondString(pExpr->pLeft, str);
H
hzcheng 已提交
2705
    if (ret != TSDB_CODE_SUCCESS) {
S
slguan 已提交
2706
      return ret;
H
hzcheng 已提交
2707
    }
S
slguan 已提交
2708

2709
    relToString(pExpr, str);
S
slguan 已提交
2710

2711
    ret = getTagCondString(pExpr->pRight, str);
S
slguan 已提交
2712 2713 2714 2715

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

H
hzcheng 已提交
2716 2717 2718
    return ret;
  }

S
slguan 已提交
2719 2720 2721
  return tSQLExprLeafToString(pExpr, true, str);
}

2722
static int32_t getTablenameCond(SQueryInfo* pQueryInfo, tSQLExpr* pTableCond, SStringBuilder* sb) {
S
slguan 已提交
2723 2724 2725 2726
  const char* msg0 = "invalid table name list";

  if (pTableCond == NULL) {
    return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
2727 2728
  }

S
slguan 已提交
2729 2730
  tSQLExpr* pLeft = pTableCond->pLeft;
  tSQLExpr* pRight = pTableCond->pRight;
H
hzcheng 已提交
2731

S
slguan 已提交
2732
  if (!isTablenameToken(&pLeft->colInfo)) {
H
hzcheng 已提交
2733 2734 2735
    return TSDB_CODE_INVALID_SQL;
  }

S
slguan 已提交
2736
  int32_t ret = TSDB_CODE_SUCCESS;
H
hzcheng 已提交
2737

S
slguan 已提交
2738
  if (pTableCond->nSQLOptr == TK_IN) {
H
hjxilinx 已提交
2739
    ret = tablenameListToString(pRight, sb);
S
slguan 已提交
2740
  } else if (pTableCond->nSQLOptr == TK_LIKE) {
H
hjxilinx 已提交
2741
    ret = tablenameCondToString(pRight, sb);
S
slguan 已提交
2742
  }
H
hzcheng 已提交
2743

S
slguan 已提交
2744
  if (ret != TSDB_CODE_SUCCESS) {
2745
    invalidSqlErrMsg(pQueryInfo->msg, msg0);
S
slguan 已提交
2746
  }
H
hzcheng 已提交
2747

S
slguan 已提交
2748 2749 2750
  return ret;
}

2751
static int32_t getColumnQueryCondInfo(SQueryInfo* pQueryInfo, tSQLExpr* pExpr, int32_t relOptr) {
S
slguan 已提交
2752 2753 2754 2755 2756
  if (pExpr == NULL) {
    return TSDB_CODE_SUCCESS;
  }

  if (!isExprDirectParentOfLeaftNode(pExpr)) {  // internal node
2757
    int32_t ret = getColumnQueryCondInfo(pQueryInfo, pExpr->pLeft, pExpr->nSQLOptr);
S
slguan 已提交
2758 2759 2760 2761
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }

2762
    return getColumnQueryCondInfo(pQueryInfo, pExpr->pRight, pExpr->nSQLOptr);
S
slguan 已提交
2763 2764
  } else {  // handle leaf node
    SColumnIndex index = COLUMN_INDEX_INITIALIZER;
2765
    if (getColumnIndexByNameEx(&pExpr->pLeft->colInfo, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
2766 2767
      return TSDB_CODE_INVALID_SQL;
    }
S
slguan 已提交
2768

2769
    return extractColumnFilterInfo(pQueryInfo, &index, pExpr, relOptr);
H
hzcheng 已提交
2770
  }
S
slguan 已提交
2771
}
H
hzcheng 已提交
2772

2773
static int32_t getJoinCondInfo(SQueryInfo* pQueryInfo, tSQLExpr* pExpr) {
S
slguan 已提交
2774
  const char* msg = "invalid join query condition";
H
hzcheng 已提交
2775

S
slguan 已提交
2776 2777 2778
  if (pExpr == NULL) {
    return TSDB_CODE_SUCCESS;
  }
H
hzcheng 已提交
2779

S
slguan 已提交
2780
  if (!isExprDirectParentOfLeaftNode(pExpr)) {
2781
    return invalidSqlErrMsg(pQueryInfo->msg, msg);
S
slguan 已提交
2782 2783
  }

2784
  STagCond*  pTagCond = &pQueryInfo->tagCond;
S
slguan 已提交
2785 2786 2787 2788
  SJoinNode* pLeft = &pTagCond->joinInfo.left;
  SJoinNode* pRight = &pTagCond->joinInfo.right;

  SColumnIndex index = COLUMN_INDEX_INITIALIZER;
2789
  if (getColumnIndexByNameEx(&pExpr->pLeft->colInfo, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
2790 2791 2792
    return TSDB_CODE_INVALID_SQL;
  }

2793
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index.tableIndex);
S
slguan 已提交
2794 2795 2796 2797 2798 2799 2800
  int16_t         tagColIndex = index.columnIndex - pMeterMetaInfo->pMeterMeta->numOfColumns;

  pLeft->uid = pMeterMetaInfo->pMeterMeta->uid;
  pLeft->tagCol = tagColIndex;
  strcpy(pLeft->meterId, pMeterMetaInfo->name);

  index = (SColumnIndex)COLUMN_INDEX_INITIALIZER;
2801
  if (getColumnIndexByNameEx(&pExpr->pRight->colInfo, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
2802 2803 2804
    return TSDB_CODE_INVALID_SQL;
  }

2805
  pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index.tableIndex);
S
slguan 已提交
2806 2807 2808 2809 2810 2811 2812
  tagColIndex = index.columnIndex - pMeterMetaInfo->pMeterMeta->numOfColumns;

  pRight->uid = pMeterMetaInfo->pMeterMeta->uid;
  pRight->tagCol = tagColIndex;
  strcpy(pRight->meterId, pMeterMetaInfo->name);

  pTagCond->joinInfo.hasJoin = true;
H
hzcheng 已提交
2813 2814 2815 2816
  return TSDB_CODE_SUCCESS;
}

// todo error handle / such as and /or mixed with +/-/*/
S
slguan 已提交
2817
int32_t buildArithmeticExprString(tSQLExpr* pExpr, char** exprString) {
H
hzcheng 已提交
2818 2819 2820 2821 2822 2823 2824
  tSQLExpr* pLeft = pExpr->pLeft;
  tSQLExpr* pRight = pExpr->pRight;

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

  if (pLeft->nSQLOptr >= TK_PLUS && pLeft->nSQLOptr <= TK_REM) {
S
slguan 已提交
2825
    buildArithmeticExprString(pLeft, exprString);
H
hzcheng 已提交
2826
  } else {
S
slguan 已提交
2827
    int32_t ret = tSQLExprNodeToString(pLeft, exprString);
H
hzcheng 已提交
2828 2829 2830 2831 2832 2833 2834 2835
    if (ret != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_INVALID_SQL;
    }
  }

  optrToString(pExpr, exprString);

  if (pRight->nSQLOptr >= TK_PLUS && pRight->nSQLOptr <= TK_REM) {
S
slguan 已提交
2836
    buildArithmeticExprString(pRight, exprString);
H
hzcheng 已提交
2837
  } else {
S
slguan 已提交
2838
    int32_t ret = tSQLExprNodeToString(pRight, exprString);
H
hzcheng 已提交
2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849
    if (ret != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_INVALID_SQL;
    }
  }

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

  return TSDB_CODE_SUCCESS;
}

S
slguan 已提交
2850
static int32_t validateSQLExpr(tSQLExpr* pExpr, SSchema* pSchema, int32_t numOfCols, SColumnIdListRes* pList) {
H
hzcheng 已提交
2851 2852
  if (pExpr->nSQLOptr == TK_ID) {
    bool validColumnName = false;
S
slguan 已提交
2853 2854 2855

    SColumnList* list = &pList->list;

H
hzcheng 已提交
2856 2857 2858 2859 2860 2861
    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;
        }
S
slguan 已提交
2862 2863 2864 2865 2866

        if (pList != NULL) {
          list->ids[list->num++].columnIndex = (int16_t)i;
        }

H
hzcheng 已提交
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876
        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;
S
slguan 已提交
2877 2878
  } else if (pExpr->nSQLOptr >= TK_MIN && pExpr->nSQLOptr <= TK_LAST_ROW) {
    return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
2879 2880 2881 2882 2883
  }

  return TSDB_CODE_SUCCESS;
}

S
slguan 已提交
2884 2885
static int32_t validateArithmeticSQLExpr(tSQLExpr* pExpr, SSchema* pSchema, int32_t numOfCols,
                                         SColumnIdListRes* pList) {
H
hzcheng 已提交
2886 2887 2888 2889 2890 2891
  if (pExpr == NULL) {
    return TSDB_CODE_SUCCESS;
  }

  tSQLExpr* pLeft = pExpr->pLeft;
  if (pLeft->nSQLOptr >= TK_PLUS && pLeft->nSQLOptr <= TK_REM) {
S
slguan 已提交
2892
    int32_t ret = validateArithmeticSQLExpr(pLeft, pSchema, numOfCols, pList);
H
hzcheng 已提交
2893 2894 2895 2896
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
  } else {
S
slguan 已提交
2897
    int32_t ret = validateSQLExpr(pLeft, pSchema, numOfCols, pList);
H
hzcheng 已提交
2898 2899 2900 2901 2902 2903 2904
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
  }

  tSQLExpr* pRight = pExpr->pRight;
  if (pRight->nSQLOptr >= TK_PLUS && pRight->nSQLOptr <= TK_REM) {
S
slguan 已提交
2905
    int32_t ret = validateArithmeticSQLExpr(pRight, pSchema, numOfCols, pList);
H
hzcheng 已提交
2906 2907 2908 2909
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
  } else {
S
slguan 已提交
2910
    int32_t ret = validateSQLExpr(pRight, pSchema, numOfCols, pList);
H
hzcheng 已提交
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925
    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:
S
slguan 已提交
2926 2927 2928
   * 1. count(*) > 12
   * 2. sum(columnA) > sum(columnB)
   * 3. 4 < 5,  'ABC'>'abc'
H
hzcheng 已提交
2929 2930 2931
   *
   * However, columnA < 4+12 is valid
   */
S
slguan 已提交
2932 2933
  if ((pLeft->nSQLOptr >= TK_COUNT && pLeft->nSQLOptr <= TK_LAST_ROW) ||
      (pRight->nSQLOptr >= TK_COUNT && pRight->nSQLOptr <= TK_LAST_ROW) ||
H
hzcheng 已提交
2934 2935 2936 2937 2938 2939 2940 2941
      (pLeft->nSQLOptr >= TK_BOOL && pLeft->nSQLOptr <= TK_BINARY && pRight->nSQLOptr >= TK_BOOL &&
       pRight->nSQLOptr <= TK_BINARY)) {
    return false;
  }

  return true;
}

S
slguan 已提交
2942 2943 2944
static void exchangeExpr(tSQLExpr* pExpr) {
  tSQLExpr* pLeft = pExpr->pLeft;
  tSQLExpr* pRight = pExpr->pRight;
H
hzcheng 已提交
2945

S
slguan 已提交
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
  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 handside.
     */
    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;
    }
H
hzcheng 已提交
2971

S
slguan 已提交
2972 2973 2974 2975 2976
    pExpr->nSQLOptr = optr;
    SWAP(pExpr->pLeft, pExpr->pRight, void*);
  }
}

2977
static bool validateJoinExprNode(SQueryInfo* pQueryInfo, tSQLExpr* pExpr, SColumnIndex* pLeftIndex) {
S
slguan 已提交
2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991
  const char* msg1 = "illegal column name";
  const char* msg2 = "= is expected in join expression";
  const char* msg3 = "join column must have same type";
  const char* msg4 = "self join is not allowed";
  const char* msg5 = "join table must be the same type(table to table, super table to super table)";
  const char* msg6 = "tags in join condition not support binary/nchar types";

  tSQLExpr* pRight = pExpr->pRight;

  if (pRight->nSQLOptr != TK_ID) {
    return true;
  }

  if (pExpr->nSQLOptr != TK_EQ) {
2992
    invalidSqlErrMsg(pQueryInfo->msg, msg2);
S
slguan 已提交
2993 2994 2995 2996 2997
    return false;
  }

  SColumnIndex rightIndex = COLUMN_INDEX_INITIALIZER;

2998 2999
  if (getColumnIndexByNameEx(&pRight->colInfo, pQueryInfo, &rightIndex) != TSDB_CODE_SUCCESS) {
    invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
3000
    return false;
H
hzcheng 已提交
3001 3002
  }

S
slguan 已提交
3003
  // todo extract function
3004
  SMeterMetaInfo* pLeftMeterMeta = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, pLeftIndex->tableIndex);
S
slguan 已提交
3005 3006 3007
  SSchema*        pLeftSchema = tsGetSchema(pLeftMeterMeta->pMeterMeta);
  int16_t         leftType = pLeftSchema[pLeftIndex->columnIndex].type;

3008
  SMeterMetaInfo* pRightMeterMeta = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, rightIndex.tableIndex);
S
slguan 已提交
3009 3010 3011 3012
  SSchema*        pRightSchema = tsGetSchema(pRightMeterMeta->pMeterMeta);
  int16_t         rightType = pRightSchema[rightIndex.columnIndex].type;

  if (leftType != rightType) {
3013
    invalidSqlErrMsg(pQueryInfo->msg, msg3);
S
slguan 已提交
3014 3015
    return false;
  } else if (pLeftIndex->tableIndex == rightIndex.tableIndex) {
3016
    invalidSqlErrMsg(pQueryInfo->msg, msg4);
S
slguan 已提交
3017 3018
    return false;
  } else if (leftType == TSDB_DATA_TYPE_BINARY || leftType == TSDB_DATA_TYPE_NCHAR) {
3019
    invalidSqlErrMsg(pQueryInfo->msg, msg6);
S
slguan 已提交
3020
    return false;
H
hzcheng 已提交
3021 3022
  }

S
slguan 已提交
3023
  // table to table/ super table to super table are allowed
3024 3025
  if (UTIL_METER_IS_SUPERTABLE(pLeftMeterMeta) != UTIL_METER_IS_SUPERTABLE(pRightMeterMeta)) {
    invalidSqlErrMsg(pQueryInfo->msg, msg5);
S
slguan 已提交
3026 3027
    return false;
  }
H
hzcheng 已提交
3028

S
slguan 已提交
3029 3030
  return true;
}
H
hzcheng 已提交
3031

S
slguan 已提交
3032 3033 3034 3035 3036 3037
static bool validTableNameOptr(tSQLExpr* pExpr) {
  const char nameFilterOptr[] = {TK_IN, TK_LIKE};

  for (int32_t i = 0; i < tListLen(nameFilterOptr); ++i) {
    if (pExpr->nSQLOptr == nameFilterOptr[i]) {
      return true;
H
hzcheng 已提交
3038 3039 3040
    }
  }

S
slguan 已提交
3041
  return false;
H
hzcheng 已提交
3042 3043
}

3044
static int32_t setExprToCond(tSQLExpr** parent, tSQLExpr* pExpr, const char* msg, int32_t parentOptr, char* msgBuf) {
S
slguan 已提交
3045 3046
  if (*parent != NULL) {
    if (parentOptr == TK_OR && msg != NULL) {
3047
      return invalidSqlErrMsg(msgBuf, msg);
S
slguan 已提交
3048
    }
H
hzcheng 已提交
3049

S
slguan 已提交
3050 3051 3052 3053
    *parent = tSQLExprCreate((*parent), pExpr, parentOptr);
  } else {
    *parent = pExpr;
  }
H
hzcheng 已提交
3054

S
slguan 已提交
3055 3056
  return TSDB_CODE_SUCCESS;
}
H
hzcheng 已提交
3057

3058
static int32_t handleExprInQueryCond(SQueryInfo* pQueryInfo, tSQLExpr** pExpr, SCondExpr* pCondExpr, int32_t* type,
S
slguan 已提交
3059 3060 3061 3062 3063
                                     int32_t parentOptr) {
  const char* msg1 = "meter query cannot use tags filter";
  const char* msg2 = "illegal column name";
  const char* msg3 = "only one query time range allowed";
  const char* msg4 = "only one join condition allowed";
H
hjxilinx 已提交
3064 3065 3066
  const char* msg5 = "not support ordinary column join";
  const char* msg6 = "only one query condition on tbname allowed";
  const char* msg7 = "only in/like allowed in filter table name";
H
hzcheng 已提交
3067

S
slguan 已提交
3068 3069
  tSQLExpr* pLeft = (*pExpr)->pLeft;
  tSQLExpr* pRight = (*pExpr)->pRight;
H
hzcheng 已提交
3070

S
slguan 已提交
3071 3072 3073
  int32_t ret = TSDB_CODE_SUCCESS;

  SColumnIndex index = COLUMN_INDEX_INITIALIZER;
3074 3075
  if (getColumnIndexByNameEx(&pLeft->colInfo, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
    return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
3076 3077
  }

S
slguan 已提交
3078 3079
  assert(isExprDirectParentOfLeaftNode(*pExpr));

3080
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index.tableIndex);
S
slguan 已提交
3081 3082 3083
  SMeterMeta*     pMeterMeta = pMeterMetaInfo->pMeterMeta;

  if (index.columnIndex == PRIMARYKEY_TIMESTAMP_COL_INDEX) {  // query on time range
3084
    if (!validateJoinExprNode(pQueryInfo, *pExpr, &index)) {
H
hzcheng 已提交
3085 3086
      return TSDB_CODE_INVALID_SQL;
    }
S
slguan 已提交
3087 3088 3089

    // set join query condition
    if (pRight->nSQLOptr == TK_ID) {  // no need to keep the timestamp join condition
3090
      pQueryInfo->type |= TSDB_QUERY_TYPE_JOIN_QUERY;
S
slguan 已提交
3091 3092 3093 3094 3095 3096 3097 3098
      pCondExpr->tsJoin = true;

      /*
       * to release expression, e.g., m1.ts = m2.ts,
       * since this expression is used to set the join query type
       */
      tSQLExprDestroy(*pExpr);
    } else {
3099
      ret = setExprToCond(&pCondExpr->pTimewindow, *pExpr, msg3, parentOptr, pQueryInfo->msg);
S
slguan 已提交
3100 3101 3102 3103 3104 3105 3106 3107
    }

    *pExpr = NULL;  // remove this expression
    *type = TSQL_EXPR_TS;
  } else if (index.columnIndex >= pMeterMeta->numOfColumns ||
             index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) {  // query on tags
    // check for tag query condition
    if (UTIL_METER_IS_NOMRAL_METER(pMeterMetaInfo)) {
3108
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120
    }

    // check for like expression
    if ((*pExpr)->nSQLOptr == TK_LIKE) {
      if (pRight->val.nLen > TSDB_PATTERN_STRING_MAX_LEN) {
        return TSDB_CODE_INVALID_SQL;
      }

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

      if ((!isTablenameToken(&pLeft->colInfo)) && pSchema[index.columnIndex].type != TSDB_DATA_TYPE_BINARY &&
          pSchema[index.columnIndex].type != TSDB_DATA_TYPE_NCHAR) {
3121
        return invalidSqlErrMsg(pQueryInfo->msg, msg2);
S
slguan 已提交
3122 3123 3124 3125 3126 3127
      }
    }

    // in case of in operator, keep it in a seperate attribute
    if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
      if (!validTableNameOptr(*pExpr)) {
3128
        return invalidSqlErrMsg(pQueryInfo->msg, msg7);
S
slguan 已提交
3129 3130 3131 3132 3133 3134 3135
      }

      if (pCondExpr->pTableCond == NULL) {
        pCondExpr->pTableCond = *pExpr;
        pCondExpr->relType = parentOptr;
        pCondExpr->tableCondIndex = index.tableIndex;
      } else {
3136
        return invalidSqlErrMsg(pQueryInfo->msg, msg6);
S
slguan 已提交
3137 3138 3139 3140 3141 3142
      }

      *type = TSQL_EXPR_TBNAME;
      *pExpr = NULL;
    } else {
      if (pRight->nSQLOptr == TK_ID) {  // join on tag columns for stable query
3143
        if (!validateJoinExprNode(pQueryInfo, *pExpr, &index)) {
S
slguan 已提交
3144 3145 3146 3147
          return TSDB_CODE_INVALID_SQL;
        }

        if (pCondExpr->pJoinExpr != NULL) {
3148
          return invalidSqlErrMsg(pQueryInfo->msg, msg4);
S
slguan 已提交
3149 3150
        }

3151 3152
        pQueryInfo->type |= TSDB_QUERY_TYPE_JOIN_QUERY;
        ret = setExprToCond(&pCondExpr->pJoinExpr, *pExpr, NULL, parentOptr, pQueryInfo->msg);
S
slguan 已提交
3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166
        *pExpr = NULL;
      } else {
        // do nothing
        //                ret = setExprToCond(pCmd, &pCondExpr->pTagCond,
        //                *pExpr, NULL, parentOptr);
      }

      *type = TSQL_EXPR_TAG;
    }

  } else {  // query on other columns
    *type = TSQL_EXPR_COLUMN;

    if (pRight->nSQLOptr == TK_ID) {  // other column cannot be served as the join column
3167
      return invalidSqlErrMsg(pQueryInfo->msg, msg5);
H
hzcheng 已提交
3168 3169
    }

3170
    ret = setExprToCond(&pCondExpr->pColumnCond, *pExpr, NULL, parentOptr, pQueryInfo->msg);
S
slguan 已提交
3171 3172
    *pExpr = NULL;  // remove it from expr tree
  }
H
hzcheng 已提交
3173

S
slguan 已提交
3174
  return ret;
H
hzcheng 已提交
3175 3176
}

3177 3178
int32_t getQueryCondExpr(SQueryInfo* pQueryInfo, tSQLExpr** pExpr, SCondExpr* pCondExpr, int32_t* type,
                         int32_t parentOptr) {
H
hzcheng 已提交
3179 3180 3181 3182
  if (pExpr == NULL) {
    return TSDB_CODE_SUCCESS;
  }

S
slguan 已提交
3183
  const char* msg1 = "query condition between different columns must use 'AND'";
H
hzcheng 已提交
3184

S
slguan 已提交
3185 3186 3187 3188
  tSQLExpr* pLeft = (*pExpr)->pLeft;
  tSQLExpr* pRight = (*pExpr)->pRight;

  if (!isValidExpr(pLeft, pRight, (*pExpr)->nSQLOptr)) {
H
hzcheng 已提交
3189 3190 3191
    return TSDB_CODE_INVALID_SQL;
  }

S
slguan 已提交
3192 3193
  int32_t leftType = -1;
  int32_t rightType = -1;
H
hzcheng 已提交
3194

S
slguan 已提交
3195
  if (!isExprDirectParentOfLeaftNode(*pExpr)) {
3196
    int32_t ret = getQueryCondExpr(pQueryInfo, &(*pExpr)->pLeft, pCondExpr, &leftType, (*pExpr)->nSQLOptr);
H
hzcheng 已提交
3197 3198 3199 3200
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }

3201
    ret = getQueryCondExpr(pQueryInfo, &(*pExpr)->pRight, pCondExpr, &rightType, (*pExpr)->nSQLOptr);
S
slguan 已提交
3202 3203 3204
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
H
hzcheng 已提交
3205

S
slguan 已提交
3206 3207 3208 3209 3210 3211
    /*
     *  if left child and right child do not belong to the same group, the sub
     *  expression is not valid for parent node, it must be TK_AND operator.
     */
    if (leftType != rightType) {
      if ((*pExpr)->nSQLOptr == TK_OR && (leftType + rightType != TSQL_EXPR_TBNAME + TSQL_EXPR_TAG)) {
3212
        return invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
3213
      }
H
hzcheng 已提交
3214 3215
    }

S
slguan 已提交
3216 3217 3218
    *type = rightType;
    return TSDB_CODE_SUCCESS;
  }
H
hzcheng 已提交
3219

S
slguan 已提交
3220
  exchangeExpr(*pExpr);
H
hzcheng 已提交
3221

3222
  return handleExprInQueryCond(pQueryInfo, pExpr, pCondExpr, type, parentOptr);
S
slguan 已提交
3223
}
H
hzcheng 已提交
3224

S
slguan 已提交
3225 3226 3227 3228
static void doCompactQueryExpr(tSQLExpr** pExpr) {
  if (*pExpr == NULL || isExprDirectParentOfLeaftNode(*pExpr)) {
    return;
  }
H
hzcheng 已提交
3229

S
slguan 已提交
3230 3231 3232
  if ((*pExpr)->pLeft) {
    doCompactQueryExpr(&(*pExpr)->pLeft);
  }
H
hzcheng 已提交
3233

S
slguan 已提交
3234 3235 3236
  if ((*pExpr)->pRight) {
    doCompactQueryExpr(&(*pExpr)->pRight);
  }
H
hzcheng 已提交
3237

S
slguan 已提交
3238 3239 3240 3241
  if ((*pExpr)->pLeft == NULL && (*pExpr)->pRight == NULL &&
      ((*pExpr)->nSQLOptr == TK_OR || (*pExpr)->nSQLOptr == TK_AND)) {
    tSQLExprNodeDestroy(*pExpr);
    *pExpr = NULL;
H
hzcheng 已提交
3242

S
slguan 已提交
3243 3244 3245
  } else if ((*pExpr)->pLeft == NULL && (*pExpr)->pRight != NULL) {
    tSQLExpr* tmpPtr = (*pExpr)->pRight;
    tSQLExprNodeDestroy(*pExpr);
H
hzcheng 已提交
3246

S
slguan 已提交
3247 3248 3249 3250
    (*pExpr) = tmpPtr;
  } else if ((*pExpr)->pRight == NULL && (*pExpr)->pLeft != NULL) {
    tSQLExpr* tmpPtr = (*pExpr)->pLeft;
    tSQLExprNodeDestroy(*pExpr);
H
hzcheng 已提交
3251

S
slguan 已提交
3252
    (*pExpr) = tmpPtr;
H
hzcheng 已提交
3253
  }
S
slguan 已提交
3254
}
H
hzcheng 已提交
3255

3256
static void doExtractExprForSTable(tSQLExpr** pExpr, SQueryInfo* pQueryInfo, tSQLExpr** pOut, int32_t tableIndex) {
S
slguan 已提交
3257 3258 3259 3260
  if (isExprDirectParentOfLeaftNode(*pExpr)) {
    tSQLExpr* pLeft = (*pExpr)->pLeft;

    SColumnIndex index = COLUMN_INDEX_INITIALIZER;
3261
    if (getColumnIndexByNameEx(&pLeft->colInfo, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
3262
      return;
H
hzcheng 已提交
3263 3264
    }

S
slguan 已提交
3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277
    if (index.tableIndex != tableIndex) {
      return;
    }

    SSQLToken t = {0};
    extractTableNameFromToken(&pLeft->colInfo, &t);

    *pOut = *pExpr;
    (*pExpr) = NULL;

  } else {
    *pOut = tSQLExprCreate(NULL, NULL, (*pExpr)->nSQLOptr);

3278 3279
    doExtractExprForSTable(&(*pExpr)->pLeft, pQueryInfo, &((*pOut)->pLeft), tableIndex);
    doExtractExprForSTable(&(*pExpr)->pRight, pQueryInfo, &((*pOut)->pRight), tableIndex);
S
slguan 已提交
3280 3281 3282
  }
}

3283
static tSQLExpr* extractExprForSTable(tSQLExpr** pExpr, SQueryInfo* pQueryInfo, int32_t tableIndex) {
S
slguan 已提交
3284
  tSQLExpr* pResExpr = NULL;
H
hzcheng 已提交
3285

S
slguan 已提交
3286
  if (*pExpr != NULL) {
3287
    doExtractExprForSTable(pExpr, pQueryInfo, &pResExpr, tableIndex);
S
slguan 已提交
3288
    doCompactQueryExpr(&pResExpr);
H
hzcheng 已提交
3289 3290
  }

S
slguan 已提交
3291
  return pResExpr;
H
hzcheng 已提交
3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306
}

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

3307 3308
static int32_t setTableCondForMetricQuery(SQueryInfo* pQueryInfo, const char* account, tSQLExpr* pExpr,
                                          int16_t tableCondIndex, SStringBuilder* sb) {
3309
  const char* msg = "table name too long";
H
hzcheng 已提交
3310

S
slguan 已提交
3311 3312 3313 3314
  if (pExpr == NULL) {
    return TSDB_CODE_SUCCESS;
  }

3315
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, tableCondIndex);
S
slguan 已提交
3316

3317
  STagCond* pTagCond = &pQueryInfo->tagCond;
S
slguan 已提交
3318 3319 3320 3321 3322
  pTagCond->tbnameCond.uid = pMeterMetaInfo->pMeterMeta->uid;

  assert(pExpr->nSQLOptr == TK_LIKE || pExpr->nSQLOptr == TK_IN);

  if (pExpr->nSQLOptr == TK_LIKE) {
H
hjxilinx 已提交
3323
    char* str = taosStringBuilderGetResult(sb, NULL);
3324
    pQueryInfo->tagCond.tbnameCond.cond = strdup(str);
S
slguan 已提交
3325 3326 3327
    return TSDB_CODE_SUCCESS;
  }

H
hjxilinx 已提交
3328 3329
  SStringBuilder sb1 = {0};
  taosStringBuilderAppendStringLen(&sb1, QUERY_COND_REL_PREFIX_IN, QUERY_COND_REL_PREFIX_IN_LEN);
H
hzcheng 已提交
3330 3331 3332

  char db[TSDB_METER_ID_LEN] = {0};

S
slguan 已提交
3333
  // remove the duplicated input table names
H
hzcheng 已提交
3334
  int32_t num = 0;
H
hjxilinx 已提交
3335 3336 3337
  char*   tableNameString = taosStringBuilderGetResult(sb, NULL);

  char** segments = strsplit(tableNameString + QUERY_COND_REL_PREFIX_IN_LEN, TBNAME_LIST_SEP, &num);
H
hjxilinx 已提交
3338
  qsort(segments, num, POINTER_BYTES, tableNameCompar);
H
hzcheng 已提交
3339 3340 3341 3342 3343 3344 3345 3346 3347

  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;

S
slguan 已提交
3348
  SSQLToken dbToken = extractDBName(pMeterMetaInfo->name, db);
H
hzcheng 已提交
3349 3350 3351

  for (int32_t i = 0; i < num; ++i) {
    if (i >= 1) {
H
hjxilinx 已提交
3352
      taosStringBuilderAppendStringLen(&sb1, TBNAME_LIST_SEP, 1);
H
hzcheng 已提交
3353
    }
H
hjxilinx 已提交
3354 3355

    char      idBuf[TSDB_METER_ID_LEN + 1] = {0};
S
slguan 已提交
3356
    int32_t   xlen = strlen(segments[i]);
H
hzcheng 已提交
3357 3358
    SSQLToken t = {.z = segments[i], .n = xlen, .type = TK_STRING};

3359
    int32_t ret = setObjFullName(idBuf, account, &dbToken, &t, &xlen);
H
hzcheng 已提交
3360
    if (ret != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
3361
      taosStringBuilderDestroy(&sb1);
H
hzcheng 已提交
3362
      tfree(segments);
H
hjxilinx 已提交
3363

3364
      invalidSqlErrMsg(pQueryInfo->msg, msg);
H
hzcheng 已提交
3365 3366
      return ret;
    }
H
hjxilinx 已提交
3367

H
hjxilinx 已提交
3368
    taosStringBuilderAppendString(&sb1, idBuf);
H
hzcheng 已提交
3369
  }
H
hjxilinx 已提交
3370

H
hjxilinx 已提交
3371
  char* str = taosStringBuilderGetResult(&sb1, NULL);
3372
  pQueryInfo->tagCond.tbnameCond.cond = strdup(str);
H
hjxilinx 已提交
3373

H
hjxilinx 已提交
3374
  taosStringBuilderDestroy(&sb1);
H
hzcheng 已提交
3375 3376 3377 3378
  tfree(segments);
  return TSDB_CODE_SUCCESS;
}

3379 3380 3381
static bool validateFilterExpr(SQueryInfo* pQueryInfo) {
  for (int32_t i = 0; i < pQueryInfo->colList.numOfCols; ++i) {
    SColumnBase* pColBase = &pQueryInfo->colList.pColList[i];
3382

S
slguan 已提交
3383 3384 3385 3386
    for (int32_t j = 0; j < pColBase->numOfFilters; ++j) {
      SColumnFilterInfo* pColFilter = &pColBase->filterInfo[j];
      int32_t            lowerOptr = pColFilter->lowerRelOptr;
      int32_t            upperOptr = pColFilter->upperRelOptr;
3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402

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

3403
static int32_t getTimeRangeFromExpr(SQueryInfo* pQueryInfo, tSQLExpr* pExpr) {
S
slguan 已提交
3404 3405
  const char* msg0 = "invalid timestamp";
  const char* msg1 = "only one time stamp window allowed";
H
hzcheng 已提交
3406 3407 3408 3409 3410

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

S
slguan 已提交
3411 3412
  if (!isExprDirectParentOfLeaftNode(pExpr)) {
    if (pExpr->nSQLOptr == TK_OR) {
3413
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
3414
    }
H
hzcheng 已提交
3415

3416
    getTimeRangeFromExpr(pQueryInfo, pExpr->pLeft);
S
slguan 已提交
3417

3418
    return getTimeRangeFromExpr(pQueryInfo, pExpr->pRight);
S
slguan 已提交
3419 3420
  } else {
    SColumnIndex index = COLUMN_INDEX_INITIALIZER;
3421
    if (getColumnIndexByNameEx(&pExpr->pLeft->colInfo, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
3422 3423 3424
      return TSDB_CODE_INVALID_SQL;
    }

3425
    SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index.tableIndex);
S
slguan 已提交
3426 3427 3428 3429 3430 3431 3432 3433
    SMeterMeta*     pMeterMeta = pMeterMetaInfo->pMeterMeta;

    tSQLExpr* pRight = pExpr->pRight;

    TSKEY stime = 0;
    TSKEY etime = INT64_MAX;

    if (getTimeRange(&stime, &etime, pRight, pExpr->nSQLOptr, pMeterMeta->precision) != TSDB_CODE_SUCCESS) {
3434
      return invalidSqlErrMsg(pQueryInfo->msg, msg0);
S
slguan 已提交
3435 3436 3437
    }

    // update the timestamp query range
3438 3439
    if (pQueryInfo->stime < stime) {
      pQueryInfo->stime = stime;
S
slguan 已提交
3440 3441
    }

3442 3443
    if (pQueryInfo->etime > etime) {
      pQueryInfo->etime = etime;
S
slguan 已提交
3444 3445 3446 3447 3448 3449
    }
  }

  return TSDB_CODE_SUCCESS;
}

3450
static int32_t validateJoinExpr(SQueryInfo* pQueryInfo, SCondExpr* pCondExpr) {
S
slguan 已提交
3451 3452 3453 3454
  const char* msg1 = "super table join requires tags column";
  const char* msg2 = "timestamp join condition missing";
  const char* msg3 = "condition missing for join query";

3455 3456
  if (!QUERY_IS_JOIN_QUERY(pQueryInfo->type)) {
    if (pQueryInfo->numOfTables == 1) {
S
slguan 已提交
3457 3458
      return TSDB_CODE_SUCCESS;
    } else {
3459
      return invalidSqlErrMsg(pQueryInfo->msg, msg3);
S
slguan 已提交
3460 3461 3462
    }
  }

3463 3464
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
  if (UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {  // for stable join, tag columns
3465
                                                   // must be present for join
S
slguan 已提交
3466
    if (pCondExpr->pJoinExpr == NULL) {
3467
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
3468 3469 3470 3471
    }
  }

  if (!pCondExpr->tsJoin) {
3472
    return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
3473 3474
  }

S
slguan 已提交
3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499
  return TSDB_CODE_SUCCESS;
}

static void cleanQueryExpr(SCondExpr* pCondExpr) {
  if (pCondExpr->pTableCond) {
    tSQLExprDestroy(pCondExpr->pTableCond);
  }

  if (pCondExpr->pTagCond) {
    tSQLExprDestroy(pCondExpr->pTagCond);
  }

  if (pCondExpr->pColumnCond) {
    tSQLExprDestroy(pCondExpr->pColumnCond);
  }

  if (pCondExpr->pTimewindow) {
    tSQLExprDestroy(pCondExpr->pTimewindow);
  }

  if (pCondExpr->pJoinExpr) {
    tSQLExprDestroy(pCondExpr->pJoinExpr);
  }
}

3500 3501 3502
static void doAddJoinTagsColumnsIntoTagList(SQueryInfo* pQueryInfo, SCondExpr* pCondExpr) {
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
  if (QUERY_IS_JOIN_QUERY(pQueryInfo->type) && UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {
S
slguan 已提交
3503
    SColumnIndex index = {0};
H
hjxilinx 已提交
3504

3505 3506
    getColumnIndexByNameEx(&pCondExpr->pJoinExpr->pLeft->colInfo, pQueryInfo, &index);
    pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index.tableIndex);
H
hjxilinx 已提交
3507

S
slguan 已提交
3508
    int32_t columnInfo = index.columnIndex - pMeterMetaInfo->pMeterMeta->numOfColumns;
3509
    addRequiredTagColumn(pQueryInfo, columnInfo, index.tableIndex);
H
hjxilinx 已提交
3510

3511 3512
    getColumnIndexByNameEx(&pCondExpr->pJoinExpr->pRight->colInfo, pQueryInfo, &index);
    pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, index.tableIndex);
H
hjxilinx 已提交
3513

S
slguan 已提交
3514
    columnInfo = index.columnIndex - pMeterMetaInfo->pMeterMeta->numOfColumns;
3515
    addRequiredTagColumn(pQueryInfo, columnInfo, index.tableIndex);
S
slguan 已提交
3516
  }
H
hjxilinx 已提交
3517
}
S
slguan 已提交
3518

3519
static int32_t getTagQueryCondExpr(SQueryInfo* pQueryInfo, SCondExpr* pCondExpr, tSQLExpr** pExpr) {
H
hjxilinx 已提交
3520
  int32_t ret = TSDB_CODE_SUCCESS;
H
hjxilinx 已提交
3521

H
hjxilinx 已提交
3522
  if (pCondExpr->pTagCond != NULL) {
3523 3524
    for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
      tSQLExpr* p1 = extractExprForSTable(pExpr, pQueryInfo, i);
H
hjxilinx 已提交
3525

3526
      SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, i);
H
hjxilinx 已提交
3527

H
hjxilinx 已提交
3528 3529
      char  c[TSDB_MAX_TAGS_LEN] = {0};
      char* str = c;
H
hjxilinx 已提交
3530

3531
      if ((ret = getTagCondString(p1, &str)) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
3532 3533
        return ret;
      }
H
hjxilinx 已提交
3534

3535
      tsSetMetricQueryCond(&pQueryInfo->tagCond, pMeterMetaInfo->pMeterMeta->uid, c);
H
hjxilinx 已提交
3536

H
hjxilinx 已提交
3537 3538 3539
      doCompactQueryExpr(pExpr);
      tSQLExprDestroy(p1);
    }
H
hjxilinx 已提交
3540

H
hjxilinx 已提交
3541 3542
    pCondExpr->pTagCond = NULL;
  }
H
hjxilinx 已提交
3543

S
slguan 已提交
3544 3545
  return ret;
}
H
hjxilinx 已提交
3546 3547 3548 3549
int32_t parseWhereClause(SSqlObj* pSql, tSQLExpr** pExpr) {
  if (pExpr == NULL) {
    return TSDB_CODE_SUCCESS;
  }
H
hjxilinx 已提交
3550

S
slguan 已提交
3551
  const char* msg = "invalid filter expression";
H
hjxilinx 已提交
3552
  const char* msg1 = "invalid expression";
H
hjxilinx 已提交
3553

H
hjxilinx 已提交
3554
  int32_t ret = TSDB_CODE_SUCCESS;
H
hjxilinx 已提交
3555

3556
  SSqlCmd*    pCmd = &pSql->cmd;
3557 3558 3559
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
  pQueryInfo->stime = 0;
  pQueryInfo->etime = INT64_MAX;
S
slguan 已提交
3560

H
hjxilinx 已提交
3561
  // tags query condition may be larger than 512bytes, therefore, we need to prepare enough large space
H
hjxilinx 已提交
3562
  SStringBuilder sb = {0};
H
hjxilinx 已提交
3563
  SCondExpr      condExpr = {0};
S
slguan 已提交
3564

H
hjxilinx 已提交
3565
  if ((*pExpr)->pLeft == NULL || (*pExpr)->pRight == NULL) {
3566
    return invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
3567 3568
  }

H
hjxilinx 已提交
3569
  int32_t type = 0;
3570
  if ((ret = getQueryCondExpr(pQueryInfo, pExpr, &condExpr, &type, (*pExpr)->nSQLOptr)) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
3571 3572
    return ret;
  }
H
hjxilinx 已提交
3573

S
slguan 已提交
3574
  doCompactQueryExpr(pExpr);
H
hjxilinx 已提交
3575

S
slguan 已提交
3576
  // after expression compact, the expression tree is only include tag query condition
H
hjxilinx 已提交
3577
  condExpr.pTagCond = (*pExpr);
H
hjxilinx 已提交
3578

S
slguan 已提交
3579
  // 1. check if it is a join query
3580
  if ((ret = validateJoinExpr(pQueryInfo, &condExpr)) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
3581 3582
    return ret;
  }
H
hjxilinx 已提交
3583

S
slguan 已提交
3584
  // 2. get the query time range
3585
  if ((ret = getTimeRangeFromExpr(pQueryInfo, condExpr.pTimewindow)) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
3586 3587
    return ret;
  }
H
hjxilinx 已提交
3588

S
slguan 已提交
3589
  // 3. get the tag query condition
3590
  if ((ret = getTagQueryCondExpr(pQueryInfo, &condExpr, pExpr)) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
3591
    return ret;
S
slguan 已提交
3592
  }
H
hjxilinx 已提交
3593

S
slguan 已提交
3594
  // 4. get the table name query condition
3595
  if ((ret = getTablenameCond(pQueryInfo, condExpr.pTableCond, &sb)) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
3596 3597
    return ret;
  }
H
hjxilinx 已提交
3598

S
slguan 已提交
3599
  // 5. other column query condition
3600
  if ((ret = getColumnQueryCondInfo(pQueryInfo, condExpr.pColumnCond, TK_AND)) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
3601 3602
    return ret;
  }
H
hjxilinx 已提交
3603

S
slguan 已提交
3604
  // 6. join condition
3605
  if ((ret = getJoinCondInfo(pQueryInfo, condExpr.pJoinExpr)) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
3606
    return ret;
H
hzcheng 已提交
3607
  }
H
hjxilinx 已提交
3608

S
slguan 已提交
3609
  // 7. query condition for table name
3610
  pQueryInfo->tagCond.relType = (condExpr.relType == TK_AND) ? TSDB_RELATION_AND : TSDB_RELATION_OR;
H
hjxilinx 已提交
3611

3612
  ret = setTableCondForMetricQuery(pQueryInfo, getAccountId(pSql), condExpr.pTableCond, condExpr.tableCondIndex, &sb);
H
hjxilinx 已提交
3613
  taosStringBuilderDestroy(&sb);
H
hjxilinx 已提交
3614

3615 3616
  if (!validateFilterExpr(pQueryInfo)) {
    return invalidSqlErrMsg(pQueryInfo->msg, msg);
3617
  }
H
hjxilinx 已提交
3618

3619
  doAddJoinTagsColumnsIntoTagList(pQueryInfo, &condExpr);
H
hjxilinx 已提交
3620

H
hjxilinx 已提交
3621
  cleanQueryExpr(&condExpr);
H
hzcheng 已提交
3622 3623 3624 3625
  return ret;
}

int32_t getTimeRange(int64_t* stime, int64_t* etime, tSQLExpr* pRight, int32_t optr, int16_t timePrecision) {
S
slguan 已提交
3626 3627 3628 3629 3630
  // this is join condition, do nothing
  if (pRight->nSQLOptr == TK_ID) {
    return TSDB_CODE_SUCCESS;
  }

S
slguan 已提交
3631 3632
  /*
   * filter primary ts filter expression like:
S
slguan 已提交
3633
   * where ts in ('2015-12-12 4:8:12')
S
slguan 已提交
3634 3635 3636 3637
   */
  if (pRight->nSQLOptr == TK_SET || optr == TK_IN) {
    return TSDB_CODE_INVALID_SQL;
  }
H
hzcheng 已提交
3638 3639 3640 3641

  int64_t val = 0;
  bool    parsed = false;
  if (pRight->val.nType == TSDB_DATA_TYPE_BINARY) {
S
slguan 已提交
3642 3643
    pRight->val.nLen = strdequote(pRight->val.pz);

S
slguan 已提交
3644
    char* seg = strnchr(pRight->val.pz, '-', pRight->val.nLen, false);
H
hzcheng 已提交
3645 3646 3647 3648 3649 3650
    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;
      }
S
slguan 已提交
3651 3652 3653 3654 3655 3656 3657
    } else {
      SSQLToken token = {.z = pRight->val.pz, .n = pRight->val.nLen, .type = TK_ID};
      int32_t   len = tSQLGetToken(pRight->val.pz, &token.type);

      if ((token.type != TK_INTEGER && token.type != TK_FLOAT) || len != pRight->val.nLen) {
        return TSDB_CODE_INVALID_SQL;
      }
H
hzcheng 已提交
3658 3659 3660 3661
    }
  } else if (pRight->nSQLOptr == TK_INTEGER && timePrecision == TSDB_TIME_PRECISION_MILLI) {
    /*
     * if the pRight->nSQLOptr == TK_INTEGER/TK_FLOAT, the value is adaptive, we
S
slguan 已提交
3662
     * need the time precision in metermeta to transfer the value in MICROSECOND
H
hzcheng 已提交
3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713
     *
     * 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;
}

3714
int32_t tsRewriteFieldNameIfNecessary(SQueryInfo* pQueryInfo) {
S
slguan 已提交
3715 3716
  const char rep[] = {'(', ')', '*', ',', '.', '/', '\\', '+', '-', '%', ' '};

3717 3718
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    char* fieldName = tscFieldInfoGetField(pQueryInfo, i)->name;
H
hzcheng 已提交
3719
    for (int32_t j = 0; j < TSDB_COL_NAME_LEN && fieldName[j] != 0; ++j) {
S
slguan 已提交
3720 3721 3722 3723 3724
      for (int32_t k = 0; k < tListLen(rep); ++k) {
        if (fieldName[j] == rep[k]) {
          fieldName[j] = '_';
          break;
        }
H
hzcheng 已提交
3725 3726
      }
    }
S
slguan 已提交
3727

H
hzcheng 已提交
3728 3729 3730 3731
    fieldName[TSDB_COL_NAME_LEN - 1] = 0;
  }

  // the column name may be identical, here check again
3732 3733 3734 3735
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    char* fieldName = tscFieldInfoGetField(pQueryInfo, i)->name;
    for (int32_t j = i + 1; j < pQueryInfo->fieldsInfo.numOfOutputCols; ++j) {
      if (strncasecmp(fieldName, tscFieldInfoGetField(pQueryInfo, j)->name, TSDB_COL_NAME_LEN) == 0) {
3736
        const char* msg = "duplicated column name in new table";
3737
        return invalidSqlErrMsg(pQueryInfo->msg, msg);
H
hzcheng 已提交
3738 3739 3740 3741 3742 3743 3744
      }
    }
  }

  return TSDB_CODE_SUCCESS;
}

3745
int32_t parseFillClause(SQueryInfo* pQueryInfo, SQuerySQL* pQuerySQL) {
H
hzcheng 已提交
3746 3747 3748 3749
  tVariantList*     pFillToken = pQuerySQL->fillType;
  tVariantListItem* pItem = &pFillToken->a[0];

  const int32_t START_INTERPO_COL_IDX = 1;
3750 3751 3752 3753

  const char* msg = "illegal value or data overflow";
  const char* msg1 = "value is expected";
  const char* msg2 = "invalid fill option";
H
hzcheng 已提交
3754 3755

  if (pItem->pVar.nType != TSDB_DATA_TYPE_BINARY) {
3756
    return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
3757 3758
  }

3759 3760 3761 3762 3763 3764 3765
  if (pQueryInfo->defaultVal == NULL) {
    pQueryInfo->defaultVal = calloc(pQueryInfo->fieldsInfo.numOfOutputCols, sizeof(int64_t));
    if (pQueryInfo->defaultVal == NULL) {
      return TSDB_CODE_CLI_OUT_OF_MEMORY;
    }
  }

H
hzcheng 已提交
3766
  if (strncasecmp(pItem->pVar.pz, "none", 4) == 0 && pItem->pVar.nLen == 4) {
3767
    pQueryInfo->interpoType = TSDB_INTERPO_NONE;
H
hzcheng 已提交
3768
  } else if (strncasecmp(pItem->pVar.pz, "null", 4) == 0 && pItem->pVar.nLen == 4) {
3769 3770 3771 3772
    pQueryInfo->interpoType = TSDB_INTERPO_NULL;
    for (int32_t i = START_INTERPO_COL_IDX; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
      TAOS_FIELD* pFields = tscFieldInfoGetField(pQueryInfo, i);
      setNull((char*)&pQueryInfo->defaultVal[i], pFields->type, pFields->bytes);
H
hzcheng 已提交
3773 3774
    }
  } else if (strncasecmp(pItem->pVar.pz, "prev", 4) == 0 && pItem->pVar.nLen == 4) {
3775
    pQueryInfo->interpoType = TSDB_INTERPO_PREV;
H
hzcheng 已提交
3776
  } else if (strncasecmp(pItem->pVar.pz, "linear", 6) == 0 && pItem->pVar.nLen == 6) {
3777
    pQueryInfo->interpoType = TSDB_INTERPO_LINEAR;
H
hzcheng 已提交
3778
  } else if (strncasecmp(pItem->pVar.pz, "value", 5) == 0 && pItem->pVar.nLen == 5) {
3779
    pQueryInfo->interpoType = TSDB_INTERPO_SET_VALUE;
H
hzcheng 已提交
3780 3781

    if (pFillToken->nExpr == 1) {
3782
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
3783 3784 3785 3786 3787 3788
    }

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

    /* for point interpolation query, we do not have the timestamp column */
3789
    if (tscIsPointInterpQuery(pQueryInfo)) {
H
hzcheng 已提交
3790 3791
      startPos = 0;

3792 3793
      if (numOfFillVal > pQueryInfo->fieldsInfo.numOfOutputCols) {
        numOfFillVal = pQueryInfo->fieldsInfo.numOfOutputCols;
H
hzcheng 已提交
3794 3795
      }
    } else {
3796 3797 3798
      numOfFillVal = (pFillToken->nExpr > pQueryInfo->fieldsInfo.numOfOutputCols)
                         ? pQueryInfo->fieldsInfo.numOfOutputCols
                         : pFillToken->nExpr;
H
hzcheng 已提交
3799 3800 3801 3802 3803
    }

    int32_t j = 1;

    for (int32_t i = startPos; i < numOfFillVal; ++i, ++j) {
3804
      TAOS_FIELD* pFields = tscFieldInfoGetField(pQueryInfo, i);
3805 3806 3807 3808 3809 3810
  
      if (pFields->type == TSDB_DATA_TYPE_BINARY || pFields->type == TSDB_DATA_TYPE_NCHAR) {
        setNull((char*)(&pQueryInfo->defaultVal[i]), pFields->type, pFields->bytes);
        continue;
      }
      
3811
      int32_t ret = tVariantDump(&pFillToken->a[j].pVar, (char*)&pQueryInfo->defaultVal[i], pFields->type);
H
hzcheng 已提交
3812
      if (ret != TSDB_CODE_SUCCESS) {
3813
        return invalidSqlErrMsg(pQueryInfo->msg, msg);
H
hzcheng 已提交
3814 3815 3816
      }
    }

3817 3818
    if ((pFillToken->nExpr < pQueryInfo->fieldsInfo.numOfOutputCols) ||
        ((pFillToken->nExpr - 1 < pQueryInfo->fieldsInfo.numOfOutputCols) && (tscIsPointInterpQuery(pQueryInfo)))) {
H
hzcheng 已提交
3819 3820
      tVariantListItem* lastItem = &pFillToken->a[pFillToken->nExpr - 1];

3821 3822 3823
      for (int32_t i = numOfFillVal; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
        TAOS_FIELD* pFields = tscFieldInfoGetField(pQueryInfo, i);
        tVariantDump(&lastItem->pVar, (char*)&pQueryInfo->defaultVal[i], pFields->type);
H
hzcheng 已提交
3824 3825

        if (pFields->type == TSDB_DATA_TYPE_BINARY || pFields->type == TSDB_DATA_TYPE_NCHAR) {
3826
          setNull((char*)(&pQueryInfo->defaultVal[i]), pFields->type, pFields->bytes);
H
hzcheng 已提交
3827 3828 3829 3830
        }
      }
    }
  } else {
3831
    return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
3832 3833 3834 3835 3836
  }

  return TSDB_CODE_SUCCESS;
}

3837
static void setDefaultOrderInfo(SQueryInfo* pQueryInfo) {
H
hzcheng 已提交
3838
  /* set default timestamp order information for all queries */
3839 3840
  pQueryInfo->order.order = TSQL_SO_ASC;
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
H
hzcheng 已提交
3841

3842 3843 3844
  if (isTopBottomQuery(pQueryInfo)) {
    pQueryInfo->order.order = TSQL_SO_ASC;
    pQueryInfo->order.orderColId = PRIMARYKEY_TIMESTAMP_COL_INDEX;
H
hzcheng 已提交
3845
  } else {
3846
    pQueryInfo->order.orderColId = -1;
H
hzcheng 已提交
3847 3848 3849
  }

  /* for metric query, set default ascending order for group output */
3850 3851
  if (UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {
    pQueryInfo->groupbyExpr.orderType = TSQL_SO_ASC;
H
hzcheng 已提交
3852 3853 3854
  }
}

3855
int32_t parseOrderbyClause(SQueryInfo* pQueryInfo, SQuerySQL* pQuerySql, SSchema* pSchema, int32_t numOfCols) {
S
slguan 已提交
3856 3857 3858 3859
  const char* msg0 = "only support order by primary timestamp";
  const char* msg1 = "invalid column name";
  const char* msg2 = "only support order by primary timestamp and queried column";
  const char* msg3 = "only support order by primary timestamp and first tag in groupby clause";
H
hzcheng 已提交
3860

3861 3862
  setDefaultOrderInfo(pQueryInfo);
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
H
hzcheng 已提交
3863 3864 3865 3866 3867 3868

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

  tVariantList* pSortorder = pQuerySql->pSortOrder;
S
slguan 已提交
3869 3870 3871 3872 3873 3874 3875 3876

  /*
   * for table query, there is only one or none order option is allowed, which is the
   * ts or values(top/bottom) order is supported.
   *
   * for super table query, the order option must be less than 3.
   */
  if (UTIL_METER_IS_NOMRAL_METER(pMeterMetaInfo)) {
H
hzcheng 已提交
3877
    if (pSortorder->nExpr > 1) {
3878
      return invalidSqlErrMsg(pQueryInfo->msg, msg0);
H
hzcheng 已提交
3879 3880 3881
    }
  } else {
    if (pSortorder->nExpr > 2) {
3882
      return invalidSqlErrMsg(pQueryInfo->msg, msg3);
H
hzcheng 已提交
3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893
    }
  }

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

S
slguan 已提交
3894 3895 3896
  SSQLToken    columnName = {pVar->nLen, pVar->nType, pVar->pz};
  SColumnIndex index = {0};

3897 3898 3899
  if (UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {  // metric query
    if (getColumnIndexByNameEx(&columnName, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
3900 3901 3902 3903
    }

    bool orderByTags = false;
    bool orderByTS = false;
H
hzcheng 已提交
3904

S
slguan 已提交
3905 3906
    if (index.columnIndex >= pMeterMetaInfo->pMeterMeta->numOfColumns) {
      int32_t relTagIndex = index.columnIndex - pMeterMetaInfo->pMeterMeta->numOfColumns;
3907
      if (relTagIndex == pQueryInfo->groupbyExpr.columnInfo[0].colIdx) {
H
hzcheng 已提交
3908 3909
        orderByTags = true;
      }
S
slguan 已提交
3910 3911
    } else if (index.columnIndex == TSDB_TBNAME_COLUMN_INDEX) {
      orderByTags = true;
H
hzcheng 已提交
3912 3913
    }

S
slguan 已提交
3914
    if (PRIMARYKEY_TIMESTAMP_COL_INDEX == index.columnIndex) {
H
hzcheng 已提交
3915 3916 3917
      orderByTS = true;
    }

3918 3919
    if (!(orderByTags || orderByTS) && !isTopBottomQuery(pQueryInfo)) {
      return invalidSqlErrMsg(pQueryInfo->msg, msg3);
H
hzcheng 已提交
3920 3921 3922 3923 3924 3925
    } else {
      assert(!(orderByTags && orderByTS));
    }

    if (pSortorder->nExpr == 1) {
      if (orderByTags) {
3926 3927 3928
        pQueryInfo->groupbyExpr.orderIndex = index.columnIndex - pMeterMetaInfo->pMeterMeta->numOfColumns;
        pQueryInfo->groupbyExpr.orderType = pQuerySql->pSortOrder->a[0].sortOrder;
      } else if (isTopBottomQuery(pQueryInfo)) {
S
slguan 已提交
3929
        /* order of top/bottom query in interval is not valid  */
3930
        SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, 0);
S
slguan 已提交
3931 3932
        assert(pExpr->functionId == TSDB_FUNC_TS);

3933
        pExpr = tscSqlExprGet(pQueryInfo, 1);
S
slguan 已提交
3934
        if (pExpr->colInfo.colIdx != index.columnIndex && index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_INDEX) {
3935
          return invalidSqlErrMsg(pQueryInfo->msg, msg2);
S
slguan 已提交
3936
        }
3937

3938 3939
        pQueryInfo->order.order = pQuerySql->pSortOrder->a[0].sortOrder;
        pQueryInfo->order.orderColId = pSchema[index.columnIndex].colId;
S
slguan 已提交
3940
        return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
3941
      } else {
3942 3943
        pQueryInfo->order.order = pSortorder->a[0].sortOrder;
        pQueryInfo->order.orderColId = PRIMARYKEY_TIMESTAMP_COL_INDEX;
H
hzcheng 已提交
3944 3945 3946 3947
      }
    }

    if (pSortorder->nExpr == 2) {
S
slguan 已提交
3948
      if (orderByTags) {
3949 3950
        pQueryInfo->groupbyExpr.orderIndex = index.columnIndex - pMeterMetaInfo->pMeterMeta->numOfColumns;
        pQueryInfo->groupbyExpr.orderType = pQuerySql->pSortOrder->a[0].sortOrder;
S
slguan 已提交
3951
      } else {
3952 3953
        pQueryInfo->order.order = pSortorder->a[0].sortOrder;
        pQueryInfo->order.orderColId = PRIMARYKEY_TIMESTAMP_COL_INDEX;
S
slguan 已提交
3954 3955
      }

H
hzcheng 已提交
3956 3957
      tVariant* pVar2 = &pSortorder->a[1].pVar;
      SSQLToken cname = {pVar2->nLen, pVar2->nType, pVar2->pz};
3958 3959
      if (getColumnIndexByNameEx(&cname, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
        return invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
3960 3961 3962
      }

      if (index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_INDEX) {
3963
        return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
3964
      } else {
3965 3966
        pQueryInfo->order.order = pSortorder->a[1].sortOrder;
        pQueryInfo->order.orderColId = PRIMARYKEY_TIMESTAMP_COL_INDEX;
H
hzcheng 已提交
3967 3968 3969 3970
      }
    }

  } else {  // meter query
3971 3972
    if (getColumnIndexByNameEx(&columnName, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
3973 3974
    }

3975 3976
    if (index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_INDEX && !isTopBottomQuery(pQueryInfo)) {
      return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
3977 3978
    }

3979
    if (isTopBottomQuery(pQueryInfo)) {
H
hzcheng 已提交
3980
      /* order of top/bottom query in interval is not valid  */
3981
      SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, 0);
S
slguan 已提交
3982
      assert(pExpr->functionId == TSDB_FUNC_TS);
H
hzcheng 已提交
3983

3984
      pExpr = tscSqlExprGet(pQueryInfo, 1);
S
slguan 已提交
3985
      if (pExpr->colInfo.colIdx != index.columnIndex && index.columnIndex != PRIMARYKEY_TIMESTAMP_COL_INDEX) {
3986
        return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
3987
      }
3988

3989 3990
      pQueryInfo->order.order = pQuerySql->pSortOrder->a[0].sortOrder;
      pQueryInfo->order.orderColId = pSchema[index.columnIndex].colId;
H
hzcheng 已提交
3991 3992
      return TSDB_CODE_SUCCESS;
    }
3993

3994
    pQueryInfo->order.order = pQuerySql->pSortOrder->a[0].sortOrder;
H
hzcheng 已提交
3995 3996 3997 3998 3999 4000
  }

  return TSDB_CODE_SUCCESS;
}

int32_t setAlterTableInfo(SSqlObj* pSql, struct SSqlInfo* pInfo) {
S
slguan 已提交
4001
  const int32_t DEFAULT_TABLE_INDEX = 0;
4002

4003 4004 4005 4006 4007 4008
  const char* msg1 = "invalid table name";
  const char* msg2 = "table name too long";
  const char* msg3 = "manipulation of tag available for super table";
  const char* msg4 = "set tag value only available for table";
  const char* msg5 = "only support add one tag";
  const char* msg6 = "column can only be modified by super table";
S
slguan 已提交
4009 4010

  SSqlCmd*        pCmd = &pSql->cmd;
H
hzcheng 已提交
4011
  SAlterTableSQL* pAlterSQL = pInfo->pAlterInfo;
4012 4013
  SQueryInfo*     pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

4014
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, DEFAULT_TABLE_INDEX);
H
hzcheng 已提交
4015

4016
  if (tscValidateName(&(pAlterSQL->name)) != TSDB_CODE_SUCCESS) {
4017
    return invalidSqlErrMsg(pQueryInfo->msg, msg1);
4018
  }
P
plum-lihui 已提交
4019

4020
  if (setMeterID(pMeterMetaInfo, &(pAlterSQL->name), pSql) != TSDB_CODE_SUCCESS) {
4021
    return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
4022 4023
  }

4024
  int32_t ret = tscGetMeterMeta(pSql, pMeterMetaInfo);
H
hzcheng 已提交
4025 4026 4027 4028
  if (ret != TSDB_CODE_SUCCESS) {
    return ret;
  }

S
slguan 已提交
4029
  SMeterMeta* pMeterMeta = pMeterMetaInfo->pMeterMeta;
H
hzcheng 已提交
4030

4031 4032
  if (pAlterSQL->type == TSDB_ALTER_TABLE_ADD_TAG_COLUMN || pAlterSQL->type == TSDB_ALTER_TABLE_DROP_TAG_COLUMN ||
      pAlterSQL->type == TSDB_ALTER_TABLE_CHANGE_TAG_COLUMN) {
S
slguan 已提交
4033
    if (UTIL_METER_IS_NOMRAL_METER(pMeterMetaInfo)) {
4034
      return invalidSqlErrMsg(pQueryInfo->msg, msg3);
H
hzcheng 已提交
4035
    }
4036 4037
  } else if ((pAlterSQL->type == TSDB_ALTER_TABLE_UPDATE_TAG_VAL) && (UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo))) {
    return invalidSqlErrMsg(pQueryInfo->msg, msg4);
4038
  } else if ((pAlterSQL->type == TSDB_ALTER_TABLE_ADD_COLUMN || pAlterSQL->type == TSDB_ALTER_TABLE_DROP_COLUMN) &&
S
slguan 已提交
4039
             UTIL_METER_IS_CREATE_FROM_METRIC(pMeterMetaInfo)) {
4040
    return invalidSqlErrMsg(pQueryInfo->msg, msg6);
H
hzcheng 已提交
4041 4042
  }

4043
  if (pAlterSQL->type == TSDB_ALTER_TABLE_ADD_TAG_COLUMN) {
H
hzcheng 已提交
4044 4045
    tFieldList* pFieldList = pAlterSQL->pAddColumns;
    if (pFieldList->nField > 1) {
4046
      return invalidSqlErrMsg(pQueryInfo->msg, msg5);
H
hzcheng 已提交
4047 4048 4049 4050 4051 4052
    }

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

4053
    tscFieldInfoSetValFromField(&pQueryInfo->fieldsInfo, 0, &pFieldList->p[0]);
4054
  } else if (pAlterSQL->type == TSDB_ALTER_TABLE_DROP_TAG_COLUMN) {
4055 4056 4057 4058 4059
    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 已提交
4060 4061

    if (pMeterMeta->numOfTags == 1) {
4062
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
4063 4064 4065 4066
    }

    // numOfTags == 1
    if (pAlterSQL->varList->nExpr > 1) {
4067
      return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
4068 4069 4070 4071
    }

    tVariantListItem* pItem = &pAlterSQL->varList->a[0];
    if (pItem->pVar.nLen > TSDB_COL_NAME_LEN) {
4072
      return invalidSqlErrMsg(pQueryInfo->msg, msg3);
H
hzcheng 已提交
4073
    }
4074

4075
    SColumnIndex index = COLUMN_INDEX_INITIALIZER;
4076 4077 4078
    SSQLToken    name = {.z = pItem->pVar.pz, .n = pItem->pVar.nLen, .type = TK_STRING};

    if (getColumnIndexByNameEx(&name, pQueryInfo, &index) != TSDB_CODE_SUCCESS) {
4079
      return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
4080 4081
    }

4082
    if (index.columnIndex < pMeterMeta->numOfColumns) {
4083
      return invalidSqlErrMsg(pQueryInfo->msg, msg4);
4084
    } else if (index.columnIndex == 0) {
4085
      return invalidSqlErrMsg(pQueryInfo->msg, msg5);
H
hzcheng 已提交
4086 4087
    }

4088 4089
    char name1[128] = {0};
    strncpy(name1, pItem->pVar.pz, pItem->pVar.nLen);
4090 4091
    tscFieldInfoSetValue(&pQueryInfo->fieldsInfo, 0, TSDB_DATA_TYPE_INT, name1,
                         tDataTypeDesc[TSDB_DATA_TYPE_INT].nSize);
4092
  } else if (pAlterSQL->type == TSDB_ALTER_TABLE_CHANGE_TAG_COLUMN) {
4093 4094
    const char* msg1 = "tag name too long";
    const char* msg2 = "invalid tag name";
4095

H
hzcheng 已提交
4096 4097 4098 4099 4100
    tVariantList* pVarList = pAlterSQL->varList;
    if (pVarList->nExpr > 2) {
      return TSDB_CODE_INVALID_SQL;
    }

4101 4102 4103 4104
    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) {
4105
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
4106 4107
    }

4108
    if (pSrcItem->pVar.nType != TSDB_DATA_TYPE_BINARY || pDstItem->pVar.nType != TSDB_DATA_TYPE_BINARY) {
4109
      return invalidSqlErrMsg(pQueryInfo->msg, msg2);
4110
    }
H
hzcheng 已提交
4111

S
slguan 已提交
4112 4113
    SColumnIndex srcIndex = COLUMN_INDEX_INITIALIZER;
    SColumnIndex destIndex = COLUMN_INDEX_INITIALIZER;
H
hzcheng 已提交
4114

S
slguan 已提交
4115
    SSQLToken srcToken = {.z = pSrcItem->pVar.pz, .n = pSrcItem->pVar.nLen, .type = TK_STRING};
4116
    if (getColumnIndexByNameEx(&srcToken, pQueryInfo, &srcIndex) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
4117
      return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
4118 4119
    }

S
slguan 已提交
4120
    SSQLToken destToken = {.z = pDstItem->pVar.pz, .n = pDstItem->pVar.nLen, .type = TK_STRING};
4121
    if (getColumnIndexByNameEx(&destToken, pQueryInfo, &destIndex) == TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
4122 4123 4124 4125 4126
      return TSDB_CODE_INVALID_SQL;
    }

    char name[128] = {0};
    strncpy(name, pVarList->a[0].pVar.pz, pVarList->a[0].pVar.nLen);
4127
    tscFieldInfoSetValue(&pQueryInfo->fieldsInfo, 0, TSDB_DATA_TYPE_INT, name, tDataTypeDesc[TSDB_DATA_TYPE_INT].nSize);
H
hzcheng 已提交
4128 4129 4130

    memset(name, 0, tListLen(name));
    strncpy(name, pVarList->a[1].pVar.pz, pVarList->a[1].pVar.nLen);
4131
    tscFieldInfoSetValue(&pQueryInfo->fieldsInfo, 1, TSDB_DATA_TYPE_INT, name, tDataTypeDesc[TSDB_DATA_TYPE_INT].nSize);
4132
  } else if (pAlterSQL->type == TSDB_ALTER_TABLE_UPDATE_TAG_VAL) {
S
slguan 已提交
4133
    const char* msg1 = "invalid tag value";
4134
    const char* msg2 = "update normal column not supported";
S
slguan 已提交
4135 4136
    const char* msg3 = "tag value too long";

4137 4138
    // Note: update can only be applied to table not super table.
    // the following is handle display tags value for meters created according to super table
H
hzcheng 已提交
4139 4140 4141
    tVariantList* pVarList = pAlterSQL->varList;
    tVariant*     pTagName = &pVarList->a[0].pVar;

4142 4143
    SColumnIndex columnIndex = COLUMN_INDEX_INITIALIZER;
    SSQLToken    name = {.type = TK_STRING, .z = pTagName->pz, .n = pTagName->nLen};
4144
    if (getColumnIndexByNameEx(&name, pQueryInfo, &columnIndex) != TSDB_CODE_SUCCESS) {
4145
      return TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
4146 4147
    }

4148
    if (columnIndex.columnIndex < pMeterMeta->numOfColumns) {
4149
      return invalidSqlErrMsg(pQueryInfo->msg, msg2);
S
slguan 已提交
4150 4151
    }

4152
    SSchema* pTagsSchema = tsGetColumnSchema(pMeterMetaInfo->pMeterMeta, columnIndex.columnIndex);
4153 4154 4155
    if (tVariantDump(&pVarList->a[1].pVar, pAlterSQL->tagData.data /*pCmd->payload*/, pTagsSchema->type) !=
        TSDB_CODE_SUCCESS) {
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
4156 4157 4158
    }

    // validate the length of binary
4159 4160
    if ((pTagsSchema->type == TSDB_DATA_TYPE_BINARY || pTagsSchema->type == TSDB_DATA_TYPE_NCHAR) &&
        pVarList->a[1].pVar.nLen > pTagsSchema->bytes) {
4161
      return invalidSqlErrMsg(pQueryInfo->msg, msg3);
H
hzcheng 已提交
4162 4163
    }

4164 4165
    char name1[128] = {0};
    strncpy(name1, pTagName->pz, pTagName->nLen);
4166 4167
    tscFieldInfoSetValue(&pQueryInfo->fieldsInfo, 0, TSDB_DATA_TYPE_INT, name1,
                         tDataTypeDesc[TSDB_DATA_TYPE_INT].nSize);
H
hzcheng 已提交
4168

4169
  } else if (pAlterSQL->type == TSDB_ALTER_TABLE_ADD_COLUMN) {
H
hzcheng 已提交
4170 4171
    tFieldList* pFieldList = pAlterSQL->pAddColumns;
    if (pFieldList->nField > 1) {
4172
      const char* msg = "only support add one column";
4173
      return invalidSqlErrMsg(pQueryInfo->msg, msg);
H
hzcheng 已提交
4174 4175 4176 4177 4178 4179
    }

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

4180
    tscFieldInfoSetValFromField(&pQueryInfo->fieldsInfo, 0, &pFieldList->p[0]);
4181
  } else if (pAlterSQL->type == TSDB_ALTER_TABLE_DROP_COLUMN) {
4182 4183 4184
    const char* msg1 = "no columns can be dropped";
    const char* msg2 = "only support one column";
    const char* msg4 = "illegal column name";
4185
    const char* msg3 = "primary timestamp column cannot be dropped";
H
hzcheng 已提交
4186 4187

    if (pMeterMeta->numOfColumns == TSDB_MIN_COLUMNS) {  //
4188
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
H
hzcheng 已提交
4189 4190 4191
    }

    if (pAlterSQL->varList->nExpr > 1) {
4192
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
H
hzcheng 已提交
4193 4194 4195 4196
    }

    tVariantListItem* pItem = &pAlterSQL->varList->a[0];

4197 4198
    SColumnIndex columnIndex = COLUMN_INDEX_INITIALIZER;
    SSQLToken    name = {.type = TK_STRING, .z = pItem->pVar.pz, .n = pItem->pVar.nLen};
4199 4200
    if (getColumnIndexByNameEx(&name, pQueryInfo, &columnIndex) != TSDB_CODE_SUCCESS) {
      return invalidSqlErrMsg(pQueryInfo->msg, msg4);
H
hzcheng 已提交
4201 4202
    }

4203
    if (columnIndex.columnIndex == PRIMARYKEY_TIMESTAMP_COL_INDEX) {
4204
      return invalidSqlErrMsg(pQueryInfo->msg, msg3);
4205
    }
H
hzcheng 已提交
4206

4207 4208
    char name1[128] = {0};
    strncpy(name1, pItem->pVar.pz, pItem->pVar.nLen);
4209 4210
    tscFieldInfoSetValue(&pQueryInfo->fieldsInfo, 0, TSDB_DATA_TYPE_INT, name1,
                         tDataTypeDesc[TSDB_DATA_TYPE_INT].nSize);
H
hzcheng 已提交
4211 4212 4213 4214 4215
  }

  return TSDB_CODE_SUCCESS;
}

4216
int32_t validateSqlFunctionInStreamSql(SQueryInfo* pQueryInfo) {
4217 4218
  const char* msg0 = "sample interval can not be less than 10ms.";
  const char* msg1 = "functions not allowed in select clause";
H
hzcheng 已提交
4219

4220 4221
  if (pQueryInfo->nAggTimeInterval != 0 && pQueryInfo->nAggTimeInterval < 10) {
    return invalidSqlErrMsg(pQueryInfo->msg, msg0);
H
hzcheng 已提交
4222 4223
  }

4224 4225
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    int32_t functId = tscSqlExprGet(pQueryInfo, i)->functionId;
H
hzcheng 已提交
4226
    if (!IS_STREAM_QUERY_VALID(aAggs[functId].nStatus)) {
4227
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
4228 4229 4230 4231 4232 4233
    }
  }

  return TSDB_CODE_SUCCESS;
}

4234
int32_t validateFunctionsInIntervalOrGroupbyQuery(SQueryInfo* pQueryInfo) {
S
slguan 已提交
4235
  bool        isProjectionFunction = false;
4236
  const char* msg1 = "column projection is not compatible with interval";
H
hjxilinx 已提交
4237

H
hzcheng 已提交
4238
  // multi-output set/ todo refactor
4239 4240
  for (int32_t k = 0; k < pQueryInfo->fieldsInfo.numOfOutputCols; ++k) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, k);
H
hjxilinx 已提交
4241

4242 4243 4244
    // projection query on primary timestamp, the selectivity function needs to be present.
    if (pExpr->functionId == TSDB_FUNC_PRJ && pExpr->colInfo.colId == PRIMARYKEY_TIMESTAMP_COL_INDEX) {
      bool hasSelectivity = false;
4245 4246
      for (int32_t j = 0; j < pQueryInfo->fieldsInfo.numOfOutputCols; ++j) {
        SSqlExpr* pEx = tscSqlExprGet(pQueryInfo, j);
4247 4248 4249 4250 4251
        if ((aAggs[pEx->functionId].nStatus & TSDB_FUNCSTATE_SELECTIVITY) == TSDB_FUNCSTATE_SELECTIVITY) {
          hasSelectivity = true;
          break;
        }
      }
H
hjxilinx 已提交
4252

4253 4254 4255 4256
      if (hasSelectivity) {
        continue;
      }
    }
H
hjxilinx 已提交
4257

S
slguan 已提交
4258
    if (pExpr->functionId == TSDB_FUNC_PRJ || pExpr->functionId == TSDB_FUNC_DIFF ||
H
hjxilinx 已提交
4259
        pExpr->functionId == TSDB_FUNC_ARITHM) {
H
hzcheng 已提交
4260 4261 4262
      isProjectionFunction = true;
    }
  }
S
slguan 已提交
4263 4264

  if (isProjectionFunction) {
4265
    invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
4266 4267 4268 4269 4270 4271
  }

  return isProjectionFunction == true ? TSDB_CODE_INVALID_SQL : TSDB_CODE_SUCCESS;
}

typedef struct SDNodeDynConfOption {
H
hjxilinx 已提交
4272 4273
  char*   name;  // command name
  int32_t len;   // name string length
H
hzcheng 已提交
4274 4275 4276 4277 4278 4279 4280
} SDNodeDynConfOption;

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

H
hjxilinx 已提交
4281
  const SDNodeDynConfOption DNODE_DYNAMIC_CFG_OPTIONS[14] = {
S
slguan 已提交
4282
      {"resetLog", 8},      {"resetQueryCache", 15}, {"dDebugFlag", 10},       {"rpcDebugFlag", 12},
H
hzcheng 已提交
4283 4284
      {"tmrDebugFlag", 12}, {"cDebugFlag", 10},      {"uDebugFlag", 10},       {"mDebugFlag", 10},
      {"sdbDebugFlag", 12}, {"httpDebugFlag", 13},   {"monitorDebugFlag", 16}, {"qDebugflag", 10},
S
slguan 已提交
4285
      {"debugFlag", 9},     {"monitor", 7}};
H
hzcheng 已提交
4286 4287 4288 4289 4290 4291

  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) {
H
hjxilinx 已提交
4292
      const SDNodeDynConfOption* pOption = &DNODE_DYNAMIC_CFG_OPTIONS[i];
H
hzcheng 已提交
4293 4294 4295 4296
      if ((strncasecmp(pOption->name, pOptionToken->z, pOptionToken->n) == 0) && (pOption->len == pOptionToken->n)) {
        return TSDB_CODE_SUCCESS;
      }
    }
S
slguan 已提交
4297 4298 4299 4300 4301 4302 4303 4304
  } else if ((strncasecmp(DNODE_DYNAMIC_CFG_OPTIONS[13].name, pOptionToken->z, pOptionToken->n) == 0) &&
             (DNODE_DYNAMIC_CFG_OPTIONS[13].len == pOptionToken->n)) {
    SSQLToken* pValToken = &pOptions->a[2];
    int32_t    val = strtol(pValToken->z, NULL, 10);
    if (val != 0 && val != 1) {
      return TSDB_CODE_INVALID_SQL;  // options value is invalid
    }
    return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
4305 4306 4307 4308 4309 4310 4311 4312 4313
  } 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;
    }

S
slguan 已提交
4314
    for (int32_t i = 2; i < tListLen(DNODE_DYNAMIC_CFG_OPTIONS) - 1; ++i) {
H
hjxilinx 已提交
4315
      const SDNodeDynConfOption* pOption = &DNODE_DYNAMIC_CFG_OPTIONS[i];
H
hzcheng 已提交
4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326

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

S
slguan 已提交
4327 4328 4329 4330 4331
int32_t validateLocalConfig(tDCLSQL* pOptions) {
  if (pOptions->nTokens < 1 || pOptions->nTokens > 2) {
    return TSDB_CODE_INVALID_SQL;
  }

H
hjxilinx 已提交
4332 4333
  SDNodeDynConfOption LOCAL_DYNAMIC_CFG_OPTIONS[6] = {{"resetLog", 8},    {"rpcDebugFlag", 12}, {"tmrDebugFlag", 12},
                                                      {"cDebugFlag", 10}, {"uDebugFlag", 10},   {"debugFlag", 9}};
S
slguan 已提交
4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364

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

  if (pOptions->nTokens == 1) {
    // reset log does not need value
    for (int32_t i = 0; i < 1; ++i) {
      SDNodeDynConfOption* pOption = &LOCAL_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[1];

    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 = 1; i < tListLen(LOCAL_DYNAMIC_CFG_OPTIONS); ++i) {
      SDNodeDynConfOption* pOption = &LOCAL_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;
}

H
hzcheng 已提交
4365 4366 4367 4368 4369 4370
int32_t validateColumnName(char* name) {
  bool ret = isKeyWord(name, strlen(name));
  if (ret) {
    return TSDB_CODE_INVALID_SQL;
  }

S
slguan 已提交
4371
  SSQLToken token = {.z = name};
H
hzcheng 已提交
4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397
  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;
}

4398 4399
bool hasTimestampForPointInterpQuery(SQueryInfo* pQueryInfo) {
  if (!tscIsPointInterpQuery(pQueryInfo)) {
H
hzcheng 已提交
4400 4401 4402
    return true;
  }

4403
  return (pQueryInfo->stime == pQueryInfo->etime) && (pQueryInfo->stime != 0);
H
hzcheng 已提交
4404 4405
}

4406
int32_t parseLimitClause(SSqlObj* pSql, int32_t subClauseIndex, SQuerySQL* pQuerySql) {
S
slguan 已提交
4407
  SSqlCmd*        pCmd = &pSql->cmd;
4408
  SQueryInfo*     pQueryInfo = tscGetQueryInfoDetail(pCmd, subClauseIndex);
4409
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
H
hzcheng 已提交
4410

S
slguan 已提交
4411 4412 4413 4414
  const char* msg0 = "soffset/offset can not be less than 0";
  const char* msg1 = "slimit/soffset only available for STable query";
  const char* msg2 = "function not supported on table";
  const char* msg3 = "slimit/soffset can not apply to projection query";
H
hzcheng 已提交
4415 4416

  // handle the limit offset value, validate the limit
4417 4418
  pQueryInfo->limit = pQuerySql->limit;
  pCmd->globalLimit = pQueryInfo->limit.limit;
H
hjxilinx 已提交
4419

4420
  pQueryInfo->slimit = pQuerySql->slimit;
H
hzcheng 已提交
4421

4422 4423
  if (pQueryInfo->slimit.offset < 0 || pQueryInfo->limit.offset < 0) {
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg0);
S
slguan 已提交
4424 4425
  }

4426
  if (pQueryInfo->limit.limit == 0) {
S
slguan 已提交
4427 4428 4429 4430
    tscTrace("%p limit 0, no output result", pSql);
    pCmd->command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
  }

4431
  if (UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo)) {
H
hjxilinx 已提交
4432
    bool queryOnTags = false;
4433
    if (tscQueryOnlyMetricTags(pQueryInfo, &queryOnTags) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
4434 4435 4436 4437 4438
      return TSDB_CODE_INVALID_SQL;
    }

    if (queryOnTags == true) {  // local handle the metric tag query
      pCmd->command = TSDB_SQL_RETRIEVE_TAGS;
S
slguan 已提交
4439
    } else {
4440
      if (tscProjectionQueryOnSTable(&pSql->cmd, 0) &&
4441 4442
          (pQueryInfo->slimit.limit > 0 || pQueryInfo->slimit.offset > 0)) {
        return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
S
slguan 已提交
4443
      }
H
hzcheng 已提交
4444 4445
    }

4446
    if (pQueryInfo->slimit.limit == 0) {
H
hzcheng 已提交
4447 4448 4449 4450 4451 4452
      tscTrace("%p limit 0, no output result", pSql);
      pCmd->command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
      return TSDB_CODE_SUCCESS;
    }

    /*
4453 4454 4455 4456
     * Get the distribution of all tables among all available virtual nodes that are qualified for the query condition
     * and created according to this super table from management node.
     * And then launching multiple async-queries against all qualified virtual nodes, during the first-stage
     * query operation.
H
hzcheng 已提交
4457
     */
4458
    int32_t code = tscGetMetricMeta(pSql, 0);
H
hzcheng 已提交
4459 4460 4461 4462
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

S
slguan 已提交
4463 4464 4465
    // No tables included. No results generated. Query results are empty.
    SMetricMeta* pMetricMeta = pMeterMetaInfo->pMetricMeta;
    if (pMeterMetaInfo->pMeterMeta == NULL || pMetricMeta == NULL || pMetricMeta->numOfMeters == 0) {
H
hzcheng 已提交
4466 4467 4468 4469 4470
      tscTrace("%p no table in metricmeta, no output result", pSql);
      pCmd->command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
    }

    // keep original limitation value in globalLimit
4471
    pCmd->globalLimit = pQueryInfo->limit.limit;
H
hzcheng 已提交
4472
  } else {
4473 4474
    if (pQueryInfo->slimit.limit != -1 || pQueryInfo->slimit.offset != 0) {
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hzcheng 已提交
4475 4476
    }

S
slguan 已提交
4477
    // filter the query functions operating on "tbname" column that are not supported by normal columns.
4478 4479
    for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
      SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
4480
      if (pExpr->colInfo.colIdx == TSDB_TBNAME_COLUMN_INDEX) {
4481
        return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hzcheng 已提交
4482 4483 4484 4485 4486 4487
      }
    }
  }

  return TSDB_CODE_SUCCESS;
}
4488

H
hjxilinx 已提交
4489 4490
static int32_t setKeepOption(SSqlCmd* pCmd, SCreateDbMsg* pMsg, SCreateDBInfo* pCreateDb) {
  const char* msg = "invalid number of options";
H
hjxilinx 已提交
4491

4492 4493 4494
  pMsg->daysToKeep = htonl(-1);
  pMsg->daysToKeep1 = htonl(-1);
  pMsg->daysToKeep2 = htonl(-1);
H
hjxilinx 已提交
4495

H
hjxilinx 已提交
4496 4497 4498
  tVariantList* pKeep = pCreateDb->keep;
  if (pKeep != NULL) {
    switch (pKeep->nExpr) {
S
slguan 已提交
4499
      case 1:
H
hjxilinx 已提交
4500
        pMsg->daysToKeep = htonl(pKeep->a[0].pVar.i64Key);
4501 4502
        break;
      case 2: {
H
hjxilinx 已提交
4503 4504
        pMsg->daysToKeep = htonl(pKeep->a[0].pVar.i64Key);
        pMsg->daysToKeep1 = htonl(pKeep->a[1].pVar.i64Key);
4505 4506 4507
        break;
      }
      case 3: {
H
hjxilinx 已提交
4508 4509 4510
        pMsg->daysToKeep = htonl(pKeep->a[0].pVar.i64Key);
        pMsg->daysToKeep1 = htonl(pKeep->a[1].pVar.i64Key);
        pMsg->daysToKeep2 = htonl(pKeep->a[2].pVar.i64Key);
4511 4512
        break;
      }
4513
      default: { return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg); }
4514 4515
    }
  }
H
hjxilinx 已提交
4516

H
hjxilinx 已提交
4517 4518
  return TSDB_CODE_SUCCESS;
}
4519

H
hjxilinx 已提交
4520 4521
static int32_t setTimePrecisionOption(SSqlCmd* pCmd, SCreateDbMsg* pMsg, SCreateDBInfo* pCreateDbInfo) {
  const char* msg = "invalid time precision";
H
hjxilinx 已提交
4522

H
hjxilinx 已提交
4523
  pMsg->precision = TSDB_TIME_PRECISION_MILLI;  // millisecond by default
H
hjxilinx 已提交
4524

H
hjxilinx 已提交
4525
  SSQLToken* pToken = &pCreateDbInfo->precision;
4526 4527
  if (pToken->n > 0) {
    pToken->n = strdequote(pToken->z);
H
hjxilinx 已提交
4528

4529 4530 4531 4532 4533
    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 &&
H
hjxilinx 已提交
4534
               strlen(TSDB_TIME_PRECISION_MICRO_STR) == pToken->n) {
4535 4536
      pMsg->precision = TSDB_TIME_PRECISION_MICRO;
    } else {
4537
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
4538 4539
    }
  }
H
hjxilinx 已提交
4540

H
hjxilinx 已提交
4541 4542
  return TSDB_CODE_SUCCESS;
}
4543

H
hjxilinx 已提交
4544 4545 4546 4547
static void setCreateDBOption(SCreateDbMsg* pMsg, SCreateDBInfo* pCreateDb) {
  pMsg->blocksPerMeter = htons(pCreateDb->numOfBlocksPerTable);
  pMsg->compression = pCreateDb->compressionLevel;

H
hjxilinx 已提交
4548
  pMsg->commitLog = (char)pCreateDb->commitLog;
H
hjxilinx 已提交
4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560
  pMsg->commitTime = htonl(pCreateDb->commitTime);
  pMsg->maxSessions = htonl(pCreateDb->tablesPerVnode);
  pMsg->cacheNumOfBlocks.fraction = pCreateDb->numOfAvgCacheBlocks;
  pMsg->cacheBlockSize = htonl(pCreateDb->cacheBlockSize);
  pMsg->rowsInFileBlock = htonl(pCreateDb->rowPerFileBlock);
  pMsg->daysPerFile = htonl(pCreateDb->daysPerFile);
  pMsg->replications = pCreateDb->replica;
}

int32_t parseCreateDBOptions(SSqlCmd* pCmd, SCreateDBInfo* pCreateDbSql) {
  SCreateDbMsg* pMsg = (SCreateDbMsg*)(pCmd->payload + tsRpcHeadSize + sizeof(SMgmtHead));
  setCreateDBOption(pMsg, pCreateDbSql);
H
hjxilinx 已提交
4561

H
hjxilinx 已提交
4562 4563 4564
  if (setKeepOption(pCmd, pMsg, pCreateDbSql) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_INVALID_SQL;
  }
H
hjxilinx 已提交
4565

H
hjxilinx 已提交
4566 4567 4568
  if (setTimePrecisionOption(pCmd, pMsg, pCreateDbSql) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_INVALID_SQL;
  }
H
hjxilinx 已提交
4569

H
hjxilinx 已提交
4570 4571 4572
  if (tscCheckCreateDbParams(pCmd, pMsg) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_INVALID_SQL;
  }
H
hjxilinx 已提交
4573

4574
  return TSDB_CODE_SUCCESS;
H
huili 已提交
4575
}
S
slguan 已提交
4576

4577
void tscAddTimestampColumn(SQueryInfo* pQueryInfo, int16_t functionId, int16_t tableIndex) {
S
slguan 已提交
4578 4579
  // the first column not timestamp column, add it
  SSqlExpr* pExpr = NULL;
4580 4581
  if (pQueryInfo->exprsInfo.numOfExprs > 0) {
    pExpr = tscSqlExprGet(pQueryInfo, 0);
S
slguan 已提交
4582 4583 4584 4585 4586
  }

  if (pExpr == NULL || pExpr->colInfo.colId != PRIMARYKEY_TIMESTAMP_COL_INDEX || pExpr->functionId != functionId) {
    SColumnIndex index = {tableIndex, PRIMARYKEY_TIMESTAMP_COL_INDEX};

4587
    pExpr = tscSqlExprInsert(pQueryInfo, 0, functionId, &index, TSDB_DATA_TYPE_TIMESTAMP, TSDB_KEYSIZE, TSDB_KEYSIZE);
S
slguan 已提交
4588 4589 4590 4591 4592
    pExpr->colInfo.flag = TSDB_COL_NORMAL;

    // NOTE: tag column does not add to source column list
    SColumnList ids = getColumnList(1, tableIndex, PRIMARYKEY_TIMESTAMP_COL_INDEX);

4593
    insertResultField(pQueryInfo, 0, &ids, TSDB_KEYSIZE, TSDB_DATA_TYPE_TIMESTAMP, "ts");
S
slguan 已提交
4594 4595 4596
  }
}

4597 4598
void addGroupInfoForSubquery(SSqlObj* pParentObj, SSqlObj* pSql, int32_t subClauseIndex, int32_t tableIndex) {
  SQueryInfo* pParentQueryInfo = tscGetQueryInfoDetail(&pParentObj->cmd, subClauseIndex);
4599

4600 4601
  if (pParentQueryInfo->groupbyExpr.numOfGroupCols > 0) {
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, subClauseIndex);
4602 4603
    int32_t     num = pQueryInfo->exprsInfo.numOfExprs;

4604
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, num - 1);
4605

S
slguan 已提交
4606
    if (pExpr->functionId != TSDB_FUNC_TAG) {
4607
      SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, tableIndex);
4608 4609 4610
      int16_t         columnInfo = tscGetJoinTagColIndexByUid(&pQueryInfo->tagCond, pMeterMetaInfo->pMeterMeta->uid);
      SColumnIndex    index = {.tableIndex = 0, .columnIndex = columnInfo};
      SSchema*        pSchema = tsGetTagSchema(pMeterMetaInfo->pMeterMeta);
S
slguan 已提交
4611 4612 4613 4614 4615

      int16_t type = pSchema[index.columnIndex].type;
      int16_t bytes = pSchema[index.columnIndex].bytes;
      char*   name = pSchema[index.columnIndex].name;

4616 4617
      pExpr = tscSqlExprInsert(pQueryInfo, pQueryInfo->fieldsInfo.numOfOutputCols, TSDB_FUNC_TAG, &index, type, bytes,
                               bytes);
S
slguan 已提交
4618 4619 4620 4621
      pExpr->colInfo.flag = TSDB_COL_TAG;

      // NOTE: tag column does not add to source column list
      SColumnList ids = {0};
4622
      insertResultField(pQueryInfo, pQueryInfo->fieldsInfo.numOfOutputCols, &ids, bytes, type, name);
S
slguan 已提交
4623 4624 4625 4626

      int32_t relIndex = index.columnIndex;

      pExpr->colInfo.colIdx = relIndex;
4627
      pQueryInfo->groupbyExpr.columnInfo[0].colIdx = relIndex;
S
slguan 已提交
4628

4629
      addRequiredTagColumn(pQueryInfo, pQueryInfo->groupbyExpr.columnInfo[0].colIdx, 0);
S
slguan 已提交
4630 4631 4632 4633
    }
  }
}

4634 4635
void doAddGroupColumnForSubquery(SQueryInfo* pQueryInfo, int32_t tagIndex) {
  int32_t index = pQueryInfo->groupbyExpr.columnInfo[tagIndex].colIdx;
S
slguan 已提交
4636

4637
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
S
slguan 已提交
4638 4639 4640 4641

  SSchema*     pSchema = tsGetColumnSchema(pMeterMetaInfo->pMeterMeta, index);
  SColumnIndex colIndex = {.tableIndex = 0, .columnIndex = index};

4642 4643
  SSqlExpr* pExpr = tscSqlExprInsert(pQueryInfo, pQueryInfo->fieldsInfo.numOfOutputCols, TSDB_FUNC_PRJ, &colIndex,
                                     pSchema->type, pSchema->bytes, pSchema->bytes);
S
slguan 已提交
4644 4645 4646 4647 4648 4649 4650 4651 4652 4653

  pExpr->colInfo.flag = TSDB_COL_NORMAL;
  pExpr->param[0].i64Key = 1;
  pExpr->numOfParams = 1;

  // NOTE: tag column does not add to source column list
  SColumnList list = {0};
  list.num = 1;
  list.ids[0] = colIndex;

4654 4655 4656
  insertResultField(pQueryInfo, pQueryInfo->fieldsInfo.numOfOutputCols, &list, pSchema->bytes, pSchema->type,
                    pSchema->name);
  tscFieldInfoUpdateVisible(&pQueryInfo->fieldsInfo, pQueryInfo->fieldsInfo.numOfOutputCols - 1, false);
S
slguan 已提交
4657 4658
}

4659
static void doUpdateSqlFunctionForTagPrj(SQueryInfo* pQueryInfo) {
S
slguan 已提交
4660
  int32_t tagLength = 0;
4661 4662
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
4663 4664 4665 4666 4667 4668 4669 4670 4671
    if (pExpr->functionId == TSDB_FUNC_TAGPRJ || pExpr->functionId == TSDB_FUNC_TAG) {
      pExpr->functionId = TSDB_FUNC_TAG_DUMMY;
      tagLength += pExpr->resBytes;
    } else if (pExpr->functionId == TSDB_FUNC_PRJ && pExpr->colInfo.colId == PRIMARYKEY_TIMESTAMP_COL_INDEX) {
      pExpr->functionId = TSDB_FUNC_TS_DUMMY;
      tagLength += pExpr->resBytes;
    }
  }

4672
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
S
slguan 已提交
4673 4674
  SSchema*        pSchema = tsGetSchema(pMeterMetaInfo->pMeterMeta);

4675 4676
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
4677 4678 4679 4680 4681 4682 4683 4684
    if (pExpr->functionId != TSDB_FUNC_TAG_DUMMY && pExpr->functionId != TSDB_FUNC_TS_DUMMY) {
      SSchema* pColSchema = &pSchema[pExpr->colInfo.colIdx];
      getResultDataInfo(pColSchema->type, pColSchema->bytes, pExpr->functionId, pExpr->param[0].i64Key, &pExpr->resType,
                        &pExpr->resBytes, &pExpr->interResBytes, tagLength, true);
    }
  }
}

4685 4686 4687
static void doUpdateSqlFunctionForColPrj(SQueryInfo* pQueryInfo) {
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
H
hjxilinx 已提交
4688 4689
    if (pExpr->functionId == TSDB_FUNC_PRJ) {
      bool qualifiedCol = false;
4690 4691
      for (int32_t j = 0; j < pQueryInfo->groupbyExpr.numOfGroupCols; ++j) {
        if (pExpr->colInfo.colId == pQueryInfo->groupbyExpr.columnInfo[j].colId) {
H
hjxilinx 已提交
4692
          qualifiedCol = true;
H
hjxilinx 已提交
4693

H
hjxilinx 已提交
4694 4695 4696 4697 4698
          pExpr->param[0].i64Key = 1;  // limit the output to be 1 for each state value
          pExpr->numOfParams = 1;
          break;
        }
      }
H
hjxilinx 已提交
4699

H
hjxilinx 已提交
4700 4701 4702 4703 4704
      assert(qualifiedCol);
    }
  }
}

S
slguan 已提交
4705 4706 4707 4708 4709 4710 4711 4712 4713 4714
static bool tagColumnInGroupby(SSqlGroupbyExpr* pGroupbyExpr, int16_t columnId) {
  for (int32_t j = 0; j < pGroupbyExpr->numOfGroupCols; ++j) {
    if (columnId == pGroupbyExpr->columnInfo[j].colId && pGroupbyExpr->columnInfo[j].flag == TSDB_COL_TAG) {
      return true;
    }
  }

  return false;
}

4715
static bool onlyTagPrjFunction(SQueryInfo* pQueryInfo) {
S
slguan 已提交
4716 4717 4718
  bool hasTagPrj = false;
  bool hasColumnPrj = false;

4719 4720
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731
    if (pExpr->functionId == TSDB_FUNC_PRJ) {
      hasColumnPrj = true;
    } else if (pExpr->functionId == TSDB_FUNC_TAGPRJ) {
      hasTagPrj = true;
    }
  }

  return (hasTagPrj) && (hasColumnPrj == false);
}

// check if all the tags prj columns belongs to the group by columns
4732
static bool allTagPrjInGroupby(SQueryInfo* pQueryInfo) {
S
slguan 已提交
4733 4734
  bool allInGroupby = true;

4735 4736
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
4737 4738 4739 4740
    if (pExpr->functionId != TSDB_FUNC_TAGPRJ) {
      continue;
    }

4741
    if (!tagColumnInGroupby(&pQueryInfo->groupbyExpr, pExpr->colInfo.colId)) {
S
slguan 已提交
4742 4743 4744 4745 4746 4747 4748 4749 4750
      allInGroupby = false;
      break;
    }
  }

  // all selected tag columns belong to the group by columns set, always correct
  return allInGroupby;
}

4751 4752 4753
static void updateTagPrjFunction(SQueryInfo* pQueryInfo) {
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765
    if (pExpr->functionId == TSDB_FUNC_TAGPRJ) {
      pExpr->functionId = TSDB_FUNC_TAG;
    }
  }
}

/*
 * check for selectivity function + tags column function both exist.
 * 1. tagprj functions are not compatible with aggregated function when missing "group by" clause
 * 2. if selectivity function and tagprj function both exist, there should be only
 *    one selectivity function exists.
 */
4766
static int32_t checkUpdateTagPrjFunctions(SQueryInfo* pQueryInfo) {
S
slguan 已提交
4767
  const char* msg1 = "only one selectivity function allowed in presence of tags function";
H
hjxilinx 已提交
4768
  const char* msg3 = "aggregation function should not be mixed up with projection";
H
hjxilinx 已提交
4769

S
slguan 已提交
4770 4771 4772 4773
  bool    tagColExists = false;
  int16_t numOfSelectivity = 0;
  int16_t numOfAggregation = 0;

4774 4775
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
4776 4777 4778 4779 4780 4781
    if (pExpr->functionId == TSDB_FUNC_TAGPRJ ||
        (pExpr->functionId == TSDB_FUNC_PRJ && pExpr->colInfo.colId == PRIMARYKEY_TIMESTAMP_COL_INDEX)) {
      tagColExists = true;
      break;
    }
  }
H
hjxilinx 已提交
4782

4783 4784
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
    int16_t functionId = tscSqlExprGet(pQueryInfo, i)->functionId;
4785
    if (functionId == TSDB_FUNC_TAGPRJ || functionId == TSDB_FUNC_PRJ || functionId == TSDB_FUNC_TS ||
H
hjxilinx 已提交
4786
        functionId == TSDB_FUNC_ARITHM) {
H
hjxilinx 已提交
4787
      continue;
S
slguan 已提交
4788
    }
H
hjxilinx 已提交
4789

H
hjxilinx 已提交
4790 4791 4792 4793 4794 4795
    if ((aAggs[functionId].nStatus & TSDB_FUNCSTATE_SELECTIVITY) != 0) {
      numOfSelectivity++;
    } else {
      numOfAggregation++;
    }
  }
H
hjxilinx 已提交
4796

H
hjxilinx 已提交
4797
  if (tagColExists) {  // check if the selectivity function exists
S
slguan 已提交
4798 4799
    // When the tag projection function on tag column that is not in the group by clause, aggregation function and
    // selectivity function exist in select clause is not allowed.
4800
    if (numOfAggregation > 0) {
4801
      return invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
4802 4803 4804 4805 4806 4807
    }

    /*
     *  if numOfSelectivity equals to 0, it is a super table projection query
     */
    if (numOfSelectivity == 1) {
4808 4809
      doUpdateSqlFunctionForTagPrj(pQueryInfo);
      doUpdateSqlFunctionForColPrj(pQueryInfo);
S
slguan 已提交
4810 4811 4812 4813 4814
    } else if (numOfSelectivity > 1) {
      /*
       * If more than one selectivity functions exist, all the selectivity functions must be last_row.
       * Otherwise, return with error code.
       */
4815 4816
      for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
        int16_t functionId = tscSqlExprGet(pQueryInfo, i)->functionId;
S
slguan 已提交
4817 4818 4819 4820 4821
        if (functionId == TSDB_FUNC_TAGPRJ) {
          continue;
        }

        if (((aAggs[functionId].nStatus & TSDB_FUNCSTATE_SELECTIVITY) != 0) && (functionId != TSDB_FUNC_LAST_ROW)) {
4822
          return invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
4823 4824 4825
        }
      }

4826 4827
      doUpdateSqlFunctionForTagPrj(pQueryInfo);
      doUpdateSqlFunctionForColPrj(pQueryInfo);
H
hjxilinx 已提交
4828 4829
    }
  } else {
4830 4831 4832
    if ((pQueryInfo->type & TSDB_QUERY_TYPE_PROJECTION_QUERY) == TSDB_QUERY_TYPE_PROJECTION_QUERY) {
      if (numOfAggregation > 0 && pQueryInfo->groupbyExpr.numOfGroupCols == 0) {
        return invalidSqlErrMsg(pQueryInfo->msg, msg3);
H
hjxilinx 已提交
4833
      }
H
hjxilinx 已提交
4834

H
hjxilinx 已提交
4835 4836
      if (numOfAggregation > 0 || numOfSelectivity > 0) {
        // clear the projection type flag
4837 4838
        pQueryInfo->type &= (~TSDB_QUERY_TYPE_PROJECTION_QUERY);
        doUpdateSqlFunctionForColPrj(pQueryInfo);
H
hjxilinx 已提交
4839
      }
S
slguan 已提交
4840 4841 4842 4843 4844 4845
    }
  }

  return TSDB_CODE_SUCCESS;
}

4846
static int32_t doAddGroupbyColumnsOnDemand(SQueryInfo* pQueryInfo) {
S
slguan 已提交
4847 4848
  const char* msg2 = "interval not allowed in group by normal column";

4849
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
S
slguan 已提交
4850 4851 4852 4853 4854 4855

  SSchema* pSchema = tsGetSchema(pMeterMetaInfo->pMeterMeta);
  int16_t  bytes = 0;
  int16_t  type = 0;
  char*    name = NULL;

4856 4857
  for (int32_t i = 0; i < pQueryInfo->groupbyExpr.numOfGroupCols; ++i) {
    SColIndexEx* pColIndex = &pQueryInfo->groupbyExpr.columnInfo[i];
S
slguan 已提交
4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873

    int16_t colIndex = pColIndex->colIdx;
    if (pColIndex->colIdx == TSDB_TBNAME_COLUMN_INDEX) {
      type = TSDB_DATA_TYPE_BINARY;
      bytes = TSDB_METER_NAME_LEN;
      name = TSQL_TBNAME_L;
    } else {
      colIndex = (TSDB_COL_IS_TAG(pColIndex->flag)) ? pMeterMetaInfo->pMeterMeta->numOfColumns + pColIndex->colIdx
                                                    : pColIndex->colIdx;

      type = pSchema[colIndex].type;
      bytes = pSchema[colIndex].bytes;
      name = pSchema[colIndex].name;
    }

    if (TSDB_COL_IS_TAG(pColIndex->flag)) {
4874
      SColumnIndex index = {.tableIndex = pQueryInfo->groupbyExpr.tableIndex, .columnIndex = colIndex};
S
slguan 已提交
4875

4876 4877
      SSqlExpr* pExpr = tscSqlExprInsert(pQueryInfo, pQueryInfo->fieldsInfo.numOfOutputCols, TSDB_FUNC_TAG, &index,
                                         type, bytes, bytes);
S
slguan 已提交
4878 4879 4880 4881 4882

      pExpr->colInfo.flag = TSDB_COL_TAG;

      // NOTE: tag column does not add to source column list
      SColumnList ids = {0};
4883
      insertResultField(pQueryInfo, pQueryInfo->fieldsInfo.numOfOutputCols, &ids, bytes, type, name);
S
slguan 已提交
4884 4885
    } else {
      // if this query is "group by" normal column, interval is not allowed
4886 4887
      if (pQueryInfo->nAggTimeInterval > 0) {
        return invalidSqlErrMsg(pQueryInfo->msg, msg2);
S
slguan 已提交
4888 4889 4890
      }

      bool hasGroupColumn = false;
4891 4892
      for (int32_t j = 0; j < pQueryInfo->fieldsInfo.numOfOutputCols; ++j) {
        SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, j);
S
slguan 已提交
4893 4894 4895 4896 4897 4898 4899 4900 4901 4902
        if (pExpr->colInfo.colId == pColIndex->colId) {
          break;
        }
      }

      /*
       * if the group by column does not required by user, add this column into the final result set
       * but invisible to user
       */
      if (!hasGroupColumn) {
4903
        doAddGroupColumnForSubquery(pQueryInfo, i);
S
slguan 已提交
4904 4905 4906 4907 4908 4909 4910
      }
    }
  }

  return TSDB_CODE_SUCCESS;
}

4911
int32_t doFunctionsCompatibleCheck(SSqlCmd* pCmd, SQueryInfo* pQueryInfo) {
S
slguan 已提交
4912
  const char* msg1 = "functions/columns not allowed in group by query";
H
hjxilinx 已提交
4913
  const char* msg2 = "projection query on columns not allowed";
S
slguan 已提交
4914
  const char* msg3 = "group by not allowed on projection query";
H
hjxilinx 已提交
4915
  const char* msg4 = "retrieve tags not compatible with group by or interval query";
S
slguan 已提交
4916 4917 4918

  // only retrieve tags, group by is not supportted
  if (pCmd->command == TSDB_SQL_RETRIEVE_TAGS) {
4919 4920
    if (pQueryInfo->groupbyExpr.numOfGroupCols > 0 || pQueryInfo->nAggTimeInterval > 0) {
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg4);
S
slguan 已提交
4921 4922 4923 4924 4925
    } else {
      return TSDB_CODE_SUCCESS;
    }
  }

4926
  if (pQueryInfo->groupbyExpr.numOfGroupCols > 0) {
S
slguan 已提交
4927
    // check if all the tags prj columns belongs to the group by columns
4928 4929 4930
    if (onlyTagPrjFunction(pQueryInfo) && allTagPrjInGroupby(pQueryInfo)) {
      updateTagPrjFunction(pQueryInfo);
      return doAddGroupbyColumnsOnDemand(pQueryInfo);
S
slguan 已提交
4931 4932 4933
    }

    // check all query functions in selection clause, multi-output functions are not allowed
4934 4935
    for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
      SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
S
slguan 已提交
4936 4937 4938 4939 4940 4941
      int32_t   functId = pExpr->functionId;

      /*
       * group by normal columns.
       * Check if the column projection is identical to the group by column or not
       */
4942
      if (functId == TSDB_FUNC_PRJ && pExpr->colInfo.colId != PRIMARYKEY_TIMESTAMP_COL_INDEX) {
S
slguan 已提交
4943
        bool qualified = false;
4944 4945
        for (int32_t j = 0; j < pQueryInfo->groupbyExpr.numOfGroupCols; ++j) {
          SColIndexEx* pColIndex = &pQueryInfo->groupbyExpr.columnInfo[j];
S
slguan 已提交
4946 4947 4948 4949 4950 4951 4952
          if (pColIndex->colId == pExpr->colInfo.colId) {
            qualified = true;
            break;
          }
        }

        if (!qualified) {
4953
          return invalidSqlErrMsg(pQueryInfo->msg, msg2);
S
slguan 已提交
4954 4955 4956 4957
        }
      }

      if (IS_MULTIOUTPUT(aAggs[functId].nStatus) && functId != TSDB_FUNC_TOP && functId != TSDB_FUNC_BOTTOM &&
H
hjxilinx 已提交
4958
          functId != TSDB_FUNC_TAGPRJ && functId != TSDB_FUNC_PRJ) {
4959
        return invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
4960 4961 4962
      }

      if (functId == TSDB_FUNC_COUNT && pExpr->colInfo.colIdx == TSDB_TBNAME_COLUMN_INDEX) {
4963
        return invalidSqlErrMsg(pQueryInfo->msg, msg1);
S
slguan 已提交
4964 4965 4966
      }
    }

4967
    if (checkUpdateTagPrjFunctions(pQueryInfo) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
4968 4969 4970 4971 4972 4973 4974
      return TSDB_CODE_INVALID_SQL;
    }

    /*
     * group by tag function must be not changed the function name, otherwise, the group operation may fail to
     * divide the subset of final result.
     */
4975
    if (doAddGroupbyColumnsOnDemand(pQueryInfo) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
4976 4977 4978 4979
      return TSDB_CODE_INVALID_SQL;
    }

    // projection query on metric does not compatible with "group by" syntax
4980
    if (tscProjectionQueryOnSTable(pCmd, 0)) {
4981
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
S
slguan 已提交
4982
    }
H
hjxilinx 已提交
4983

H
hjxilinx 已提交
4984
    return TSDB_CODE_SUCCESS;
S
slguan 已提交
4985
  } else {
4986
    return checkUpdateTagPrjFunctions(pQueryInfo);
S
slguan 已提交
4987 4988
  }
}
H
hjxilinx 已提交
4989

4990
int32_t doLocalQueryProcess(SQuerySQL* pQuerySql, SSqlCmd* pCmd, int32_t subClauseIndex) {
H
hjxilinx 已提交
4991 4992 4993
  const char* msg1 = "only one expression allowed";
  const char* msg2 = "invalid expression in select clause";
  const char* msg3 = "invalid function";
H
hjxilinx 已提交
4994

4995
  SQueryInfo*   pQueryInfo = tscGetQueryInfoDetail(pCmd, subClauseIndex);
H
hjxilinx 已提交
4996 4997
  tSQLExprList* pExprList = pQuerySql->pSelection;
  if (pExprList->nExpr != 1) {
4998
    return invalidSqlErrMsg(pQueryInfo->msg, msg1);
H
hjxilinx 已提交
4999
  }
H
hjxilinx 已提交
5000

H
hjxilinx 已提交
5001 5002
  tSQLExpr* pExpr = pExprList->a[0].pNode;
  if (pExpr->operand.z == NULL) {
5003
    return invalidSqlErrMsg(pQueryInfo->msg, msg2);
H
hjxilinx 已提交
5004
  }
H
hjxilinx 已提交
5005

H
hjxilinx 已提交
5006
  // TODO redefine the function
H
hjxilinx 已提交
5007 5008 5009 5010 5011 5012
  SDNodeDynConfOption functionsInfo[5] = {{"database()", 10},
                                          {"server_version()", 16},
                                          {"server_status()", 15},
                                          {"client_version()", 16},
                                          {"current_user()", 14}};

H
hjxilinx 已提交
5013
  int32_t index = -1;
H
hjxilinx 已提交
5014
  for (int32_t i = 0; i < tListLen(functionsInfo); ++i) {
H
hjxilinx 已提交
5015
    if (strncasecmp(functionsInfo[i].name, pExpr->operand.z, functionsInfo[i].len) == 0 &&
H
hjxilinx 已提交
5016
        functionsInfo[i].len == pExpr->operand.n) {
H
hjxilinx 已提交
5017 5018 5019 5020
      index = i;
      break;
    }
  }
H
hjxilinx 已提交
5021

5022
  SSqlExpr* pExpr1 = tscSqlExprInsertEmpty(pQueryInfo, 0, TSDB_FUNC_TAG_DUMMY);
H
hjxilinx 已提交
5023 5024 5025 5026 5027
  if (pExprList->a[0].aliasName != NULL) {
    strncpy(pExpr1->aliasName, pExprList->a[0].aliasName, tListLen(pExpr1->aliasName));
  } else {
    strncpy(pExpr1->aliasName, functionsInfo[index].name, tListLen(pExpr1->aliasName));
  }
H
hjxilinx 已提交
5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044

  switch (index) {
    case 0:
      pCmd->command = TSDB_SQL_CURRENT_DB;
      return TSDB_CODE_SUCCESS;
    case 1:
      pCmd->command = TSDB_SQL_SERV_VERSION;
      return TSDB_CODE_SUCCESS;
    case 2:
      pCmd->command = TSDB_SQL_SERV_STATUS;
      return TSDB_CODE_SUCCESS;
    case 3:
      pCmd->command = TSDB_SQL_CLI_VERSION;
      return TSDB_CODE_SUCCESS;
    case 4:
      pCmd->command = TSDB_SQL_CURRENT_USER;
      return TSDB_CODE_SUCCESS;
5045
    default: { return invalidSqlErrMsg(pQueryInfo->msg, msg3); }
H
hjxilinx 已提交
5046 5047
  }
}
H
hjxilinx 已提交
5048 5049

// can only perform the parameters based on the macro definitation
H
hjxilinx 已提交
5050
int32_t tscCheckCreateDbParams(SSqlCmd* pCmd, SCreateDbMsg* pCreate) {
H
hjxilinx 已提交
5051
  char msg[512] = {0};
H
hjxilinx 已提交
5052

H
hjxilinx 已提交
5053 5054
  if (pCreate->commitLog != -1 && (pCreate->commitLog < 0 || pCreate->commitLog > 1)) {
    snprintf(msg, tListLen(msg), "invalid db option commitLog: %d, only 0 or 1 allowed", pCreate->commitLog);
5055
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hjxilinx 已提交
5056
  }
H
hjxilinx 已提交
5057

H
hjxilinx 已提交
5058 5059
  if (pCreate->replications != -1 &&
      (pCreate->replications < TSDB_REPLICA_MIN_NUM || pCreate->replications > TSDB_REPLICA_MAX_NUM)) {
H
hjxilinx 已提交
5060 5061
    snprintf(msg, tListLen(msg), "invalid db option replications: %d valid range: [%d, %d]", pCreate->replications,
             TSDB_REPLICA_MIN_NUM, TSDB_REPLICA_MAX_NUM);
5062
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hjxilinx 已提交
5063
  }
H
hjxilinx 已提交
5064

H
hjxilinx 已提交
5065 5066 5067 5068
  int32_t val = htonl(pCreate->daysPerFile);
  if (val != -1 && (val < TSDB_FILE_MIN_PARTITION_RANGE || val > TSDB_FILE_MAX_PARTITION_RANGE)) {
    snprintf(msg, tListLen(msg), "invalid db option daysPerFile: %d valid range: [%d, %d]", val,
             TSDB_FILE_MIN_PARTITION_RANGE, TSDB_FILE_MAX_PARTITION_RANGE);
5069
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hjxilinx 已提交
5070
  }
H
hjxilinx 已提交
5071

H
hjxilinx 已提交
5072 5073 5074 5075
  val = htonl(pCreate->rowsInFileBlock);
  if (val != -1 && (val < TSDB_MIN_ROWS_IN_FILEBLOCK || val > TSDB_MAX_ROWS_IN_FILEBLOCK)) {
    snprintf(msg, tListLen(msg), "invalid db option rowsInFileBlock: %d valid range: [%d, %d]", val,
             TSDB_MIN_ROWS_IN_FILEBLOCK, TSDB_MAX_ROWS_IN_FILEBLOCK);
5076
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hjxilinx 已提交
5077
  }
H
hjxilinx 已提交
5078

H
hjxilinx 已提交
5079 5080 5081 5082
  val = htonl(pCreate->cacheBlockSize);
  if (val != -1 && (val < TSDB_MIN_CACHE_BLOCK_SIZE || val > TSDB_MAX_CACHE_BLOCK_SIZE)) {
    snprintf(msg, tListLen(msg), "invalid db option cacheBlockSize: %d valid range: [%d, %d]", val,
             TSDB_MIN_CACHE_BLOCK_SIZE, TSDB_MAX_CACHE_BLOCK_SIZE);
5083
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hjxilinx 已提交
5084
  }
H
hjxilinx 已提交
5085

H
hjxilinx 已提交
5086 5087
  val = htonl(pCreate->maxSessions);
  if (val != -1 && (val < TSDB_MIN_TABLES_PER_VNODE || val > TSDB_MAX_TABLES_PER_VNODE)) {
H
hjxilinx 已提交
5088 5089
    snprintf(msg, tListLen(msg), "invalid db option maxSessions: %d valid range: [%d, %d]", val,
             TSDB_MIN_TABLES_PER_VNODE, TSDB_MAX_TABLES_PER_VNODE);
5090
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hjxilinx 已提交
5091
  }
H
hjxilinx 已提交
5092 5093 5094 5095

  if (pCreate->precision != TSDB_TIME_PRECISION_MILLI && pCreate->precision != TSDB_TIME_PRECISION_MICRO) {
    snprintf(msg, tListLen(msg), "invalid db option timePrecision: %d valid value: [%d, %d]", pCreate->precision,
             TSDB_TIME_PRECISION_MILLI, TSDB_TIME_PRECISION_MICRO);
5096
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hjxilinx 已提交
5097
  }
H
hjxilinx 已提交
5098

H
hjxilinx 已提交
5099
  if (pCreate->cacheNumOfBlocks.fraction != -1 && (pCreate->cacheNumOfBlocks.fraction < TSDB_MIN_AVG_BLOCKS ||
H
hjxilinx 已提交
5100 5101 5102
                                                   pCreate->cacheNumOfBlocks.fraction > TSDB_MAX_AVG_BLOCKS)) {
    snprintf(msg, tListLen(msg), "invalid db option ablocks: %f valid value: [%d, %d]",
             pCreate->cacheNumOfBlocks.fraction, TSDB_MIN_AVG_BLOCKS, TSDB_MAX_AVG_BLOCKS);
5103
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hjxilinx 已提交
5104
  }
H
hjxilinx 已提交
5105

H
hjxilinx 已提交
5106 5107 5108 5109
  val = htonl(pCreate->commitTime);
  if (val != -1 && (val < TSDB_MIN_COMMIT_TIME_INTERVAL || val > TSDB_MAX_COMMIT_TIME_INTERVAL)) {
    snprintf(msg, tListLen(msg), "invalid db option commitTime: %d valid range: [%d, %d]", val,
             TSDB_MIN_COMMIT_TIME_INTERVAL, TSDB_MAX_COMMIT_TIME_INTERVAL);
5110
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hjxilinx 已提交
5111
  }
H
hjxilinx 已提交
5112

H
hjxilinx 已提交
5113 5114
  if (pCreate->compression != -1 &&
      (pCreate->compression < TSDB_MIN_COMPRESSION_LEVEL || pCreate->compression > TSDB_MAX_COMPRESSION_LEVEL)) {
H
hjxilinx 已提交
5115 5116
    snprintf(msg, tListLen(msg), "invalid db option compression: %d valid range: [%d, %d]", pCreate->compression,
             TSDB_MIN_COMPRESSION_LEVEL, TSDB_MAX_COMPRESSION_LEVEL);
5117
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
H
hjxilinx 已提交
5118
  }
H
hjxilinx 已提交
5119

H
hjxilinx 已提交
5120 5121
  return TSDB_CODE_SUCCESS;
}
H
hjxilinx 已提交
5122 5123

// for debug purpose
5124
void tscPrintSelectClause(SSqlCmd* pCmd, int32_t subClauseIndex) {
5125 5126
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, subClauseIndex);

5127
  if (pCmd == NULL || pQueryInfo->exprsInfo.numOfExprs == 0) {
H
hjxilinx 已提交
5128 5129
    return;
  }
H
hjxilinx 已提交
5130 5131

  char*   str = calloc(1, 10240);
H
hjxilinx 已提交
5132
  int32_t offset = 0;
H
hjxilinx 已提交
5133

5134 5135 5136
  offset += sprintf(str, "%d [", pQueryInfo->exprsInfo.numOfExprs);
  for (int32_t i = 0; i < pQueryInfo->exprsInfo.numOfExprs; ++i) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);
H
hjxilinx 已提交
5137

H
hjxilinx 已提交
5138 5139
    int32_t size = sprintf(str + offset, "%s(%d)", aAggs[pExpr->functionId].aName, pExpr->colInfo.colId);
    offset += size;
H
hjxilinx 已提交
5140

5141
    if (i < pQueryInfo->exprsInfo.numOfExprs - 1) {
H
hjxilinx 已提交
5142 5143 5144
      str[offset++] = ',';
    }
  }
H
hjxilinx 已提交
5145

H
hjxilinx 已提交
5146 5147
  str[offset] = ']';
  printf("%s\n", str);
H
hjxilinx 已提交
5148

H
hjxilinx 已提交
5149 5150
  free(str);
}
5151

5152
int32_t doCheckForCreateTable(SSqlObj* pSql, int32_t subClauseIndex, SSqlInfo* pInfo) {
5153 5154 5155
  const char* msg1 = "invalid table name";
  const char* msg2 = "table name too long";

5156 5157 5158
  SSqlCmd*        pCmd = &pSql->cmd;
  SQueryInfo*     pQueryInfo = tscGetQueryInfoDetail(pCmd, subClauseIndex);
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170

  SCreateTableSQL* pCreateTable = pInfo->pCreateTableInfo;

  tFieldList* pFieldList = pCreateTable->colInfo.pColumns;
  tFieldList* pTagList = pCreateTable->colInfo.pTagColumns;

  assert(pFieldList != NULL);

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

  if (tscValidateName(pzTableName) != TSDB_CODE_SUCCESS) {
5171
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
5172 5173
  }

5174
  if (setMeterID(pMeterMetaInfo, pzTableName, pSql) != TSDB_CODE_SUCCESS) {
5175
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg2);
5176 5177 5178 5179 5180 5181 5182 5183 5184
  }

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

  int32_t col = 0;
  for (; col < pFieldList->nField; ++col) {
5185
    tscFieldInfoSetValFromField(&pQueryInfo->fieldsInfo, col, &pFieldList->p[col]);
5186 5187 5188 5189 5190 5191
  }

  pCmd->numOfCols = (int16_t)pFieldList->nField;

  if (pTagList != NULL) {  // create metric[optional]
    for (int32_t i = 0; i < pTagList->nField; ++i) {
5192
      tscFieldInfoSetValFromField(&pQueryInfo->fieldsInfo, col++, &pTagList->p[i]);
5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209
    }

    pCmd->count = pTagList->nField;
  }

  return TSDB_CODE_SUCCESS;
}

int32_t doCheckForCreateFromStable(SSqlObj* pSql, SSqlInfo* pInfo) {
  const char* msg1 = "invalid table name";
  const char* msg3 = "tag value too long";
  const char* msg4 = "illegal value or data overflow";
  const char* msg5 = "tags number not matched";

  SSqlCmd* pCmd = &pSql->cmd;

  SCreateTableSQL* pCreateTable = pInfo->pCreateTableInfo;
5210 5211 5212 5213 5214 5215 5216 5217 5218 5219
  SQueryInfo*      pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

  // two table: the first one is for current table, and the secondary is for the super table.
  tscAddEmptyMeterMetaInfo(pQueryInfo);
  assert(pQueryInfo->numOfTables == 2);

  const int32_t TABLE_INDEX = 0;
  const int32_t STABLE_INDEX = 1;

  SMeterMetaInfo* pStableMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, STABLE_INDEX);
5220 5221 5222 5223 5224

  // super table name, create table by using dst
  SSQLToken* pToken = &(pCreateTable->usingInfo.stableName);

  if (tscValidateName(pToken) != TSDB_CODE_SUCCESS) {
5225
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
5226 5227
  }

5228
  if (setMeterID(pStableMeterMetaInfo, pToken, pSql) != TSDB_CODE_SUCCESS) {
5229
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
5230 5231 5232
  }

  // get meter meta from mnode
5233
  strncpy(pCreateTable->usingInfo.tagdata.name, pStableMeterMetaInfo->name, TSDB_METER_ID_LEN);
5234 5235
  tVariantList* pList = pInfo->pCreateTableInfo->usingInfo.pTagVals;

5236
  int32_t code = tscGetMeterMeta(pSql, pStableMeterMetaInfo);
5237 5238 5239 5240
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

5241
  if (pStableMeterMetaInfo->pMeterMeta->numOfTags != pList->nExpr) {
5242
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg5);
5243 5244 5245
  }

  // too long tag values will return invalid sql, not be truncated automatically
5246
  SSchema* pTagSchema = tsGetTagSchema(pStableMeterMetaInfo->pMeterMeta);
5247 5248 5249 5250 5251

  char* tagVal = pCreateTable->usingInfo.tagdata.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) {
5252
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg4);
5253 5254 5255 5256 5257
    }

    // validate the length of binary
    if ((pTagSchema[i].type == TSDB_DATA_TYPE_BINARY || pTagSchema[i].type == TSDB_DATA_TYPE_NCHAR) &&
        pList->a[i].pVar.nLen > pTagSchema[i].bytes) {
5258
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg3);
5259 5260 5261 5262 5263 5264 5265
    }

    tagVal += pTagSchema[i].bytes;
  }

  // table name
  if (tscValidateName(&pInfo->pCreateTableInfo->name) != TSDB_CODE_SUCCESS) {
5266
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
5267 5268
  }

5269 5270
  SMeterMetaInfo* pTableMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, TABLE_INDEX);
  int32_t         ret = setMeterID(pTableMeterMetaInfo, &pInfo->pCreateTableInfo->name, pSql);
5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284
  if (ret != TSDB_CODE_SUCCESS) {
    return ret;
  }

  return TSDB_CODE_SUCCESS;
}

int32_t doCheckForStream(SSqlObj* pSql, SSqlInfo* pInfo) {
  const char* msg1 = "invalid table name";
  const char* msg2 = "table name too long";
  const char* msg3 = "fill only available for interval query";
  const char* msg4 = "fill option not supported in stream computing";
  const char* msg5 = "sql too long";  // todo ADD support

5285
  SSqlCmd*    pCmd = &pSql->cmd;
5286
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
5287 5288
  assert(pQueryInfo->numOfTables == 1);

5289
  SCreateTableSQL* pCreateTable = pInfo->pCreateTableInfo;
5290
  SMeterMetaInfo*  pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
5291 5292 5293 5294 5295 5296

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

  if (tscValidateName(pzTableName) != TSDB_CODE_SUCCESS) {
5297
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
5298 5299 5300 5301 5302 5303 5304
  }

  tVariantList* pSrcMeterName = pInfo->pCreateTableInfo->pSelect->from;
  tVariant*     pVar = &pSrcMeterName->a[0].pVar;

  SSQLToken srcToken = {.z = pVar->pz, .n = pVar->nLen, .type = TK_STRING};
  if (tscValidateName(&srcToken) != TSDB_CODE_SUCCESS) {
5305
    return invalidSqlErrMsg(pQueryInfo->msg, msg1);
5306 5307
  }

5308
  if (setMeterID(pMeterMetaInfo, &srcToken, pSql) != TSDB_CODE_SUCCESS) {
5309
    return invalidSqlErrMsg(pQueryInfo->msg, msg2);
5310 5311
  }

5312
  int32_t code = tscGetMeterMeta(pSql, pMeterMetaInfo);
5313 5314 5315 5316
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

5317 5318
  bool isSTable = UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo);
  if (parseSelectClause(&pSql->cmd, pQuerySql->pSelection, isSTable) != TSDB_CODE_SUCCESS) {
5319 5320 5321 5322 5323 5324 5325 5326 5327 5328
    return TSDB_CODE_INVALID_SQL;
  }

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

  // set interval value
5329
  if (parseIntervalClause(pQueryInfo, pQuerySql) != TSDB_CODE_SUCCESS) {
5330 5331
    return TSDB_CODE_INVALID_SQL;
  } else {
5332 5333
    if ((pQueryInfo->nAggTimeInterval > 0) &&
        (validateFunctionsInIntervalOrGroupbyQuery(pQueryInfo) != TSDB_CODE_SUCCESS)) {
5334 5335 5336 5337
      return TSDB_CODE_INVALID_SQL;
    }
  }

5338
  if (setSlidingClause(pQueryInfo, pQuerySql) != TSDB_CODE_SUCCESS) {
5339 5340 5341 5342
    return TSDB_CODE_INVALID_SQL;
  }

  // set the created table[stream] name
5343
  if (setMeterID(pMeterMetaInfo, pzTableName, pSql) != TSDB_CODE_SUCCESS) {
5344
    return invalidSqlErrMsg(pQueryInfo->msg, msg1);
5345 5346 5347
  }

  if (pQuerySql->selectToken.n > TSDB_MAX_SAVED_SQL_LEN) {
5348
    return invalidSqlErrMsg(pQueryInfo->msg, msg5);
5349 5350
  }

5351
  if (tsRewriteFieldNameIfNecessary(pQueryInfo) != TSDB_CODE_SUCCESS) {
5352 5353 5354
    return TSDB_CODE_INVALID_SQL;
  }

5355
  pCmd->numOfCols = pQueryInfo->fieldsInfo.numOfOutputCols;
5356

5357
  if (validateSqlFunctionInStreamSql(pQueryInfo) != TSDB_CODE_SUCCESS) {
5358 5359 5360 5361 5362 5363 5364 5365
    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) {
5366 5367
    if (pQueryInfo->nAggTimeInterval == 0) {
      return invalidSqlErrMsg(pQueryInfo->msg, msg3);
5368 5369 5370 5371 5372 5373
    }

    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))) {
5374
        return invalidSqlErrMsg(pQueryInfo->msg, msg4);
5375 5376 5377 5378 5379
      }
    }
  }

  // set the number of stream table columns
5380
  pCmd->numOfCols = pQueryInfo->fieldsInfo.numOfOutputCols;
5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398
  return TSDB_CODE_SUCCESS;
}

int32_t doCheckForQuery(SSqlObj* pSql, SQuerySQL* pQuerySql, int32_t index) {
  assert(pQuerySql != NULL && (pQuerySql->from == NULL || pQuerySql->from->nExpr > 0));

  const char* msg0 = "invalid table name";
  const char* msg1 = "table name too long";
  const char* msg2 = "point interpolation query needs timestamp";
  const char* msg3 = "sliding value too small";
  const char* msg4 = "sliding value no larger than the interval value";
  const char* msg5 = "fill only available for interval query";
  const char* msg6 = "start(end) time of query range required or time range too large";
  const char* msg7 = "illegal number of tables in from clause";
  const char* msg8 = "too many columns in selection clause";
  const char* msg9 = "TWA query requires both the start and end time";

  int32_t code = TSDB_CODE_SUCCESS;
5399

5400
  SSqlCmd* pCmd = &pSql->cmd;
5401

5402 5403
  SQueryInfo*     pQueryInfo = tscGetQueryInfoDetail(pCmd, index);
  SMeterMetaInfo* pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
5404

5405 5406
  // too many result columns not support order by in query
  if (pQuerySql->pSelection->nExpr > TSDB_MAX_COLUMNS) {
5407
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg8);
5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419
  }

  /*
   * handle the sql expression without from subclause
   * select current_database();
   * select server_version();
   * select client_version();
   * select server_state();
   */
  if (pQuerySql->from == NULL) {
    assert(pQuerySql->fillType == NULL && pQuerySql->pGroupby == NULL && pQuerySql->pWhere == NULL &&
           pQuerySql->pSortOrder == NULL);
5420
    return doLocalQueryProcess(pQuerySql, pCmd, 0);
5421 5422 5423
  }

  if (pQuerySql->from->nExpr > TSDB_MAX_JOIN_TABLE_NUM) {
5424
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg7);
5425 5426 5427 5428 5429 5430 5431
  }

  // set all query tables, which are maybe more than one.
  for (int32_t i = 0; i < pQuerySql->from->nExpr; ++i) {
    tVariant* pTableItem = &pQuerySql->from->a[i].pVar;

    if (pTableItem->nType != TSDB_DATA_TYPE_BINARY) {
5432
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg0);
5433 5434 5435 5436 5437 5438
    }

    pTableItem->nLen = strdequote(pTableItem->pz);

    SSQLToken tableName = {.z = pTableItem->pz, .n = pTableItem->nLen, .type = TK_STRING};
    if (tscValidateName(&tableName) != TSDB_CODE_SUCCESS) {
5439
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg0);
5440 5441
    }

5442
    if (pQueryInfo->numOfTables <= i) {  // more than one table
5443
      tscAddEmptyMeterMetaInfo(pQueryInfo);
5444 5445
    }

5446 5447
    SMeterMetaInfo* pMeterInfo1 = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, i);

5448
    SSQLToken t = {.type = TSDB_DATA_TYPE_BINARY, .n = pTableItem->nLen, .z = pTableItem->pz};
5449
    if (setMeterID(pMeterInfo1, &t, pSql) != TSDB_CODE_SUCCESS) {
5450
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg1);
5451 5452
    }

5453
    code = tscGetMeterMeta(pSql, pMeterInfo1);
5454 5455 5456 5457 5458
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

5459 5460
  assert(pQueryInfo->numOfTables == pQuerySql->from->nExpr);

5461
  // parse the group by clause in the first place
5462
  if (parseGroupbyClause(pQueryInfo, pQuerySql->pGroupby, pCmd) != TSDB_CODE_SUCCESS) {
5463 5464 5465
    return TSDB_CODE_INVALID_SQL;
  }

5466 5467
  bool isSTable = UTIL_METER_IS_SUPERTABLE(pMeterMetaInfo);
  if (parseSelectClause(pCmd, pQuerySql->pSelection, isSTable) != TSDB_CODE_SUCCESS) {
5468 5469 5470 5471
    return TSDB_CODE_INVALID_SQL;
  }

  // set interval value
5472
  if (parseIntervalClause(pQueryInfo, pQuerySql) != TSDB_CODE_SUCCESS) {
5473 5474
    return TSDB_CODE_INVALID_SQL;
  } else {
5475 5476
    if ((pQueryInfo->nAggTimeInterval > 0) &&
        (validateFunctionsInIntervalOrGroupbyQuery(pQueryInfo) != TSDB_CODE_SUCCESS)) {
5477 5478 5479 5480 5481 5482 5483
      return TSDB_CODE_INVALID_SQL;
    }
  }

  // set sliding value
  SSQLToken* pSliding = &pQuerySql->sliding;
  if (pSliding->n != 0) {
5484
    if (!tscEmbedded && pCmd->inStream == 0) {  // sliding only allowed in stream
5485
      const char* msg = "not support sliding in query";
5486
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg);
5487 5488
    }

5489
    getTimestampInUsFromStr(pSliding->z, pSliding->n, &pQueryInfo->nSlidingTime);
5490
    if (pMeterMetaInfo->pMeterMeta->precision == TSDB_TIME_PRECISION_MILLI) {
5491
      pQueryInfo->nSlidingTime /= 1000;
5492 5493
    }

5494 5495
    if (pQueryInfo->nSlidingTime < tsMinSlidingTime) {
      return invalidSqlErrMsg(pQueryInfo->msg, msg3);
5496 5497
    }

5498 5499
    if (pQueryInfo->nSlidingTime > pQueryInfo->nAggTimeInterval) {
      return invalidSqlErrMsg(pQueryInfo->msg, msg4);
5500 5501 5502 5503
    }
  }

  // set order by info
5504
  if (parseOrderbyClause(pQueryInfo, pQuerySql, tsGetSchema(pMeterMetaInfo->pMeterMeta),
5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517
                         pMeterMetaInfo->pMeterMeta->numOfColumns) != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_INVALID_SQL;
  }

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

    pQuerySql->pWhere = NULL;

    if (pMeterMetaInfo->pMeterMeta->precision == TSDB_TIME_PRECISION_MILLI) {
5518 5519
      pQueryInfo->stime = pQueryInfo->stime / 1000;
      pQueryInfo->etime = pQueryInfo->etime / 1000;
5520 5521
    }
  } else {  // set the time rang
5522 5523
    pQueryInfo->stime = 0;
    pQueryInfo->etime = INT64_MAX;
5524 5525 5526
  }

  // user does not specified the query time window, twa is not allowed in such case.
5527
  if ((pQueryInfo->stime == 0 || pQueryInfo->etime == INT64_MAX ||
5528
       (pQueryInfo->etime == INT64_MAX / 1000 && pMeterMetaInfo->pMeterMeta->precision == TSDB_TIME_PRECISION_MILLI)) &&
5529 5530
      tscIsTWAQuery(pQueryInfo)) {
    return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg9);
5531 5532 5533
  }

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

5539 5540
  if (!hasTimestampForPointInterpQuery(pQueryInfo)) {
    return invalidSqlErrMsg(pQueryInfo->msg, msg2);
5541 5542 5543
  }

  // in case of join query, time range is required.
5544 5545
  if (QUERY_IS_JOIN_QUERY(pQueryInfo->type)) {
    int64_t timeRange = labs(pQueryInfo->stime - pQueryInfo->etime);
5546

5547 5548
    if (timeRange == 0 && pQueryInfo->stime == 0) {
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg6);
5549 5550 5551 5552
    }
  }

  // handle the limit offset value, validate the limit
5553
  pQueryInfo->limit = pQuerySql->limit;
5554 5555

  // temporarily save the original limitation value
5556
  if ((code = parseLimitClause(pSql, 0, pQuerySql)) != TSDB_CODE_SUCCESS) {
5557 5558 5559
    return code;
  }

5560
  if ((code = doFunctionsCompatibleCheck(pCmd, pQueryInfo)) != TSDB_CODE_SUCCESS) {
5561 5562 5563
    return code;
  }

5564
  setColumnOffsetValueInResultset(pQueryInfo);
5565

5566 5567
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
    updateTagColumnIndex(pQueryInfo, i);
5568
  }
5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591
  
  /*
   * fill options are set at the end position, when all columns are set properly
   * the columns may be increased due to group by operation
   */
  if (pQuerySql->fillType != NULL) {
    if (pQueryInfo->nAggTimeInterval == 0 && (!tscIsPointInterpQuery(pQueryInfo))) {
      return invalidSqlErrMsg(tscGetErrorMsgPayload(pCmd), msg5);
    }
    
    if (pQueryInfo->nAggTimeInterval > 0) {
      int64_t timeRange = labs(pQueryInfo->stime - pQueryInfo->etime);
      // number of result is not greater than 10,000,000
      if ((timeRange == 0) || (timeRange / pQueryInfo->nAggTimeInterval) > MAX_RETRIEVE_ROWS_IN_INTERVAL_QUERY) {
        return invalidSqlErrMsg(pQueryInfo->msg, msg6);
      }
    }
    
    int32_t ret = parseFillClause(pQueryInfo, pQuerySql);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
  }
5592 5593 5594

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