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

S
slguan 已提交
16
#include "os.h"
H
hzcheng 已提交
17 18 19 20
#include "tcache.h"
#include "trpc.h"
#include "tscProfile.h"
#include "tscSecondaryMerge.h"
H
hjxilinx 已提交
21
#include "tscSubquery.h"
H
hzcheng 已提交
22 23 24 25 26 27 28 29 30 31
#include "tscUtil.h"
#include "tschemautil.h"
#include "tsclient.h"
#include "tsocket.h"
#include "ttime.h"
#include "ttimer.h"
#include "tutil.h"

#define TSC_MGMT_VNODE 999

S
slguan 已提交
32
SRpcIpSet  tscMgmtIpList;
S
slguan 已提交
33 34
SRpcIpSet  tscDnodeIpSet;

35 36
int (*tscBuildMsg[TSDB_SQL_MAX])(SSqlObj *pSql, SSqlInfo *pInfo) = {0};

H
hzcheng 已提交
37 38 39
int (*tscProcessMsgRsp[TSDB_SQL_MAX])(SSqlObj *pSql);
void tscProcessActivityTimer(void *handle, void *tmrId);
int tscKeepConn[TSDB_SQL_MAX] = {0};
40

41 42 43
TSKEY tscGetSubscriptionProgress(void* sub, int64_t uid);
void tscUpdateSubscriptionProgress(void* sub, int64_t uid, TSKEY ts);
void tscSaveSubscriptionProgress(void* sub);
H
hzcheng 已提交
44

S
slguan 已提交
45
static int32_t minMsgSize() { return tsRpcHeadSize + 100; }
H
hzcheng 已提交
46

47 48 49 50 51 52 53 54 55 56 57 58
static void tscSetDnodeIpList(SSqlObj* pSql, STableMeta* pTableMeta) {
  SRpcIpSet* pIpList = &pSql->ipList;
  
  pIpList->numOfIps = pTableMeta->numOfVpeers;
  pIpList->port     = tsDnodeShellPort;
  pIpList->inUse    = 0;
  
  for(int32_t i = 0; i < pTableMeta->numOfVpeers; ++i) {
    pIpList->ip[i] = pTableMeta->vpeerDesc[i].ip;
  }
}

S
slguan 已提交
59 60
void tscPrintMgmtIp() {
  if (tscMgmtIpList.numOfIps <= 0) {
S
slguan 已提交
61
    tscError("invalid mgmt IP list:%d", tscMgmtIpList.numOfIps);
S
slguan 已提交
62
  } else {
S
slguan 已提交
63
    for (int i = 0; i < tscMgmtIpList.numOfIps; ++i) {
S
slguan 已提交
64
      tscTrace("mgmt index:%d ip:%d", i, tscMgmtIpList.ip[i]);
S
slguan 已提交
65
    }
S
slguan 已提交
66 67 68
  }
}

S
slguan 已提交
69 70
void tscSetMgmtIpListFromCluster(SRpcIpSet *pIpList) {
  tscMgmtIpList.numOfIps = htons(pIpList->numOfIps);
S
slguan 已提交
71
  tscMgmtIpList.inUse = htons(pIpList->inUse);
S
slguan 已提交
72 73 74
  tscMgmtIpList.port = htons(pIpList->port);
  for (int32_t i = 0; i <tscMgmtIpList.numOfIps; ++i) {
    tscMgmtIpList.ip[i] = pIpList->ip[i];
S
slguan 已提交
75 76 77 78
  }
}

void tscSetMgmtIpListFromEdge() {
S
slguan 已提交
79 80
  if (tscMgmtIpList.numOfIps != 1) {
    tscMgmtIpList.numOfIps = 1;
S
slguan 已提交
81
    tscMgmtIpList.inUse = 0;
S
slguan 已提交
82
    tscMgmtIpList.port = tsMnodeShellPort;
S
slguan 已提交
83 84 85 86 87 88
    tscMgmtIpList.ip[0] = inet_addr(tsMasterIp);
    tscTrace("edge mgmt IP list:");
    tscPrintMgmtIp();
  }
}

S
slguan 已提交
89
void tscSetMgmtIpList(SRpcIpSet *pIpList) {
S
slguan 已提交
90 91 92 93 94 95 96 97
  /*
    * The iplist returned by the cluster edition is the current management nodes
    * and the iplist returned by the edge edition is empty
    */
  if (pIpList->numOfIps != 0) {
    tscSetMgmtIpListFromCluster(pIpList);
  } else {
    tscSetMgmtIpListFromEdge();
S
slguan 已提交
98 99 100
  }
}

H
hjxilinx 已提交
101 102 103 104 105 106 107
/*
 * For each management node, try twice at least in case of poor network situation.
 * If the client start to connect to a non-management node from the client, and the first retry may fail due to
 * the poor network quality. And then, the second retry get the response with redirection command.
 * The retry will not be executed since only *two* retry is allowed in case of single management node in the cluster.
 * Therefore, we need to multiply the retry times by factor of 2 to fix this problem.
 */
108
UNUSED_FUNC
H
hjxilinx 已提交
109 110 111 112 113
static int32_t tscGetMgmtConnMaxRetryTimes() {
  int32_t factor = 2;
  return tscMgmtIpList.numOfIps * factor;
}

H
hzcheng 已提交
114 115 116 117 118 119 120 121 122 123 124 125
void tscProcessHeartBeatRsp(void *param, TAOS_RES *tres, int code) {
  STscObj *pObj = (STscObj *)param;
  if (pObj == NULL) return;
  if (pObj != pObj->signature) {
    tscError("heart beat msg, pObj:%p, signature:%p invalid", pObj, pObj->signature);
    return;
  }

  SSqlObj *pSql = pObj->pHb;
  SSqlRes *pRes = &pSql->res;

  if (code == 0) {
126
    SCMHeartBeatRsp *pRsp = (SCMHeartBeatRsp *)pRes->pRsp;
S
slguan 已提交
127
    SRpcIpSet *      pIpList = &pRsp->ipList;
S
slguan 已提交
128
    tscSetMgmtIpList(pIpList);
S
slguan 已提交
129

H
hzcheng 已提交
130 131 132
    if (pRsp->killConnection) {
      tscKillConnection(pObj);
    } else {
S
slguan 已提交
133 134
      if (pRsp->queryId) tscKillQuery(pObj, htonl(pRsp->queryId));
      if (pRsp->streamId) tscKillStream(pObj, htonl(pRsp->streamId));
H
hzcheng 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    }
  } else {
    tscTrace("heart beat failed, code:%d", code);
  }

  taosTmrReset(tscProcessActivityTimer, tsShellActivityTimer * 500, pObj, tscTmr, &pObj->pTimer);
}

void tscProcessActivityTimer(void *handle, void *tmrId) {
  STscObj *pObj = (STscObj *)handle;

  if (pObj == NULL) return;
  if (pObj->signature != pObj) return;
  if (pObj->pTimer != tmrId) return;

  if (pObj->pHb == NULL) {
S
slguan 已提交
151 152 153
    SSqlObj *pSql = (SSqlObj *)calloc(1, sizeof(SSqlObj));
    if (NULL == pSql) return;

H
hzcheng 已提交
154
    pSql->fp = tscProcessHeartBeatRsp;
H
hjxilinx 已提交
155
    
156 157 158 159
    SQueryInfo *pQueryInfo = NULL;
    tscGetQueryInfoDetailSafely(&pSql->cmd, 0, &pQueryInfo);
    pQueryInfo->command = TSDB_SQL_HB;
    
S
slguan 已提交
160 161 162 163 164
    if (TSDB_CODE_SUCCESS != tscAllocPayload(&(pSql->cmd), TSDB_DEFAULT_PAYLOAD_SIZE)) {
      tfree(pSql);
      return;
    }

H
hzcheng 已提交
165 166 167 168
    pSql->param = pObj;
    pSql->pTscObj = pObj;
    pSql->signature = pSql;
    pObj->pHb = pSql;
169
    tscAddSubqueryInfo(&pObj->pHb->cmd);
170

S
slguan 已提交
171
    tscTrace("%p pHb is allocated, pObj:%p", pObj->pHb, pObj);
H
hzcheng 已提交
172 173 174
  }

  if (tscShouldFreeHeatBeat(pObj->pHb)) {
S
slguan 已提交
175
    tscTrace("%p free HB object and release connection", pObj);
H
hzcheng 已提交
176 177 178 179 180 181 182 183 184
    tscFreeSqlObj(pObj->pHb);
    tscCloseTscObj(pObj);
    return;
  }

  tscProcessSql(pObj->pHb);
}

int tscSendMsgToServer(SSqlObj *pSql) {
H
hjxilinx 已提交
185 186 187
  SSqlCmd* pCmd = &pSql->cmd;
  
  char *pMsg = rpcMallocCont(pCmd->payloadLen);
S
slguan 已提交
188
  if (NULL == pMsg) {
S
slguan 已提交
189 190
    tscError("%p msg:%s malloc fail", pSql, taosMsg[pSql->cmd.msgType]);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
H
hzcheng 已提交
191 192
  }

S
slguan 已提交
193
  if (pSql->cmd.command < TSDB_SQL_MGMT) {
194
    tscTrace("%p msg:%s is sent to server %d", pSql, taosMsg[pSql->cmd.msgType], pSql->ipList.port);
S
slguan 已提交
195
    memcpy(pMsg, pSql->cmd.payload + tsRpcHeadSize, pSql->cmd.payloadLen);
196 197 198 199 200 201

    SRpcMsg rpcMsg = {
      .msgType = pSql->cmd.msgType,
      .pCont   = pMsg,
      .contLen = pSql->cmd.payloadLen,
      .handle  = pSql,
H
hjxilinx 已提交
202
      .code    = 0
203
    };
H
hjxilinx 已提交
204
    rpcSendRequest(pVnodeConn, &pSql->ipList, &rpcMsg);
S
slguan 已提交
205
  } else {
H
hjxilinx 已提交
206 207 208 209
    pSql->ipList = tscMgmtIpList;
    pSql->ipList.port = tsMnodeShellPort;
    
    tscTrace("%p msg:%s is sent to server %d", pSql, taosMsg[pSql->cmd.msgType], pSql->ipList.port);
S
slguan 已提交
210
    memcpy(pMsg, pSql->cmd.payload, pSql->cmd.payloadLen);
211 212 213 214 215 216 217
    SRpcMsg rpcMsg = {
        .msgType = pSql->cmd.msgType,
        .pCont   = pMsg,
        .contLen = pSql->cmd.payloadLen,
        .handle  = pSql,
        .code   = 0
    };
H
hjxilinx 已提交
218
    rpcSendRequest(pTscMgmtConn, &pSql->ipList, &rpcMsg);
H
hzcheng 已提交
219 220
  }

S
slguan 已提交
221
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
222 223
}

224 225
void tscProcessMsgFromServer(SRpcMsg *rpcMsg) {
  SSqlObj *pSql = (SSqlObj *)rpcMsg->handle;
S
slguan 已提交
226
  if (pSql == NULL || pSql->signature != pSql) {
H
hzcheng 已提交
227
    tscError("%p sql is already released, signature:%p", pSql, pSql->signature);
S
slguan 已提交
228
    return;
H
hzcheng 已提交
229 230
  }

S
slguan 已提交
231 232 233
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;
  STscObj *pObj = pSql->pTscObj;
234
  tscTrace("%p msg:%p is received from server", pSql, rpcMsg->pCont);
H
hzcheng 已提交
235 236

  if (pSql->freed || pObj->signature != pObj) {
S
slguan 已提交
237 238
    tscTrace("%p sql is already released or DB connection is closed, freed:%d pObj:%p signature:%p", pSql, pSql->freed,
             pObj, pObj->signature);
H
hzcheng 已提交
239
    tscFreeSqlObj(pSql);
240
    rpcFreeCont(rpcMsg->pCont);
S
slguan 已提交
241
    return;
H
hzcheng 已提交
242 243
  }

244 245
  if (rpcMsg->pCont == NULL) {
    rpcMsg->code = TSDB_CODE_NETWORK_UNAVAIL;
S
slguan 已提交
246
  } else {
247
    STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
248 249
    if (rpcMsg->code == TSDB_CODE_NOT_ACTIVE_TABLE || rpcMsg->code == TSDB_CODE_INVALID_TABLE_ID ||
        rpcMsg->code == TSDB_CODE_INVALID_VNODE_ID || rpcMsg->code == TSDB_CODE_NOT_ACTIVE_VNODE ||
S
slguan 已提交
250
        rpcMsg->code == TSDB_CODE_NETWORK_UNAVAIL || rpcMsg->code == TSDB_CODE_NOT_ACTIVE_TABLE ||
251
        rpcMsg->code == TSDB_CODE_TABLE_ID_MISMATCH) {
S
slguan 已提交
252 253 254 255 256 257 258 259 260 261 262
      /*
       * not_active_table: 1. the virtual node may fail to create table, since the procedure of create table is asynchronized,
       *                   the virtual node may have not create table till now, so try again by using the new metermeta.
       *                   2. this requested table may have been removed by other client, so we need to renew the
       *                   metermeta here.
       *
       * not_active_vnode: current vnode is move to other node due to node balance procedure or virtual node have been
       *                   removed. So, renew metermeta and try again.
       * not_active_session: db has been move to other node, the vnode does not exist on this dnode anymore.
       */
      if (pCmd->command == TSDB_SQL_CONNECT) {
263 264
        rpcMsg->code = TSDB_CODE_NETWORK_UNAVAIL;
        rpcFreeCont(rpcMsg->pCont);
S
slguan 已提交
265 266
        return;
      } else if (pCmd->command == TSDB_SQL_HB) {
267 268
        rpcMsg->code = TSDB_CODE_NOT_READY;
        rpcFreeCont(rpcMsg->pCont);
S
slguan 已提交
269 270
        return;
      } else {
271
        tscWarn("%p it shall renew table meta, code:%s, retry:%d", pSql, tstrerror(rpcMsg->code), ++pSql->retry);
H
hzcheng 已提交
272

273
        pSql->maxRetry = TSDB_VNODES_SUPPORT * 2;  // todo move away
274
        pSql->res.code = rpcMsg->code;  // keep the previous error code
275 276 277 278 279 280 281 282
        if (pSql->retry > pSql->maxRetry) {
          tscError("%p max retry %d reached, give up", pSql, pSql->maxRetry);
        } else {
          rpcMsg->code = tscRenewMeterMeta(pSql, pTableMetaInfo->name);
          if (pTableMetaInfo->pTableMeta) {
            tscSendMsgToServer(pSql);
          }
  
283
          rpcFreeCont(rpcMsg->pCont);
S
slguan 已提交
284 285
          return;
        }
H
hzcheng 已提交
286 287
      }
    }
S
slguan 已提交
288
  }
H
hzcheng 已提交
289

290 291 292 293 294
  if (pRes->code == TSDB_CODE_SUCCESS) {
    tscTrace("%p reset retry counter to be 0 due to success rsp, old:%d", pSql, pSql->retry);
    pSql->retry = 0;
  }
  
H
hzcheng 已提交
295
  pRes->rspLen = 0;
296
  
H
hzcheng 已提交
297
  if (pRes->code != TSDB_CODE_QUERY_CANCELLED) {
298
    pRes->code = (rpcMsg->code != TSDB_CODE_SUCCESS) ? rpcMsg->code : TSDB_CODE_NETWORK_UNAVAIL;
H
hzcheng 已提交
299
  } else {
H
hjxilinx 已提交
300
    tscTrace("%p query is cancelled, code:%d", pSql, tstrerror(pRes->code));
H
hzcheng 已提交
301 302
  }

S
slguan 已提交
303
  if (pRes->code != TSDB_CODE_QUERY_CANCELLED) {
304
    assert(rpcMsg->msgType == pCmd->msgType + 1);
305
    pRes->code    = rpcMsg->code;
306
    pRes->rspType = rpcMsg->msgType;
307
    pRes->rspLen  = rpcMsg->contLen;
H
hzcheng 已提交
308

309 310 311 312 313 314
    if (pRes->rspLen > 0) {
      char *tmp = (char *)realloc(pRes->pRsp, pRes->rspLen);
      if (tmp == NULL) {
        pRes->code = TSDB_CODE_CLI_OUT_OF_MEMORY;
      } else {
        pRes->pRsp = tmp;
315
        memcpy(pRes->pRsp, rpcMsg->pCont, pRes->rspLen);
S
slguan 已提交
316
      }
317 318
    } else {
      pRes->pRsp = NULL;
S
slguan 已提交
319 320 321
    }

    // ignore the error information returned from mnode when set ignore flag in sql
S
slguan 已提交
322
    if (pRes->code == TSDB_CODE_DB_ALREADY_EXIST && pCmd->existsCheck && pRes->rspType == TSDB_MSG_TYPE_CM_CREATE_DB_RSP) {
H
hzcheng 已提交
323 324 325 326 327 328 329
      pRes->code = TSDB_CODE_SUCCESS;
    }

    /*
     * There is not response callback function for submit response.
     * The actual inserted number of points is the first number.
     */
330 331
    if (rpcMsg->msgType == TSDB_MSG_TYPE_SUBMIT_RSP) {
      SShellSubmitRspMsg *pMsg = (SShellSubmitRspMsg*)pRes->pRsp;
S
slguan 已提交
332 333 334 335 336 337 338
      pMsg->code = htonl(pMsg->code);
      pMsg->numOfRows = htonl(pMsg->numOfRows);
      pMsg->affectedRows = htonl(pMsg->affectedRows);
      pMsg->failedRows = htonl(pMsg->failedRows);
      pMsg->numOfFailedBlocks = htonl(pMsg->numOfFailedBlocks);

      pRes->numOfRows += pMsg->affectedRows;
339
      tscTrace("%p cmd:%d code:%s, inserted rows:%d, rsp len:%d", pSql, pCmd->command, tstrerror(pRes->code),
H
hjxilinx 已提交
340
          pMsg->affectedRows, pRes->rspLen);
S
slguan 已提交
341
    } else {
H
hjxilinx 已提交
342
      tscTrace("%p cmd:%d code:%s rsp len:%d", pSql, pCmd->command, tstrerror(pRes->code), pRes->rspLen);
H
hzcheng 已提交
343 344 345
    }
  }

346 347
  if (pRes->code == TSDB_CODE_SUCCESS && tscProcessMsgRsp[pCmd->command])
    rpcMsg->code = (*tscProcessMsgRsp[pCmd->command])(pSql);
H
hjxilinx 已提交
348
  
349
  if (rpcMsg->code != TSDB_CODE_ACTION_IN_PROGRESS) {
350
    void *taosres = tscKeepConn[pCmd->command] ? pSql : NULL;
H
[td-32]  
hjxilinx 已提交
351
    rpcMsg->code = pRes->code ? pRes->code : pRes->numOfRows;
352
    
353
    tscTrace("%p SQL result:%s res:%p", pSql, tstrerror(pRes->code), pSql);
H
hzcheng 已提交
354

355 356 357 358 359 360 361 362 363
    /*
     * Whether to free sqlObj or not should be decided before call the user defined function, since this SqlObj
     * may be freed in UDF, and reused by other threads before tscShouldFreeAsyncSqlObj called, in which case
     * tscShouldFreeAsyncSqlObj checks an object which is actually allocated by other threads.
     *
     * If this block of memory is re-allocated for an insert thread, in which tscKeepConn[command] equals to 0,
     * the tscShouldFreeAsyncSqlObj will success and tscFreeSqlObj free it immediately.
     */
    bool shouldFree = tscShouldFreeAsyncSqlObj(pSql);
H
hjxilinx 已提交
364
    (*pSql->fp)(pSql->param, taosres, rpcMsg->code);
H
hzcheng 已提交
365

366
    if (shouldFree) {
367
      tscTrace("%p sqlObj is automatically freed", pSql);
sangshuduo's avatar
sangshuduo 已提交
368
      tscFreeSqlObj(pSql);
H
hzcheng 已提交
369 370 371
    }
  }

372
  rpcFreeCont(rpcMsg->pCont);
H
hzcheng 已提交
373 374
}

S
slguan 已提交
375 376 377 378
int doProcessSql(SSqlObj *pSql) {
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;

H
hjxilinx 已提交
379 380 381 382 383 384 385
  if (pCmd->command == TSDB_SQL_SELECT ||
      pCmd->command == TSDB_SQL_FETCH ||
      pCmd->command == TSDB_SQL_RETRIEVE ||
      pCmd->command == TSDB_SQL_INSERT ||
      pCmd->command == TSDB_SQL_CONNECT ||
      pCmd->command == TSDB_SQL_HB ||
      pCmd->command == TSDB_SQL_META ||
H
hjxilinx 已提交
386
      pCmd->command == TSDB_SQL_STABLEVGROUP) {
387
    tscBuildMsg[pCmd->command](pSql, NULL);
S
slguan 已提交
388
  }
389 390 391

  int32_t code = tscSendMsgToServer(pSql);
  if (code != TSDB_CODE_SUCCESS) {
S
slguan 已提交
392
    pRes->code = code;
H
hjxilinx 已提交
393
    tscQueueAsyncRes(pSql);
S
slguan 已提交
394
  }
H
hjxilinx 已提交
395 396
  
  return TSDB_CODE_SUCCESS;
S
slguan 已提交
397 398 399
}

int tscProcessSql(SSqlObj *pSql) {
400 401 402
  char *   name = NULL;
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;
403 404
  
  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
405
  STableMetaInfo *pTableMetaInfo = NULL;
406
  uint16_t        type = 0;
407

408
  if (pQueryInfo != NULL) {
H
hjxilinx 已提交
409
    pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
410 411
    if (pTableMetaInfo != NULL) {
      name = pTableMetaInfo->name;
412
    }
413

414
    type = pQueryInfo->type;
415
  
416
    // for heartbeat, numOfTables == 0;
417
    assert((pQueryInfo->numOfTables == 0 && pQueryInfo->command == TSDB_SQL_HB) || pQueryInfo->numOfTables > 0);
S
slguan 已提交
418
  }
419

420
  tscTrace("%p SQL cmd:%d will be processed, name:%s, type:%d", pSql, pCmd->command, name, type);
H
hzcheng 已提交
421
  if (pSql->cmd.command < TSDB_SQL_MGMT) {
H
hjxilinx 已提交
422 423
    // the pTableMetaInfo cannot be NULL
    if (pTableMetaInfo == NULL) {
H
hjxilinx 已提交
424 425 426
      pSql->res.code = TSDB_CODE_OTHERS;
      return pSql->res.code;
    }
H
hzcheng 已提交
427
  } else if (pSql->cmd.command < TSDB_SQL_LOCAL) {
H
hjxilinx 已提交
428
    pSql->ipList = tscMgmtIpList;
H
hzcheng 已提交
429 430 431 432
  } else {  // local handler
    return (*tscProcessMsgRsp[pCmd->command])(pSql);
  }

S
slguan 已提交
433
  // todo handle async situation
434 435
  if (QUERY_IS_JOIN_QUERY(type)) {
    if ((pQueryInfo->type & TSDB_QUERY_TYPE_SUBQUERY) == 0) {
H
hjxilinx 已提交
436
      return tscHandleMasterJoinQuery(pSql);
S
slguan 已提交
437 438
    } else {
      // for first stage sub query, iterate all vnodes to get all timestamp
439
      if ((pQueryInfo->type & TSDB_QUERY_TYPE_JOIN_SEC_STAGE) != TSDB_QUERY_TYPE_JOIN_SEC_STAGE) {
S
slguan 已提交
440 441 442 443
        return doProcessSql(pSql);
      }
    }
  }
444
  
H
hjxilinx 已提交
445 446 447 448 449
  if (tscIsTwoStageSTableQuery(pQueryInfo, 0)) { // super table query
    tscHandleMasterSTableQuery(pSql);
    return pRes->code;
  } else if (pSql->fp == (void(*)())tscHandleMultivnodeInsert) {  // multi-vnodes insertion
    tscHandleMultivnodeInsert(pSql);
H
hzcheng 已提交
450 451
    return pSql->res.code;
  }
452
  
S
slguan 已提交
453 454
  return doProcessSql(pSql);
}
H
hzcheng 已提交
455 456

void tscKillMetricQuery(SSqlObj *pSql) {
457 458 459
  SSqlCmd* pCmd = &pSql->cmd;
  
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
460
  if (!tscIsTwoStageSTableQuery(pQueryInfo, 0)) {
H
hzcheng 已提交
461 462 463 464 465 466
    return;
  }

  for (int i = 0; i < pSql->numOfSubs; ++i) {
    SSqlObj *pSub = pSql->pSubs[i];

S
slguan 已提交
467
    if (pSub == NULL) {
H
hzcheng 已提交
468 469
      continue;
    }
S
slguan 已提交
470

H
hzcheng 已提交
471 472 473 474 475
    /*
     * here, we cannot set the command = TSDB_SQL_KILL_QUERY. Otherwise, it may cause
     * sub-queries not correctly released and master sql object of metric query reaches an abnormal state.
     */
    pSql->pSubs[i]->res.code = TSDB_CODE_QUERY_CANCELLED;
S
slguan 已提交
476
    //taosStopRpcConn(pSql->pSubs[i]->thandle);
H
hzcheng 已提交
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
  }

  /*
   * 1. if the subqueries are not launched or partially launched, we need to waiting the launched
   * query return to successfully free allocated resources.
   * 2. if no any subqueries are launched yet, which means the metric query only in parse sql stage,
   * set the res.code, and return.
   */
  const int64_t MAX_WAITING_TIME = 10000;  // 10 Sec.
  int64_t       stime = taosGetTimestampMs();

  while (pSql->cmd.command != TSDB_SQL_RETRIEVE_METRIC && pSql->cmd.command != TSDB_SQL_RETRIEVE_EMPTY_RESULT) {
    taosMsleep(100);
    if (taosGetTimestampMs() - stime > MAX_WAITING_TIME) {
      break;
    }
  }

  tscTrace("%p metric query is cancelled", pSql);
}

498
int tscBuildRetrieveMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
499 500 501 502 503
  char *pMsg, *pStart;

  pStart = pSql->cmd.payload + tsRpcHeadSize;
  pMsg = pStart;

504
  SRetrieveTableMsg *pRetrieveMsg = (SRetrieveTableMsg *)pMsg;
S
slguan 已提交
505
  pRetrieveMsg->qhandle = htobe64(pSql->res.qhandle);
S
slguan 已提交
506 507
  pMsg += sizeof(pSql->res.qhandle);

508
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
S
slguan 已提交
509
  pRetrieveMsg->free = htons(pQueryInfo->type);
510
  pMsg += sizeof(pQueryInfo->type);
H
hzcheng 已提交
511

512 513 514 515 516 517 518 519 520 521 522
  // todo valid the vgroupId at the client side
  if (UTIL_TABLE_IS_SUPERTABLE(pQueryInfo->pTableMetaInfo[0])) {
    SVgroupsInfo* pVgroupInfo = pQueryInfo->pTableMetaInfo[0]->vgroupList;
    assert(pVgroupInfo->dnodeVgroups->numOfVgroups == 1); // todo fix me
    
    pRetrieveMsg->header.vgId = htonl(pVgroupInfo->dnodeVgroups[0].vgId[0]);
  } else {
    STableMeta* pTableMeta = pQueryInfo->pTableMetaInfo[0]->pTableMeta;
    pRetrieveMsg->header.vgId = htonl(pTableMeta->vgId);
  }
  
523 524 525 526
  pMsg += sizeof(SRetrieveTableMsg);
  
  pRetrieveMsg->header.contLen = htonl(pSql->cmd.payloadLen);
  
S
slguan 已提交
527
  pSql->cmd.msgType = TSDB_MSG_TYPE_RETRIEVE;
528
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
529 530
}

531
int tscBuildSubmitMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hjxilinx 已提交
532
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
H
hjxilinx 已提交
533
  STableMeta* pTableMeta = tscGetMetaInfo(pQueryInfo, 0)->pTableMeta;
H
hjxilinx 已提交
534
  
535 536 537 538
  char* pMsg = pSql->cmd.payload + tsRpcHeadSize;
  
  // NOTE: shell message size should not include SMsgDesc
  int32_t size = pSql->cmd.payloadLen - sizeof(SMsgDesc);
H
hjxilinx 已提交
539
  
540
  SMsgDesc* pMsgDesc = (SMsgDesc*) pMsg;
541 542
  
  pMsgDesc->numOfVnodes = htonl(1);       //todo set the right number of vnodes
543
  pMsg += sizeof(SMsgDesc);
H
hjxilinx 已提交
544
  
545 546
  SSubmitMsg *pShellMsg = (SSubmitMsg *)pMsg;
  
H
hjxilinx 已提交
547
  pShellMsg->header.vgId = htonl(pTableMeta->vgId);
548
  pShellMsg->header.contLen = htonl(size);
549
  pShellMsg->length = pShellMsg->header.contLen;
H
hjxilinx 已提交
550
  
551
  pShellMsg->numOfBlocks = htonl(pSql->cmd.numOfTablesInSubmit);  // number of meters to be inserted
H
hzcheng 已提交
552

H
hjxilinx 已提交
553
  // pSql->cmd.payloadLen is set during copying data into payload
S
slguan 已提交
554
  pSql->cmd.msgType = TSDB_MSG_TYPE_SUBMIT;
555
  tscSetDnodeIpList(pSql, pTableMeta);
556
  
557
  tscTrace("%p build submit msg, vgId:%d numOfVnodes:%d", pSql, pTableMeta->vgId, htonl(pMsgDesc->numOfVnodes));
558
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
559 560 561 562 563 564
}

/*
 * for meter query, simply return the size <= 1k
 * for metric query, estimate size according to meter tags
 */
565
static int32_t tscEstimateQueryMsgSize(SSqlCmd *pCmd, int32_t clauseIndex) {
H
hzcheng 已提交
566
  const static int32_t MIN_QUERY_MSG_PKT_SIZE = TSDB_MAX_BYTES_PER_ROW * 5;
567
  SQueryInfo *         pQueryInfo = tscGetQueryInfoDetail(pCmd, clauseIndex);
H
hzcheng 已提交
568

569
  int32_t srcColListSize = pQueryInfo->colList.numOfCols * sizeof(SColumnInfo);
570

H
hjxilinx 已提交
571
  int32_t         exprSize = sizeof(SSqlFuncExprMsg) * pQueryInfo->exprsInfo.numOfExprs;
H
hjxilinx 已提交
572
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hzcheng 已提交
573 574

  // meter query without tags values
H
hjxilinx 已提交
575
  if (!UTIL_TABLE_IS_SUPERTABLE(pTableMetaInfo)) {
S
slguan 已提交
576
    return MIN_QUERY_MSG_PKT_SIZE + minMsgSize() + sizeof(SQueryTableMsg) + srcColListSize + exprSize;
H
hzcheng 已提交
577
  }
H
hjxilinx 已提交
578 579 580 581
  
  int32_t size = 4096;
  
#if 0
H
hjxilinx 已提交
582
  SSuperTableMeta *pMetricMeta = pTableMetaInfo->pMetricMeta;
583
  SVnodeSidList *pVnodeSidList = tscGetVnodeSidList(pMetricMeta, pTableMetaInfo->dnodeIndex);
H
hzcheng 已提交
584

585
  int32_t meterInfoSize = (pMetricMeta->tagLen + sizeof(STableIdInfo)) * pVnodeSidList->numOfSids;
H
hjxilinx 已提交
586
  int32_t outputColumnSize = pQueryInfo->exprsInfo.numOfExprs * sizeof(SSqlFuncExprMsg);
H
hzcheng 已提交
587

S
slguan 已提交
588
  int32_t size = meterInfoSize + outputColumnSize + srcColListSize + exprSize + MIN_QUERY_MSG_PKT_SIZE;
589 590
  if (pQueryInfo->tsBuf != NULL) {
    size += pQueryInfo->tsBuf->fileSize;
S
slguan 已提交
591
  }
H
hjxilinx 已提交
592 593
#endif
  
S
slguan 已提交
594
  return size;
H
hzcheng 已提交
595 596
}

H
hjxilinx 已提交
597
static char *doSerializeTableInfo(SSqlObj *pSql, int32_t vgId, char *pMsg) {
598
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, pSql->cmd.clauseIndex, 0);
599

H
hjxilinx 已提交
600
  STableMeta * pTableMeta = pTableMetaInfo->pTableMeta;
H
hjxilinx 已提交
601 602 603 604 605 606 607 608
  tscTrace("%p vgId:%d, query on table:%s, uid:%" PRIu64, pSql, vgId, pTableMetaInfo->name, pTableMeta->uid);
  
  STableIdInfo *pTableIdInfo = (STableIdInfo *)pMsg;
  pTableIdInfo->sid = htonl(pTableMeta->sid);
  pTableIdInfo->uid = htobe64(pTableMeta->uid);
  pTableIdInfo->key = htobe64(tscGetSubscriptionProgress(pSql->pSubscription, pTableMeta->uid));
  
  pMsg += sizeof(STableIdInfo);
609 610 611
  return pMsg;
}

612
int tscBuildQueryMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
613 614
  SSqlCmd *pCmd = &pSql->cmd;

615
  int32_t size = tscEstimateQueryMsgSize(pCmd, pCmd->clauseIndex);
H
hzcheng 已提交
616

S
slguan 已提交
617 618 619 620
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
    tscError("%p failed to malloc for query msg", pSql);
    return -1;
  }
621
  
622
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
623
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
624
  STableMeta * pTableMeta = pTableMetaInfo->pTableMeta;
625 626 627 628 629
  
  if (pQueryInfo->colList.numOfCols <= 0) {
    tscError("%p illegal value of numOfCols in query msg: %d", pSql, tscGetNumOfColumns(pTableMeta));
    return -1;
  }
630 631 632 633 634 635 636 637 638 639
  
  if (pQueryInfo->intervalTime < 0) {
    tscError("%p illegal value of aggregation time interval in query msg: %ld", pSql, pQueryInfo->intervalTime);
    return -1;
  }
  
  if (pQueryInfo->groupbyExpr.numOfGroupCols < 0) {
    tscError("%p illegal value of numOfGroupCols in query msg: %d", pSql, pQueryInfo->groupbyExpr.numOfGroupCols);
    return -1;
  }
640 641

  char *pStart = pCmd->payload + tsRpcHeadSize;
H
hzcheng 已提交
642

S
slguan 已提交
643
  SQueryTableMsg *pQueryMsg = (SQueryTableMsg *)pStart;
H
hzcheng 已提交
644 645

  int32_t msgLen = 0;
S
slguan 已提交
646
  int32_t numOfTables = 0;
H
hzcheng 已提交
647

H
hjxilinx 已提交
648
  if (UTIL_TABLE_IS_NOMRAL_TABLE(pTableMetaInfo)) {
S
slguan 已提交
649
    numOfTables = 1;
650
    tscSetDnodeIpList(pSql, pTableMeta);
651
    pQueryMsg->head.vgId = htonl(pTableMeta->vgId);
H
hjxilinx 已提交
652
    tscTrace("%p queried tables:%d, table id: %s", pSql, 1, pTableMetaInfo->name);
653
  } else {  // query super table
654 655 656
    
    if (pTableMetaInfo->dnodeIndex < 0) {
      tscError("%p error vnodeIdx:%d", pSql, pTableMetaInfo->dnodeIndex);
H
hzcheng 已提交
657 658
      return -1;
    }
H
hjxilinx 已提交
659
    
660
    pSql->ipList.numOfIps = 1; // todo fix me
661 662
    pSql->ipList.port     = tsDnodeShellPort;
    pSql->ipList.inUse    = 0;
663 664 665 666
  
    // todo extract method
    STableDnodeVgroupInfo* pVgroupInfo = &pTableMetaInfo->vgroupList->dnodeVgroups[pTableMetaInfo->dnodeIndex];
    pSql->ipList.ip[0] = pVgroupInfo->ipAddr.ip;
H
hjxilinx 已提交
667 668
    
#if 0
669
    SVnodeSidList *pVnodeSidList = tscGetVnodeSidList(pMetricMeta, pTableMetaInfo->dnodeIndex);
H
hzcheng 已提交
670 671
    uint32_t       vnodeId = pVnodeSidList->vpeerDesc[pVnodeSidList->index].vnode;

S
slguan 已提交
672 673 674
    numOfTables = pVnodeSidList->numOfSids;
    if (numOfTables <= 0) {
      tscError("%p vid:%d,error numOfTables in query message:%d", pSql, vnodeId, numOfTables);
H
hzcheng 已提交
675 676
      return -1;  // error
    }
H
hjxilinx 已提交
677 678
#endif
    
679 680 681 682
    tscTrace("%p query on super table, numOfVgroup:%d, dnodeIndex:%d", pSql, pVgroupInfo->numOfVgroups,
        pTableMetaInfo->dnodeIndex);
    
    pQueryMsg->head.vgId = htonl(pVgroupInfo->vgId[0]);
H
hjxilinx 已提交
683
    numOfTables = 1;
H
hzcheng 已提交
684 685
  }

686
  if (pQueryInfo->order.order == TSDB_ORDER_ASC) {
H
hjxilinx 已提交
687 688
    pQueryMsg->window.skey = htobe64(pQueryInfo->stime);
    pQueryMsg->window.ekey = htobe64(pQueryInfo->etime);
H
hzcheng 已提交
689
  } else {
H
hjxilinx 已提交
690 691
    pQueryMsg->window.skey = htobe64(pQueryInfo->etime);
    pQueryMsg->window.ekey = htobe64(pQueryInfo->stime);
H
hzcheng 已提交
692 693
  }

694
  pQueryMsg->numOfTables    = htonl(numOfTables);
695 696 697 698 699 700 701 702
  pQueryMsg->order          = htons(pQueryInfo->order.order);
  pQueryMsg->orderColId     = htons(pQueryInfo->order.orderColId);
  pQueryMsg->interpoType    = htons(pQueryInfo->interpoType);
  pQueryMsg->limit          = htobe64(pQueryInfo->limit.limit);
  pQueryMsg->offset         = htobe64(pQueryInfo->limit.offset);
  pQueryMsg->numOfCols      = htons(pQueryInfo->colList.numOfCols);
  pQueryMsg->intervalTime   = htobe64(pQueryInfo->intervalTime);
  pQueryMsg->slidingTime    = htobe64(pQueryInfo->slidingTime);
H
hjxilinx 已提交
703
  pQueryMsg->slidingTimeUnit = pQueryInfo->slidingTimeUnit;
704
  pQueryMsg->numOfGroupCols = htons(pQueryInfo->groupbyExpr.numOfGroupCols);
H
hzcheng 已提交
705

706 707
  pQueryMsg->queryType = htons(pQueryInfo->type);
  pQueryMsg->numOfOutputCols = htons(pQueryInfo->exprsInfo.numOfExprs);
H
hzcheng 已提交
708

H
hjxilinx 已提交
709 710 711
  int32_t numOfOutput = pQueryInfo->fieldsInfo.numOfOutputCols;
  if (numOfOutput < 0) {
    tscError("%p illegal value of number of output columns in query msg: %d", pSql, numOfOutput);
H
hzcheng 已提交
712 713 714 715
    return -1;
  }

  // set column list ids
H
hjxilinx 已提交
716
  char *pMsg = (char *)(pQueryMsg->colList) + pQueryInfo->colList.numOfCols * sizeof(SColumnInfo);
H
hjxilinx 已提交
717
  SSchema *pSchema = tscGetTableSchema(pTableMeta);
H
hzcheng 已提交
718

719 720
  for (int32_t i = 0; i < pQueryInfo->colList.numOfCols; ++i) {
    SColumnBase *pCol = tscColumnBaseInfoGet(&pQueryInfo->colList, i);
S
slguan 已提交
721
    SSchema *    pColSchema = &pSchema[pCol->colIndex.columnIndex];
H
hzcheng 已提交
722

H
hjxilinx 已提交
723 724 725 726 727 728 729 730
//    if (pCol->colIndex.columnIndex >= tscGetNumOfColumns(pTableMeta) || pColSchema->type < TSDB_DATA_TYPE_BOOL ||
//        pColSchema->type > TSDB_DATA_TYPE_NCHAR) {
//      tscError("%p vid:%d sid:%d id:%s, column index out of range, numOfColumns:%d, index:%d, column name:%s", pSql,
//               htons(pQueryMsg->vnode), pTableMeta->sid, pTableMetaInfo->name, tscGetNumOfColumns(pTableMeta), pCol->colIndex,
//               pColSchema->name);
//
//      return -1;  // 0 means build msg failed
//    }
H
hzcheng 已提交
731 732 733

    pQueryMsg->colList[i].colId = htons(pColSchema->colId);
    pQueryMsg->colList[i].bytes = htons(pColSchema->bytes);
734
    pQueryMsg->colList[i].type  = htons(pColSchema->type);
S
slguan 已提交
735
    pQueryMsg->colList[i].numOfFilters = htons(pCol->numOfFilters);
H
hzcheng 已提交
736

S
slguan 已提交
737 738 739
    // append the filter information after the basic column information
    for (int32_t f = 0; f < pCol->numOfFilters; ++f) {
      SColumnFilterInfo *pColFilter = &pCol->filterInfo[f];
H
hzcheng 已提交
740

S
slguan 已提交
741 742 743 744
      SColumnFilterInfo *pFilterMsg = (SColumnFilterInfo *)pMsg;
      pFilterMsg->filterOnBinary = htons(pColFilter->filterOnBinary);

      pMsg += sizeof(SColumnFilterInfo);
H
hzcheng 已提交
745

S
slguan 已提交
746 747 748 749 750 751 752 753 754 755 756
      if (pColFilter->filterOnBinary) {
        pFilterMsg->len = htobe64(pColFilter->len);
        memcpy(pMsg, (void *)pColFilter->pz, pColFilter->len + 1);
        pMsg += (pColFilter->len + 1);  // append the additional filter binary info
      } else {
        pFilterMsg->lowerBndi = htobe64(pColFilter->lowerBndi);
        pFilterMsg->upperBndi = htobe64(pColFilter->upperBndi);
      }

      pFilterMsg->lowerRelOptr = htons(pColFilter->lowerRelOptr);
      pFilterMsg->upperRelOptr = htons(pColFilter->upperRelOptr);
H
hzcheng 已提交
757

S
slguan 已提交
758 759 760 761 762
      if (pColFilter->lowerRelOptr == TSDB_RELATION_INVALID && pColFilter->upperRelOptr == TSDB_RELATION_INVALID) {
        tscError("invalid filter info");
        return -1;
      }
    }
H
hzcheng 已提交
763 764 765 766
  }

  bool hasArithmeticFunction = false;

S
slguan 已提交
767
  SSqlFuncExprMsg *pSqlFuncExpr = (SSqlFuncExprMsg *)pMsg;
H
hjxilinx 已提交
768
  for (int32_t i = 0; i < tscSqlExprNumOfExprs(pQueryInfo); ++i) {
769
    SSqlExpr *pExpr = tscSqlExprGet(pQueryInfo, i);
H
hzcheng 已提交
770

S
slguan 已提交
771
    if (pExpr->functionId == TSDB_FUNC_ARITHM) {
H
hzcheng 已提交
772 773 774
      hasArithmeticFunction = true;
    }

H
hjxilinx 已提交
775
    if (!tscValidateColumnId(pTableMetaInfo, pExpr->colInfo.colId)) {
776
      /* column id is not valid according to the cached metermeta, the table meta is expired */
H
hzcheng 已提交
777 778 779 780
      tscError("%p table schema is not matched with parsed sql", pSql);
      return -1;
    }

781 782 783
    pSqlFuncExpr->colInfo.colId    = htons(pExpr->colInfo.colId);
    pSqlFuncExpr->colInfo.colIndex = htons(pExpr->colInfo.colIndex);
    pSqlFuncExpr->colInfo.flag     = htons(pExpr->colInfo.flag);
H
hzcheng 已提交
784

785
    pSqlFuncExpr->functionId  = htons(pExpr->functionId);
H
hzcheng 已提交
786 787 788 789 790 791 792 793 794
    pSqlFuncExpr->numOfParams = htons(pExpr->numOfParams);
    pMsg += sizeof(SSqlFuncExprMsg);

    for (int32_t j = 0; j < pExpr->numOfParams; ++j) {
      pSqlFuncExpr->arg[j].argType = htons((uint16_t)pExpr->param[j].nType);
      pSqlFuncExpr->arg[j].argBytes = htons(pExpr->param[j].nLen);

      if (pExpr->param[j].nType == TSDB_DATA_TYPE_BINARY) {
        memcpy(pMsg, pExpr->param[j].pz, pExpr->param[j].nLen);
S
slguan 已提交
795 796 797

        // by plus one char to make the string null-terminated
        pMsg += pExpr->param[j].nLen + 1;
H
hzcheng 已提交
798 799 800 801 802 803 804 805 806 807
      } else {
        pSqlFuncExpr->arg[j].argValue.i64 = htobe64(pExpr->param[j].i64Key);
      }
    }

    pSqlFuncExpr = (SSqlFuncExprMsg *)pMsg;
  }

  int32_t len = 0;
  if (hasArithmeticFunction) {
808 809
    SColumnBase *pColBase = pQueryInfo->colList.pColList;
    for (int32_t i = 0; i < pQueryInfo->colList.numOfCols; ++i) {
S
slguan 已提交
810
      char *  name = pSchema[pColBase[i].colIndex.columnIndex].name;
H
hzcheng 已提交
811 812 813 814 815 816 817 818 819 820 821
      int32_t lenx = strlen(name);
      memcpy(pMsg, name, lenx);
      *(pMsg + lenx) = ',';

      len += (lenx + 1);  // one for comma
      pMsg += (lenx + 1);
    }
  }

  pQueryMsg->colNameLen = htonl(len);

822
  // serialize the table info (sid, uid, tags)
H
hjxilinx 已提交
823
  pMsg = doSerializeTableInfo(pSql, htons(pQueryMsg->head.vgId), pMsg);
H
hzcheng 已提交
824

825
  SSqlGroupbyExpr *pGroupbyExpr = &pQueryInfo->groupbyExpr;
S
slguan 已提交
826 827
  if (pGroupbyExpr->numOfGroupCols != 0) {
    pQueryMsg->orderByIdx = htons(pGroupbyExpr->orderIndex);
H
hzcheng 已提交
828 829
    pQueryMsg->orderType = htons(pGroupbyExpr->orderType);

S
slguan 已提交
830
    for (int32_t j = 0; j < pGroupbyExpr->numOfGroupCols; ++j) {
831
      SColIndex *pCol = &pGroupbyExpr->columnInfo[j];
S
slguan 已提交
832 833 834 835

      *((int16_t *)pMsg) = pCol->colId;
      pMsg += sizeof(pCol->colId);

836 837
      *((int16_t *)pMsg) += pCol->colIndex;
      pMsg += sizeof(pCol->colIndex);
S
slguan 已提交
838 839 840

      *((int16_t *)pMsg) += pCol->flag;
      pMsg += sizeof(pCol->flag);
H
hjxilinx 已提交
841 842 843
      
      memcpy(pMsg, pCol->name, tListLen(pCol->name));
      pMsg += tListLen(pCol->name);
S
slguan 已提交
844 845 846
    }
  }

847 848 849 850
  if (pQueryInfo->interpoType != TSDB_INTERPO_NONE) {
    for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
      *((int64_t *)pMsg) = htobe64(pQueryInfo->defaultVal[i]);
      pMsg += sizeof(pQueryInfo->defaultVal[0]);
S
slguan 已提交
851 852 853 854 855 856 857 858
    }
  }

  // compressed ts block
  pQueryMsg->tsOffset = htonl(pMsg - pStart);
  int32_t tsLen = 0;
  int32_t numOfBlocks = 0;

859
  if (pQueryInfo->tsBuf != NULL) {
860
    STSVnodeBlockInfo *pBlockInfo = tsBufGetVnodeBlockInfo(pQueryInfo->tsBuf, pTableMetaInfo->dnodeIndex);
861
    assert(QUERY_IS_JOIN_QUERY(pQueryInfo->type) && pBlockInfo != NULL);  // this query should not be sent
S
slguan 已提交
862 863

    // todo refactor
864 865
    fseek(pQueryInfo->tsBuf->f, pBlockInfo->offset, SEEK_SET);
    fread(pMsg, pBlockInfo->compLen, 1, pQueryInfo->tsBuf->f);
S
slguan 已提交
866 867 868 869

    pMsg += pBlockInfo->compLen;
    tsLen = pBlockInfo->compLen;
    numOfBlocks = pBlockInfo->numOfBlocks;
H
hzcheng 已提交
870 871
  }

S
slguan 已提交
872 873
  pQueryMsg->tsLen = htonl(tsLen);
  pQueryMsg->tsNumOfBlocks = htonl(numOfBlocks);
874 875
  if (pQueryInfo->tsBuf != NULL) {
    pQueryMsg->tsOrder = htonl(pQueryInfo->tsBuf->tsOrder);
H
hzcheng 已提交
876 877
  }

H
hjxilinx 已提交
878
  // serialize tag column query condition
879
  if (pQueryInfo->tagCond.pCond != NULL && taosArrayGetSize(pQueryInfo->tagCond.pCond) > 0) {
880 881
    STagCond* pTagCond = &pQueryInfo->tagCond;
    
882
    SCond *pCond = tsGetSTableQueryCond(pTagCond, pTableMeta->uid);
883
    if (pCond != NULL && pCond->cond != NULL) {
884 885
      pQueryMsg->tagCondLen = htons(pCond->len);
      memcpy(pMsg, pCond->cond, pCond->len);
886
      
887
      pMsg += pCond->len;
888 889 890
    }
  }
  
H
hjxilinx 已提交
891
  // tbname in/like query expression should be sent to mgmt node
H
hzcheng 已提交
892 893 894 895
  msgLen = pMsg - pStart;

  tscTrace("%p msg built success,len:%d bytes", pSql, msgLen);
  pCmd->payloadLen = msgLen;
S
slguan 已提交
896
  pSql->cmd.msgType = TSDB_MSG_TYPE_QUERY;
H
hjxilinx 已提交
897
  
898
  pQueryMsg->head.contLen = htonl(msgLen);
H
hzcheng 已提交
899
  assert(msgLen + minMsgSize() <= size);
900 901

  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
902 903
}

904 905
int32_t tscBuildCreateDbMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
906
  pCmd->payloadLen = sizeof(SCMCreateDbMsg);
S
slguan 已提交
907
  pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_DB;
H
hzcheng 已提交
908

909
  SCMCreateDbMsg *pCreateDbMsg = (SCMCreateDbMsg*)pCmd->payload;
910

911
  assert(pCmd->numOfClause == 1);
912
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
913
  strncpy(pCreateDbMsg->db, pTableMetaInfo->name, tListLen(pCreateDbMsg->db));
H
hzcheng 已提交
914

915
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
916 917
}

918 919
int32_t tscBuildCreateDnodeMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
920
  pCmd->payloadLen = sizeof(SCMCreateDnodeMsg);
S
slguan 已提交
921 922 923 924
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
H
hzcheng 已提交
925

926
  SCMCreateDnodeMsg *pCreate = (SCMCreateDnodeMsg *)pCmd->payload;
927
  strncpy(pCreate->ip, pInfo->pDCLInfo->a[0].z, pInfo->pDCLInfo->a[0].n);
S
slguan 已提交
928
  pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_DNODE;
H
hzcheng 已提交
929

930
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
931 932
}

933 934
int32_t tscBuildAcctMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
935
  pCmd->payloadLen = sizeof(SCMCreateAcctMsg);
S
slguan 已提交
936 937 938 939
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
H
hzcheng 已提交
940

941
  SCMCreateAcctMsg *pAlterMsg = (SCMCreateAcctMsg *)pCmd->payload;
H
hzcheng 已提交
942

943 944
  SSQLToken *pName = &pInfo->pDCLInfo->user.user;
  SSQLToken *pPwd = &pInfo->pDCLInfo->user.passwd;
H
hzcheng 已提交
945

946 947
  strncpy(pAlterMsg->user, pName->z, pName->n);
  strncpy(pAlterMsg->pass, pPwd->z, pPwd->n);
S
slguan 已提交
948

949
  SCreateAcctSQL *pAcctOpt = &pInfo->pDCLInfo->acctOpt;
H
hzcheng 已提交
950

951 952 953 954 955 956 957 958
  pAlterMsg->cfg.maxUsers = htonl(pAcctOpt->maxUsers);
  pAlterMsg->cfg.maxDbs = htonl(pAcctOpt->maxDbs);
  pAlterMsg->cfg.maxTimeSeries = htonl(pAcctOpt->maxTimeSeries);
  pAlterMsg->cfg.maxStreams = htonl(pAcctOpt->maxStreams);
  pAlterMsg->cfg.maxPointsPerSecond = htonl(pAcctOpt->maxPointsPerSecond);
  pAlterMsg->cfg.maxStorage = htobe64(pAcctOpt->maxStorage);
  pAlterMsg->cfg.maxQueryTime = htobe64(pAcctOpt->maxQueryTime);
  pAlterMsg->cfg.maxConnections = htonl(pAcctOpt->maxConnections);
H
hzcheng 已提交
959

960 961 962 963 964 965 966 967 968 969 970 971 972
  if (pAcctOpt->stat.n == 0) {
    pAlterMsg->cfg.accessState = -1;
  } else {
    if (pAcctOpt->stat.z[0] == 'r' && pAcctOpt->stat.n == 1) {
      pAlterMsg->cfg.accessState = TSDB_VN_READ_ACCCESS;
    } else if (pAcctOpt->stat.z[0] == 'w' && pAcctOpt->stat.n == 1) {
      pAlterMsg->cfg.accessState = TSDB_VN_WRITE_ACCCESS;
    } else if (strncmp(pAcctOpt->stat.z, "all", 3) == 0 && pAcctOpt->stat.n == 3) {
      pAlterMsg->cfg.accessState = TSDB_VN_ALL_ACCCESS;
    } else if (strncmp(pAcctOpt->stat.z, "no", 2) == 0 && pAcctOpt->stat.n == 2) {
      pAlterMsg->cfg.accessState = 0;
    }
  }
H
hzcheng 已提交
973

S
slguan 已提交
974
  pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_ACCT;
975
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
976 977
}

978 979
int32_t tscBuildUserMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
980
  pCmd->payloadLen = sizeof(SCMCreateUserMsg);
S
slguan 已提交
981

S
slguan 已提交
982 983 984 985 986
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }

987
  SCMCreateUserMsg *pAlterMsg = (SCMCreateUserMsg*)pCmd->payload;
H
hzcheng 已提交
988

989 990 991
  SUserInfo *pUser = &pInfo->pDCLInfo->user;
  strncpy(pAlterMsg->user, pUser->user.z, pUser->user.n);
  pAlterMsg->flag = pUser->type;
H
hzcheng 已提交
992

993 994 995 996
  if (pUser->type == TSDB_ALTER_USER_PRIVILEGES) {
    pAlterMsg->privilege = (char)pCmd->count;
  } else if (pUser->type == TSDB_ALTER_USER_PASSWD) {
    strncpy(pAlterMsg->pass, pUser->passwd.z, pUser->passwd.n);
H
hjxilinx 已提交
997 998
  } else { // create user password info
    strncpy(pAlterMsg->pass, pUser->passwd.z, pUser->passwd.n);
999
  }
H
hzcheng 已提交
1000

1001
  if (pUser->type == TSDB_ALTER_USER_PASSWD || pUser->type == TSDB_ALTER_USER_PRIVILEGES) {
S
slguan 已提交
1002
    pCmd->msgType = TSDB_MSG_TYPE_CM_ALTER_USER;
1003
  } else {
S
slguan 已提交
1004
    pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_USER;
1005
  }
H
hzcheng 已提交
1006

1007
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1008 1009
}

1010 1011
int32_t tscBuildCfgDnodeMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
S
slguan 已提交
1012
  pCmd->payloadLen = sizeof(SCMCfgDnodeMsg);
H
hzcheng 已提交
1013

S
slguan 已提交
1014 1015 1016 1017
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
H
hzcheng 已提交
1018

S
slguan 已提交
1019
  pCmd->msgType = TSDB_MSG_TYPE_MD_CONFIG_DNODE;
1020 1021
  return TSDB_CODE_SUCCESS;
}
S
slguan 已提交
1022

1023 1024
int32_t tscBuildDropDbMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
1025
  pCmd->payloadLen = sizeof(SCMDropDbMsg);
H
hzcheng 已提交
1026

S
slguan 已提交
1027 1028 1029 1030 1031
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }

1032
  SCMDropDbMsg *pDropDbMsg = (SCMDropDbMsg*)pCmd->payload;
H
hzcheng 已提交
1033

1034
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1035
  strncpy(pDropDbMsg->db, pTableMetaInfo->name, tListLen(pDropDbMsg->db));
1036
  pDropDbMsg->ignoreNotExists = pInfo->pDCLInfo->existsCheck ? 1 : 0;
H
hzcheng 已提交
1037

S
slguan 已提交
1038
  pCmd->msgType = TSDB_MSG_TYPE_CM_DROP_DB;
1039
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1040 1041
}

1042 1043
int32_t tscBuildDropTableMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
1044
  pCmd->payloadLen = sizeof(SCMDropTableMsg);
H
hzcheng 已提交
1045

S
slguan 已提交
1046 1047 1048 1049
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
H
hzcheng 已提交
1050

1051
  SCMDropTableMsg *pDropTableMsg = (SCMDropTableMsg*)pCmd->payload;
1052
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1053
  strcpy(pDropTableMsg->tableId, pTableMetaInfo->name);
S
slguan 已提交
1054
  pDropTableMsg->igNotExists = pInfo->pDCLInfo->existsCheck ? 1 : 0;
H
hzcheng 已提交
1055

S
slguan 已提交
1056
  pCmd->msgType = TSDB_MSG_TYPE_CM_DROP_TABLE;
1057
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1058 1059
}

1060
int32_t tscBuildDropDnodeMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
S
slguan 已提交
1061
  SSqlCmd *pCmd = &pSql->cmd;
1062
  pCmd->payloadLen = sizeof(SCMDropDnodeMsg);
S
slguan 已提交
1063 1064 1065 1066
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
H
hzcheng 已提交
1067

1068
  SCMDropDnodeMsg *pDrop = (SCMDropDnodeMsg *)pCmd->payload;
1069
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1070
  strcpy(pDrop->ip, pTableMetaInfo->name);
S
slguan 已提交
1071
  pCmd->msgType = TSDB_MSG_TYPE_CM_DROP_DNODE;
H
hzcheng 已提交
1072

1073
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1074 1075
}

S
[TD-16]  
slguan 已提交
1076
int32_t tscBuildDropUserMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
1077
  SSqlCmd *pCmd = &pSql->cmd;
1078
  pCmd->payloadLen = sizeof(SCMDropUserMsg);
S
slguan 已提交
1079
  pCmd->msgType = TSDB_MSG_TYPE_CM_DROP_USER;
H
hzcheng 已提交
1080

S
slguan 已提交
1081 1082 1083 1084
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
H
hzcheng 已提交
1085

1086
  SCMDropUserMsg *pDropMsg = (SCMDropUserMsg*)pCmd->payload;
1087
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1088
  strcpy(pDropMsg->user, pTableMetaInfo->name);
H
hzcheng 已提交
1089

1090
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1091 1092
}

S
[TD-16]  
slguan 已提交
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
int32_t tscBuildDropAcctMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
  pCmd->payloadLen = sizeof(SCMDropUserMsg);
  pCmd->msgType = TSDB_MSG_TYPE_CM_DROP_ACCT;

  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }

  SCMDropUserMsg *pDropMsg = (SCMDropUserMsg*)pCmd->payload;
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
  strcpy(pDropMsg->user, pTableMetaInfo->name);

  return TSDB_CODE_SUCCESS;
}

1110 1111
int32_t tscBuildUseDbMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
1112
  pCmd->payloadLen = sizeof(SCMUseDbMsg);
H
hzcheng 已提交
1113

S
slguan 已提交
1114 1115 1116 1117
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
1118

1119
  SCMUseDbMsg *pUseDbMsg = (SCMUseDbMsg*)pCmd->payload;
1120
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1121
  strcpy(pUseDbMsg->db, pTableMetaInfo->name);
S
slguan 已提交
1122
  pCmd->msgType = TSDB_MSG_TYPE_CM_USE_DB;
H
hzcheng 已提交
1123

1124
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1125 1126
}

1127
int32_t tscBuildShowMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1128
  STscObj *pObj = pSql->pTscObj;
S
slguan 已提交
1129
  SSqlCmd *pCmd = &pSql->cmd;
S
slguan 已提交
1130
  pCmd->msgType = TSDB_MSG_TYPE_CM_SHOW;
1131
  pCmd->payloadLen = sizeof(SCMShowMsg) + 100;
H
hzcheng 已提交
1132

S
slguan 已提交
1133 1134 1135
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
S
slguan 已提交
1136
  }
H
hzcheng 已提交
1137

1138
  SCMShowMsg *pShowMsg = (SCMShowMsg*)pCmd->payload;
S
slguan 已提交
1139

1140
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1141
  size_t nameLen = strlen(pTableMetaInfo->name);
S
slguan 已提交
1142
  if (nameLen > 0) {
H
hjxilinx 已提交
1143
    strcpy(pShowMsg->db, pTableMetaInfo->name);  // prefix is set here
H
hzcheng 已提交
1144
  } else {
S
slguan 已提交
1145
    strcpy(pShowMsg->db, pObj->db);
H
hzcheng 已提交
1146 1147
  }

1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
  SShowInfo *pShowInfo = &pInfo->pDCLInfo->showOpt;
  pShowMsg->type = pShowInfo->showType;

  if (pShowInfo->showType != TSDB_MGMT_TABLE_VNODES) {
    SSQLToken *pPattern = &pShowInfo->pattern;
    if (pPattern->type > 0) {  // only show tables support wildcard query
      strncpy(pShowMsg->payload, pPattern->z, pPattern->n);
      pShowMsg->payloadLen = htons(pPattern->n);
    }
  } else {
    SSQLToken *pIpAddr = &pShowInfo->prefix;
    assert(pIpAddr->n > 0 && pIpAddr->type > 0);
H
hzcheng 已提交
1160

1161 1162 1163 1164
    strncpy(pShowMsg->payload, pIpAddr->z, pIpAddr->n);
    pShowMsg->payloadLen = htons(pIpAddr->n);
  }

1165
  pCmd->payloadLen = sizeof(SCMShowMsg) + pShowMsg->payloadLen;
1166
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1167 1168
}

1169
int32_t tscBuildKillMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1170
  SSqlCmd *pCmd = &pSql->cmd;
1171
  pCmd->payloadLen = sizeof(SCMKillQueryMsg);
H
hzcheng 已提交
1172

S
slguan 已提交
1173 1174 1175 1176
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
H
hzcheng 已提交
1177

1178
  SCMKillQueryMsg *pKill = (SCMKillQueryMsg*)pCmd->payload;
1179 1180 1181
  strncpy(pKill->queryId, pInfo->pDCLInfo->ip.z, pInfo->pDCLInfo->ip.n);
  switch (pCmd->command) {
    case TSDB_SQL_KILL_QUERY:
S
slguan 已提交
1182
      pCmd->msgType = TSDB_MSG_TYPE_CM_KILL_QUERY;
1183 1184
      break;
    case TSDB_SQL_KILL_CONNECTION:
S
slguan 已提交
1185
      pCmd->msgType = TSDB_MSG_TYPE_CM_KILL_CONN;
1186 1187
      break;
    case TSDB_SQL_KILL_STREAM:
S
slguan 已提交
1188
      pCmd->msgType = TSDB_MSG_TYPE_CM_KILL_STREAM;
1189 1190 1191
      break;
  }
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1192 1193
}

1194
int tscEstimateCreateTableMsgLength(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1195 1196
  SSqlCmd *pCmd = &(pSql->cmd);

1197
  int32_t size = minMsgSize() + sizeof(SMgmtHead) + sizeof(SCMCreateTableMsg);
H
hzcheng 已提交
1198

1199
  SCreateTableSQL *pCreateTableInfo = pInfo->pCreateTableInfo;
1200
  if (pCreateTableInfo->type == TSQL_CREATE_TABLE_FROM_STABLE) {
H
hzcheng 已提交
1201 1202
    size += sizeof(STagData);
  } else {
S
slguan 已提交
1203
    size += sizeof(SSchema) * (pCmd->numOfCols + pCmd->count);
H
hzcheng 已提交
1204
  }
1205

1206 1207 1208
  if (pCreateTableInfo->pSelect != NULL) {
    size += (pCreateTableInfo->pSelect->selectToken.n + 1);
  }
H
hzcheng 已提交
1209 1210 1211 1212

  return size + TSDB_EXTRA_PAYLOAD_SIZE;
}

1213
int tscBuildCreateTableMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1214
  int              msgLen = 0;
S
slguan 已提交
1215
  SSchema *        pSchema;
H
hzcheng 已提交
1216
  int              size = 0;
1217 1218 1219
  SSqlCmd *pCmd = &pSql->cmd;

  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
hjxilinx 已提交
1220
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hzcheng 已提交
1221 1222

  // Reallocate the payload size
1223
  size = tscEstimateCreateTableMsgLength(pSql, pInfo);
S
slguan 已提交
1224 1225
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
    tscError("%p failed to malloc for create table msg", pSql);
1226
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
S
slguan 已提交
1227
  }
H
hzcheng 已提交
1228 1229


1230
  SCMCreateTableMsg *pCreateTableMsg = (SCMCreateTableMsg *)pCmd->payload;
H
hjxilinx 已提交
1231
  strcpy(pCreateTableMsg->tableId, pTableMetaInfo->name);
1232 1233

  // use dbinfo from table id without modifying current db info
H
hjxilinx 已提交
1234
  tscGetDBInfoFromMeterId(pTableMetaInfo->name, pCreateTableMsg->db);
H
hzcheng 已提交
1235

1236 1237 1238
  SCreateTableSQL *pCreateTable = pInfo->pCreateTableInfo;

  pCreateTableMsg->igExists = pCreateTable->existCheck ? 1 : 0;
H
hzcheng 已提交
1239 1240 1241 1242
  pCreateTableMsg->numOfColumns = htons(pCmd->numOfCols);
  pCreateTableMsg->numOfTags = htons(pCmd->count);

  pCreateTableMsg->sqlLen = 0;
S
slguan 已提交
1243
  char *pMsg = (char *)pCreateTableMsg->schema;
H
hzcheng 已提交
1244

1245 1246 1247
  int8_t type = pInfo->pCreateTableInfo->type;
  if (type == TSQL_CREATE_TABLE_FROM_STABLE) {  // create by using super table, tags value
    memcpy(pMsg, &pInfo->pCreateTableInfo->usingInfo.tagdata, sizeof(STagData));
H
hzcheng 已提交
1248
    pMsg += sizeof(STagData);
1249
  } else {  // create (super) table
1250
    pSchema = (SSchema *)pCreateTableMsg->schema;
1251

H
hzcheng 已提交
1252
    for (int i = 0; i < pCmd->numOfCols + pCmd->count; ++i) {
1253
      TAOS_FIELD *pField = tscFieldInfoGetField(pQueryInfo, i);
H
hzcheng 已提交
1254 1255 1256 1257

      pSchema->type = pField->type;
      strcpy(pSchema->name, pField->name);
      pSchema->bytes = htons(pField->bytes);
1258

H
hzcheng 已提交
1259 1260 1261 1262
      pSchema++;
    }

    pMsg = (char *)pSchema;
1263 1264
    if (type == TSQL_CREATE_STREAM) {  // check if it is a stream sql
      SQuerySQL *pQuerySql = pInfo->pCreateTableInfo->pSelect;
H
hzcheng 已提交
1265

1266 1267 1268
      strncpy(pMsg, pQuerySql->selectToken.z, pQuerySql->selectToken.n + 1);
      pCreateTableMsg->sqlLen = htons(pQuerySql->selectToken.n + 1);
      pMsg += pQuerySql->selectToken.n + 1;
H
hzcheng 已提交
1269 1270 1271
    }
  }

1272
  tscClearFieldInfo(&pQueryInfo->fieldsInfo);
H
hzcheng 已提交
1273

S
slguan 已提交
1274
  msgLen = pMsg - (char*)pCreateTableMsg;
S
slguan 已提交
1275
  pCreateTableMsg->contLen = htonl(msgLen);
H
hzcheng 已提交
1276
  pCmd->payloadLen = msgLen;
S
slguan 已提交
1277
  pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_TABLE;
H
hzcheng 已提交
1278 1279

  assert(msgLen + minMsgSize() <= size);
1280
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1281 1282 1283
}

int tscEstimateAlterTableMsgLength(SSqlCmd *pCmd) {
1284
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
1285
  return minMsgSize() + sizeof(SMgmtHead) + sizeof(SCMAlterTableMsg) + sizeof(SSchema) * tscNumOfFields(pQueryInfo) +
H
hzcheng 已提交
1286 1287 1288
         TSDB_EXTRA_PAYLOAD_SIZE;
}

1289
int tscBuildAlterTableMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
1290
  SCMAlterTableMsg *pAlterTableMsg;
1291
  char *          pMsg;
H
hzcheng 已提交
1292 1293 1294
  int             msgLen = 0;
  int             size = 0;

1295 1296 1297
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

H
hjxilinx 已提交
1298
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hzcheng 已提交
1299 1300

  size = tscEstimateAlterTableMsgLength(pCmd);
S
slguan 已提交
1301 1302 1303 1304
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
    tscError("%p failed to malloc for alter table msg", pSql);
    return -1;
  }
H
hzcheng 已提交
1305

1306
  pAlterTableMsg = (SCMAlterTableMsg *)pCmd->payload;
H
hzcheng 已提交
1307

H
hjxilinx 已提交
1308
  tscGetDBInfoFromMeterId(pTableMetaInfo->name, pAlterTableMsg->db);
H
hzcheng 已提交
1309

1310 1311
  SAlterTableSQL *pAlterInfo = pInfo->pAlterInfo;

H
hjxilinx 已提交
1312
  strcpy(pAlterTableMsg->tableId, pTableMetaInfo->name);
1313
  pAlterTableMsg->type = htons(pAlterInfo->type);
1314

1315
  pAlterTableMsg->numOfCols = htons(tscNumOfFields(pQueryInfo));
1316
  memcpy(pAlterTableMsg->tagVal, pAlterInfo->tagData.data, TSDB_MAX_TAGS_LEN);
H
hzcheng 已提交
1317

S
slguan 已提交
1318
  SSchema *pSchema = pAlterTableMsg->schema;
1319 1320
  for (int i = 0; i < tscNumOfFields(pQueryInfo); ++i) {
    TAOS_FIELD *pField = tscFieldInfoGetField(pQueryInfo, i);
H
hzcheng 已提交
1321 1322 1323 1324 1325 1326 1327 1328 1329

    pSchema->type = pField->type;
    strcpy(pSchema->name, pField->name);
    pSchema->bytes = htons(pField->bytes);
    pSchema++;
  }

  pMsg = (char *)pSchema;

S
slguan 已提交
1330
  msgLen = pMsg - (char*)pAlterTableMsg;
H
hzcheng 已提交
1331
  pCmd->payloadLen = msgLen;
S
slguan 已提交
1332
  pCmd->msgType = TSDB_MSG_TYPE_CM_ALTER_TABLE;
H
hzcheng 已提交
1333 1334

  assert(msgLen + minMsgSize() <= size);
1335

1336
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1337 1338
}

1339
int tscAlterDbMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
S
slguan 已提交
1340
  SSqlCmd *pCmd = &pSql->cmd;
1341
  pCmd->payloadLen = sizeof(SCMAlterDbMsg);
S
slguan 已提交
1342
  pCmd->msgType = TSDB_MSG_TYPE_CM_ALTER_DB;
H
hzcheng 已提交
1343

S
slguan 已提交
1344 1345 1346 1347
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
H
hzcheng 已提交
1348

1349
  SCMAlterDbMsg *pAlterDbMsg = (SCMAlterDbMsg*)pCmd->payload;
1350
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1351
  strcpy(pAlterDbMsg->db, pTableMetaInfo->name);
H
hzcheng 已提交
1352

1353
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1354 1355
}

1356
int tscBuildRetrieveFromMgmtMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
S
slguan 已提交
1357 1358 1359
  SSqlCmd *pCmd = &pSql->cmd;
  pCmd->msgType = TSDB_MSG_TYPE_RETRIEVE;
  pCmd->payloadLen = sizeof(SRetrieveTableMsg);
S
slguan 已提交
1360

S
slguan 已提交
1361 1362 1363
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
H
hzcheng 已提交
1364
  }
S
slguan 已提交
1365

S
slguan 已提交
1366 1367 1368 1369
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
  SRetrieveTableMsg *pRetrieveMsg = (SRetrieveTableMsg*)pCmd->payload;
  pRetrieveMsg->qhandle = htobe64(pSql->res.qhandle);
  pRetrieveMsg->free = htons(pQueryInfo->type);
H
hzcheng 已提交
1370

1371
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1372 1373
}

1374
static int tscSetResultPointer(SQueryInfo *pQueryInfo, SSqlRes *pRes) {
1375
  if (tscCreateResPointerInfo(pRes, pQueryInfo) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
1376 1377 1378
    return pRes->code;
  }

1379
  for (int i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
H
hjxilinx 已提交
1380 1381
    int16_t offset = tscFieldInfoGetOffset(pQueryInfo, i);
    pRes->tsrow[i] = (pRes->data + offset * pRes->numOfRows);
H
hzcheng 已提交
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
  }

  return 0;
}

/*
 * this function can only be called once.
 * by using pRes->rspType to denote its status
 *
 * if pRes->rspType is 1, no more result
 */
static int tscLocalResultCommonBuilder(SSqlObj *pSql, int32_t numOfRes) {
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;
1396

1397
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
1398

H
hzcheng 已提交
1399 1400 1401 1402 1403 1404 1405
  pRes->code = TSDB_CODE_SUCCESS;

  if (pRes->rspType == 0) {
    pRes->numOfRows = numOfRes;
    pRes->row = 0;
    pRes->rspType = 1;

1406
    tscSetResultPointer(pQueryInfo, pRes);
H
hzcheng 已提交
1407
  } else {
S
slguan 已提交
1408
    tscResetForNextRetrieve(pRes);
H
hzcheng 已提交
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
  }

  uint8_t code = pSql->res.code;
  if (pSql->fp) {
    if (code == TSDB_CODE_SUCCESS) {
      (*pSql->fp)(pSql->param, pSql, pSql->res.numOfRows);
    } else {
      tscQueueAsyncRes(pSql);
    }
  }

  return code;
}

int tscProcessDescribeTableRsp(SSqlObj *pSql) {
S
slguan 已提交
1424
  SSqlCmd *       pCmd = &pSql->cmd;
1425
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hzcheng 已提交
1426

H
hjxilinx 已提交
1427
  STableComInfo tinfo = tscGetTableInfo(pTableMetaInfo->pTableMeta);
H
hjxilinx 已提交
1428 1429
  
  int32_t numOfRes = tinfo.numOfColumns + tinfo.numOfTags;
H
hzcheng 已提交
1430 1431 1432 1433
  return tscLocalResultCommonBuilder(pSql, numOfRes);
}

int tscProcessTagRetrieveRsp(SSqlObj *pSql) {
1434
//  SSqlCmd *pCmd = &pSql->cmd;
1435

1436 1437
//  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
//  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
S
slguan 已提交
1438 1439

  int32_t numOfRes = 0;
H
hjxilinx 已提交
1440
#if 0
1441
  if (tscSqlExprGet(pQueryInfo, 0)->functionId == TSDB_FUNC_TAGPRJ) {
H
hjxilinx 已提交
1442
    numOfRes = pTableMetaInfo->pMetricMeta->numOfTables;
H
hzcheng 已提交
1443 1444 1445
  } else {
    numOfRes = 1;  // for count function, there is only one output.
  }
H
hjxilinx 已提交
1446 1447 1448
  
#endif

H
hzcheng 已提交
1449 1450 1451 1452 1453 1454 1455
  return tscLocalResultCommonBuilder(pSql, numOfRes);
}

int tscProcessRetrieveMetricRsp(SSqlObj *pSql) {
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;

H
hjxilinx 已提交
1456 1457
  pRes->code = tscDoLocalreduce(pSql);
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hzcheng 已提交
1458 1459

  if (pRes->code == TSDB_CODE_SUCCESS && pRes->numOfRows > 0) {
1460
    tscSetResultPointer(pQueryInfo, pRes);
H
hzcheng 已提交
1461 1462 1463 1464
  }

  pRes->row = 0;

1465
  uint8_t code = pRes->code;
H
hzcheng 已提交
1466
  if (pSql->fp) {  // async retrieve metric data
1467 1468
    if (pRes->code == TSDB_CODE_SUCCESS) {
      (*pSql->fp)(pSql->param, pSql, pRes->numOfRows);
H
hzcheng 已提交
1469 1470 1471 1472 1473 1474 1475 1476
    } else {
      tscQueueAsyncRes(pSql);
    }
  }

  return code;
}

S
slguan 已提交
1477
int tscProcessEmptyResultRsp(SSqlObj *pSql) { return tscLocalResultCommonBuilder(pSql, 0); }
H
hzcheng 已提交
1478

1479
int tscBuildConnectMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1480
  STscObj *pObj = pSql->pTscObj;
S
slguan 已提交
1481
  SSqlCmd *pCmd = &pSql->cmd;
S
slguan 已提交
1482
  pCmd->msgType = TSDB_MSG_TYPE_CM_CONNECT;
1483
  pCmd->payloadLen = sizeof(SCMConnectMsg);
H
hzcheng 已提交
1484

S
slguan 已提交
1485 1486 1487 1488 1489
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }

1490
  SCMConnectMsg *pConnect = (SCMConnectMsg*)pCmd->payload;
H
hzcheng 已提交
1491 1492 1493 1494 1495

  char *db;  // ugly code to move the space
  db = strstr(pObj->db, TS_PATH_DELIMITER);
  db = (db == NULL) ? pObj->db : db + 1;
  strcpy(pConnect->db, db);
S
slguan 已提交
1496
  strcpy(pConnect->clientVersion, version);
S
slguan 已提交
1497
  strcpy(pConnect->msgVersion, "");
H
hzcheng 已提交
1498

1499
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1500 1501
}

H
hjxilinx 已提交
1502
int tscBuildTableMetaMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
1503
  SCMTableInfoMsg *pInfoMsg;
S
slguan 已提交
1504
  char *         pMsg;
H
hzcheng 已提交
1505 1506 1507 1508 1509
  int            msgLen = 0;

  char *tmpData = 0;
  if (pSql->cmd.allocSize > 0) {
    tmpData = calloc(1, pSql->cmd.allocSize);
1510 1511 1512 1513
    if (NULL == tmpData) {
      return TSDB_CODE_CLI_OUT_OF_MEMORY;
    }

H
hzcheng 已提交
1514 1515 1516 1517
    // STagData is in binary format, strncpy is not available
    memcpy(tmpData, pSql->cmd.payload, pSql->cmd.allocSize);
  }

1518 1519 1520
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);

H
hjxilinx 已提交
1521
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
S
slguan 已提交
1522

1523
  pInfoMsg = (SCMTableInfoMsg *)pCmd->payload;
H
hjxilinx 已提交
1524
  strcpy(pInfoMsg->tableId, pTableMetaInfo->name);
H
hjxilinx 已提交
1525
  pInfoMsg->createFlag = htons(pSql->cmd.autoCreated ? 1 : 0);
S
slguan 已提交
1526

1527
  pMsg = (char*)pInfoMsg + sizeof(SCMTableInfoMsg);
H
hzcheng 已提交
1528

H
hjxilinx 已提交
1529
  if (pSql->cmd.autoCreated) {
H
hzcheng 已提交
1530 1531 1532 1533
    memcpy(pInfoMsg->tags, tmpData, sizeof(STagData));
    pMsg += sizeof(STagData);
  }

H
hjxilinx 已提交
1534
  pCmd->payloadLen = pMsg - (char*)pInfoMsg;;
S
slguan 已提交
1535
  pCmd->msgType = TSDB_MSG_TYPE_CM_TABLE_META;
H
hzcheng 已提交
1536 1537 1538 1539

  tfree(tmpData);

  assert(msgLen + minMsgSize() <= pCmd->allocSize);
1540
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1541 1542
}

S
slguan 已提交
1543
/**
1544
 *  multi table meta req pkg format:
1545
 *  | SMgmtHead | SCMMultiTableInfoMsg | tableId0 | tableId1 | tableId2 | ......
S
slguan 已提交
1546 1547
 *      no used         4B
 **/
1548
int tscBuildMultiMeterMetaMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
S
slguan 已提交
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
  SSqlCmd *pCmd = &pSql->cmd;

  // copy payload content to temp buff
  char *tmpData = 0;
  if (pCmd->payloadLen > 0) {
    tmpData = calloc(1, pCmd->payloadLen + 1);
    if (NULL == tmpData) return -1;
    memcpy(tmpData, pCmd->payload, pCmd->payloadLen);
  }

  // fill head info
  SMgmtHead *pMgmt = (SMgmtHead *)(pCmd->payload + tsRpcHeadSize);
S
slguan 已提交
1561
  memset(pMgmt->db, 0, TSDB_TABLE_ID_LEN);  // server don't need the db
S
slguan 已提交
1562

1563
  SCMMultiTableInfoMsg *pInfoMsg = (SCMMultiTableInfoMsg *)(pCmd->payload + tsRpcHeadSize + sizeof(SMgmtHead));
S
slguan 已提交
1564
  pInfoMsg->numOfTables = htonl((int32_t)pCmd->count);
S
slguan 已提交
1565 1566

  if (pCmd->payloadLen > 0) {
S
slguan 已提交
1567
    memcpy(pInfoMsg->tableIds, tmpData, pCmd->payloadLen);
S
slguan 已提交
1568 1569 1570 1571
  }

  tfree(tmpData);

1572
  pCmd->payloadLen += sizeof(SMgmtHead) + sizeof(SCMMultiTableInfoMsg);
S
slguan 已提交
1573
  pCmd->msgType = TSDB_MSG_TYPE_CM_TABLES_META;
S
slguan 已提交
1574 1575 1576

  assert(pCmd->payloadLen + minMsgSize() <= pCmd->allocSize);

S
slguan 已提交
1577
  tscTrace("%p build load multi-metermeta msg completed, numOfTables:%d, msg size:%d", pSql, pCmd->count,
S
slguan 已提交
1578 1579 1580 1581 1582
           pCmd->payloadLen);

  return pCmd->payloadLen;
}

1583
static UNUSED_FUNC int32_t tscEstimateMetricMetaMsgSize(SSqlCmd *pCmd) {
H
hzcheng 已提交
1584
  const int32_t defaultSize =
S
slguan 已提交
1585
      minMsgSize() + sizeof(SSuperTableMetaMsg) + sizeof(SMgmtHead) + sizeof(int16_t) * TSDB_MAX_TAGS;
1586
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
hzcheng 已提交
1587

S
slguan 已提交
1588
  int32_t n = 0;
1589 1590 1591 1592
  size_t size = taosArrayGetSize(pQueryInfo->tagCond.pCond);
  for (int32_t i = 0; i < size; ++i) {
    assert(0);
//    n += strlen(pQueryInfo->tagCond.cond[i].cond);
H
hzcheng 已提交
1593
  }
S
slguan 已提交
1594

H
hjxilinx 已提交
1595
  int32_t tagLen = n * TSDB_NCHAR_SIZE;
1596 1597
  if (pQueryInfo->tagCond.tbnameCond.cond != NULL) {
    tagLen += strlen(pQueryInfo->tagCond.tbnameCond.cond) * TSDB_NCHAR_SIZE;
H
hjxilinx 已提交
1598
  }
1599

S
slguan 已提交
1600
  int32_t joinCondLen = (TSDB_TABLE_ID_LEN + sizeof(int16_t)) * 2;
S
slguan 已提交
1601
  int32_t elemSize = sizeof(SSuperTableMetaElemMsg) * pQueryInfo->numOfTables;
H
hjxilinx 已提交
1602
  
1603
  int32_t colSize = pQueryInfo->groupbyExpr.numOfGroupCols*sizeof(SColIndex);
S
slguan 已提交
1604

H
hjxilinx 已提交
1605
  int32_t len = tagLen + joinCondLen + elemSize + colSize + defaultSize;
S
slguan 已提交
1606 1607

  return MAX(len, TSDB_DEFAULT_PAYLOAD_SIZE);
H
hzcheng 已提交
1608 1609
}

H
hjxilinx 已提交
1610 1611 1612
int tscBuildSTableVgroupMsg(SSqlObj *pSql, SSqlInfo *pInfo) {

#if 0
S
slguan 已提交
1613
  SSuperTableMetaMsg *pMetaMsg;
H
hzcheng 已提交
1614 1615
  char *          pMsg, *pStart;
  int             msgLen = 0;
S
slguan 已提交
1616
  int             tableIndex = 0;
H
hzcheng 已提交
1617

1618 1619 1620
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);

1621
  STagCond *pTagCond = &pQueryInfo->tagCond;
S
slguan 已提交
1622

H
hjxilinx 已提交
1623
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, tableIndex);
H
hzcheng 已提交
1624 1625

  int32_t size = tscEstimateMetricMetaMsgSize(pCmd);
S
slguan 已提交
1626 1627 1628 1629
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
    tscError("%p failed to malloc for metric meter msg", pSql);
    return -1;
  }
H
hzcheng 已提交
1630 1631 1632 1633 1634

  pStart = pCmd->payload + tsRpcHeadSize;
  pMsg = pStart;

  SMgmtHead *pMgmt = (SMgmtHead *)pMsg;
H
hjxilinx 已提交
1635
  tscGetDBInfoFromMeterId(pTableMetaInfo->name, pMgmt->db);
H
hzcheng 已提交
1636 1637 1638

  pMsg += sizeof(SMgmtHead);

S
slguan 已提交
1639
  pMetaMsg = (SSuperTableMetaMsg *)pMsg;
S
slguan 已提交
1640
  pMetaMsg->numOfTables = htonl(pQueryInfo->numOfTables);
S
slguan 已提交
1641

S
slguan 已提交
1642
  pMsg += sizeof(SSuperTableMetaMsg);
S
slguan 已提交
1643 1644 1645 1646 1647

  int32_t offset = pMsg - (char *)pMetaMsg;
  pMetaMsg->join = htonl(offset);

  // todo refactor
S
slguan 已提交
1648
  pMetaMsg->joinCondLen = htonl((TSDB_TABLE_ID_LEN + sizeof(int16_t)) * 2);
H
hzcheng 已提交
1649

S
slguan 已提交
1650
  memcpy(pMsg, pTagCond->joinInfo.left.tableId, TSDB_TABLE_ID_LEN);
S
slguan 已提交
1651
  pMsg += TSDB_TABLE_ID_LEN;
H
hzcheng 已提交
1652

S
slguan 已提交
1653 1654 1655
  *(int16_t *)pMsg = pTagCond->joinInfo.left.tagCol;
  pMsg += sizeof(int16_t);

S
slguan 已提交
1656
  memcpy(pMsg, pTagCond->joinInfo.right.tableId, TSDB_TABLE_ID_LEN);
S
slguan 已提交
1657
  pMsg += TSDB_TABLE_ID_LEN;
S
slguan 已提交
1658 1659 1660 1661

  *(int16_t *)pMsg = pTagCond->joinInfo.right.tagCol;
  pMsg += sizeof(int16_t);

1662
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
1663
    pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, i);
H
hjxilinx 已提交
1664
    uint64_t uid = pTableMetaInfo->pTableMeta->uid;
S
slguan 已提交
1665 1666 1667 1668

    offset = pMsg - (char *)pMetaMsg;
    pMetaMsg->metaElem[i] = htonl(offset);

S
slguan 已提交
1669 1670
    SSuperTableMetaElemMsg *pElem = (SSuperTableMetaElemMsg *)pMsg;
    pMsg += sizeof(SSuperTableMetaElemMsg);
S
slguan 已提交
1671 1672 1673 1674

    // convert to unicode before sending to mnode for metric query
    int32_t condLen = 0;
    if (pTagCond->numOfTagCond > 0) {
1675
      SCond *pCond = tsGetSTableQueryCond(pTagCond, uid);
H
hjxilinx 已提交
1676
      if (pCond != NULL && pCond->cond != NULL) {
H
hjxilinx 已提交
1677
        condLen = strlen(pCond->cond) + 1;
1678

H
hjxilinx 已提交
1679
        bool ret = taosMbsToUcs4(pCond->cond, condLen, pMsg, condLen * TSDB_NCHAR_SIZE);
S
slguan 已提交
1680
        if (!ret) {
1681
          tscError("%p mbs to ucs4 failed:%s", pSql, tsGetSTableQueryCond(pTagCond, uid));
S
slguan 已提交
1682 1683 1684
          return 0;
        }
      }
H
hzcheng 已提交
1685 1686
    }

S
slguan 已提交
1687
    pElem->condLen = htonl(condLen);
H
hzcheng 已提交
1688

S
slguan 已提交
1689 1690 1691
    offset = pMsg - (char *)pMetaMsg;
    pElem->cond = htonl(offset);
    pMsg += condLen * TSDB_NCHAR_SIZE;
H
hzcheng 已提交
1692

S
slguan 已提交
1693 1694 1695
    pElem->rel = htons(pTagCond->relType);
    if (pTagCond->tbnameCond.uid == uid) {
      offset = pMsg - (char *)pMetaMsg;
H
hzcheng 已提交
1696

S
slguan 已提交
1697
      pElem->tableCond = htonl(offset);
H
hjxilinx 已提交
1698 1699 1700 1701 1702 1703 1704
      
      uint32_t len = 0;
      if (pTagCond->tbnameCond.cond != NULL) {
        len = strlen(pTagCond->tbnameCond.cond);
        memcpy(pMsg, pTagCond->tbnameCond.cond, len);
      }
      
H
hjxilinx 已提交
1705 1706
      pElem->tableCondLen = htonl(len);
      pMsg += len;
S
slguan 已提交
1707 1708
    }

1709
    SSqlGroupbyExpr *pGroupby = &pQueryInfo->groupbyExpr;
S
slguan 已提交
1710

H
hjxilinx 已提交
1711
    if (pGroupby->tableIndex != i && pGroupby->numOfGroupCols > 0) {
S
slguan 已提交
1712 1713 1714 1715 1716
      pElem->orderType = 0;
      pElem->orderIndex = 0;
      pElem->numOfGroupCols = 0;
    } else {
      pElem->numOfGroupCols = htons(pGroupby->numOfGroupCols);
H
hjxilinx 已提交
1717 1718
      for (int32_t j = 0; j < pTableMetaInfo->numOfTags; ++j) {
        pElem->tagCols[j] = htons(pTableMetaInfo->tagColumnIndex[j]);
S
slguan 已提交
1719 1720 1721 1722 1723 1724 1725 1726
      }

      if (pGroupby->numOfGroupCols != 0) {
        pElem->orderIndex = htons(pGroupby->orderIndex);
        pElem->orderType = htons(pGroupby->orderType);
        offset = pMsg - (char *)pMetaMsg;

        pElem->groupbyTagColumnList = htonl(offset);
1727
        for (int32_t j = 0; j < pQueryInfo->groupbyExpr.numOfGroupCols; ++j) {
1728 1729
          SColIndex *pCol = &pQueryInfo->groupbyExpr.columnInfo[j];
          SColIndex *pDestCol = (SColIndex *)pMsg;
1730

H
hjxilinx 已提交
1731
          pDestCol->colIdxInBuf = 0;
1732
          pDestCol->colIndex = htons(pCol->colIndex);
H
hjxilinx 已提交
1733 1734
          pDestCol->colId = htons(pDestCol->colId);
          pDestCol->flag = htons(pDestCol->flag);
H
hjxilinx 已提交
1735
          strncpy(pDestCol->name, pCol->name, tListLen(pCol->name));
1736

1737
          pMsg += sizeof(SColIndex);
S
slguan 已提交
1738 1739
        }
      }
H
hzcheng 已提交
1740
    }
S
slguan 已提交
1741

H
hjxilinx 已提交
1742 1743
    strcpy(pElem->tableId, pTableMetaInfo->name);
    pElem->numOfTags = htons(pTableMetaInfo->numOfTags);
S
slguan 已提交
1744 1745 1746

    int16_t len = pMsg - (char *)pElem;
    pElem->elemLen = htons(len);  // redundant data for integrate check
H
hzcheng 已提交
1747 1748 1749 1750
  }

  msgLen = pMsg - pStart;
  pCmd->payloadLen = msgLen;
S
slguan 已提交
1751
  pCmd->msgType = TSDB_MSG_TYPE_CM_STABLE_VGROUP;
H
hzcheng 已提交
1752
  assert(msgLen + minMsgSize() <= size);
H
hjxilinx 已提交
1753
#endif
1754
  
H
hjxilinx 已提交
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
  SSqlCmd *pCmd = &pSql->cmd;

  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);

  SCMSTableVgroupMsg *pStableVgroupMsg = (SCMSTableVgroupMsg *) pCmd->payload;
  strncpy(pStableVgroupMsg->tableId, pTableMetaInfo->name, tListLen(pStableVgroupMsg->tableId));

  pCmd->msgType = TSDB_MSG_TYPE_CM_STABLE_VGROUP;
  pCmd->payloadLen = sizeof(SCMSTableVgroupMsg);

1765
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1766 1767
}

1768
int tscEstimateHeartBeatMsgLength(SSqlObj *pSql) {
H
hzcheng 已提交
1769 1770 1771 1772
  int      size = 0;
  STscObj *pObj = pSql->pTscObj;

  size += tsRpcHeadSize + sizeof(SMgmtHead);
S
slguan 已提交
1773
  size += sizeof(SQqueryList);
H
hzcheng 已提交
1774 1775 1776

  SSqlObj *tpSql = pObj->sqlList;
  while (tpSql) {
S
slguan 已提交
1777
    size += sizeof(SQueryDesc);
H
hzcheng 已提交
1778 1779 1780
    tpSql = tpSql->next;
  }

S
slguan 已提交
1781
  size += sizeof(SStreamList);
H
hzcheng 已提交
1782 1783
  SSqlStream *pStream = pObj->streamList;
  while (pStream) {
S
slguan 已提交
1784
    size += sizeof(SStreamDesc);
H
hzcheng 已提交
1785 1786 1787 1788 1789 1790
    pStream = pStream->next;
  }

  return size + TSDB_EXTRA_PAYLOAD_SIZE;
}

1791
int tscBuildHeartBeatMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1792 1793 1794 1795 1796 1797 1798 1799 1800
  char *pMsg, *pStart;
  int   msgLen = 0;
  int   size = 0;

  SSqlCmd *pCmd = &pSql->cmd;
  STscObj *pObj = pSql->pTscObj;

  pthread_mutex_lock(&pObj->mutex);

1801
  size = tscEstimateHeartBeatMsgLength(pSql);
S
slguan 已提交
1802
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
1803
    pthread_mutex_unlock(&pObj->mutex);
S
slguan 已提交
1804 1805 1806
    tscError("%p failed to malloc for heartbeat msg", pSql);
    return -1;
  }
H
hzcheng 已提交
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819

  pMsg = pCmd->payload + tsRpcHeadSize;
  pStart = pMsg;

  SMgmtHead *pMgmt = (SMgmtHead *)pMsg;
  strcpy(pMgmt->db, pObj->db);
  pMsg += sizeof(SMgmtHead);

  pMsg = tscBuildQueryStreamDesc(pMsg, pObj);
  pthread_mutex_unlock(&pObj->mutex);

  msgLen = pMsg - pStart;
  pCmd->payloadLen = msgLen;
S
slguan 已提交
1820
  pCmd->msgType = TSDB_MSG_TYPE_CM_HEARTBEAT;
H
hzcheng 已提交
1821 1822 1823 1824 1825

  assert(msgLen + minMsgSize() <= size);
  return msgLen;
}

1826 1827
int tscProcessTableMetaRsp(SSqlObj *pSql) {
  STableMetaMsg *pMetaMsg = (STableMetaMsg *)pSql->res.pRsp;
H
hzcheng 已提交
1828

1829 1830
  pMetaMsg->sid = htonl(pMetaMsg->sid);
  pMetaMsg->sversion = htons(pMetaMsg->sversion);
H
hjxilinx 已提交
1831
  pMetaMsg->vgId = htonl(pMetaMsg->vgId);
1832 1833
  pMetaMsg->uid = htobe64(pMetaMsg->uid);
  pMetaMsg->contLen = htons(pMetaMsg->contLen);
1834
  pMetaMsg->numOfColumns = htons(pMetaMsg->numOfColumns);
H
hzcheng 已提交
1835

H
hjxilinx 已提交
1836 1837
  if (pMetaMsg->sid < 0 || pMetaMsg->vgId < 0) {
    tscError("invalid meter vgId:%d, sid%d", pMetaMsg->vgId, pMetaMsg->sid);
H
hzcheng 已提交
1838 1839 1840
    return TSDB_CODE_INVALID_VALUE;
  }

1841 1842
  if (pMetaMsg->numOfTags > TSDB_MAX_TAGS || pMetaMsg->numOfTags < 0) {
    tscError("invalid numOfTags:%d", pMetaMsg->numOfTags);
H
hzcheng 已提交
1843 1844 1845
    return TSDB_CODE_INVALID_VALUE;
  }

1846 1847
  if (pMetaMsg->numOfColumns > TSDB_MAX_COLUMNS || pMetaMsg->numOfColumns <= 0) {
    tscError("invalid numOfColumns:%d", pMetaMsg->numOfColumns);
H
hzcheng 已提交
1848 1849 1850 1851
    return TSDB_CODE_INVALID_VALUE;
  }

  for (int i = 0; i < TSDB_VNODES_SUPPORT; ++i) {
H
hjxilinx 已提交
1852 1853
    pMetaMsg->vpeerDesc[i].ip = htonl(pMetaMsg->vpeerDesc[i].ip);
    pMetaMsg->vpeerDesc[i].dnodeId = htonl(pMetaMsg->vpeerDesc[i].dnodeId);
H
hzcheng 已提交
1854 1855
  }

1856
  SSchema* pSchema = pMetaMsg->schema;
H
hzcheng 已提交
1857

1858
  int32_t numOfTotalCols = pMetaMsg->numOfColumns + pMetaMsg->numOfTags;
H
hzcheng 已提交
1859 1860 1861 1862 1863 1864
  for (int i = 0; i < numOfTotalCols; ++i) {
    pSchema->bytes = htons(pSchema->bytes);
    pSchema->colId = htons(pSchema->colId);
    pSchema++;
  }

1865 1866
  size_t size = 0;
  STableMeta* pTableMeta = tscCreateTableMetaFromMsg(pMetaMsg, &size);
H
hzcheng 已提交
1867

1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878
#if 0
  // if current table is created according to super table, get the table meta of super table
  if (pTableMeta->tableType == TSDB_CHILD_TABLE) {
    char id[TSDB_TABLE_ID_LEN + 1] = {0};
    strncpy(id, pMetaMsg->stableId, TSDB_TABLE_ID_LEN);
  
    // NOTE: if the table meta of super table is not cached at client side yet, the pSTable is NULL
    pTableMeta->pSTable = taosCacheAcquireByName(tscCacheHandle, id);
  }
#endif
  
H
hzcheng 已提交
1879
  // todo add one more function: taosAddDataIfNotExists();
1880
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
H
hjxilinx 已提交
1881
  assert(pTableMetaInfo->pTableMeta == NULL);
H
hzcheng 已提交
1882

H
hjxilinx 已提交
1883 1884 1885
  pTableMetaInfo->pTableMeta =
      (STableMeta *) taosCachePut(tscCacheHandle, pTableMetaInfo->name, pTableMeta, size, tsMeterMetaKeepTimer);
  
1886
  // todo handle out of memory case
1887
  if (pTableMetaInfo->pTableMeta == NULL) {
H
hjxilinx 已提交
1888
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
1889
  }
H
hzcheng 已提交
1890

1891
  free(pTableMeta);
1892
  
H
hjxilinx 已提交
1893
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1894 1895
}

S
slguan 已提交
1896
/**
1897
 *  multi table meta rsp pkg format:
1898
 *  | STaosRsp | ieType | SCMMultiTableInfoMsg | SMeterMeta0 | SSchema0 | SMeterMeta1 | SSchema1 | SMeterMeta2 | SSchema2
S
slguan 已提交
1899 1900 1901
 *  |...... 1B        1B            4B
 **/
int tscProcessMultiMeterMetaRsp(SSqlObj *pSql) {
1902 1903 1904 1905
//  uint8_t  ieType;
//  int32_t  totalNum;
//  int32_t  i;
#if 0
S
slguan 已提交
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917
  char *rsp = pSql->res.pRsp;

  ieType = *rsp;
  if (ieType != TSDB_IE_TYPE_META) {
    tscError("invalid ie type:%d", ieType);
    pSql->res.code = TSDB_CODE_INVALID_IE;
    pSql->res.numOfTotal = 0;
    return TSDB_CODE_OTHERS;
  }

  rsp++;

1918
  SCMMultiTableInfoMsg *pInfo = (SCMMultiTableInfoMsg *)rsp;
S
slguan 已提交
1919
  totalNum = htonl(pInfo->numOfTables);
1920
  rsp += sizeof(SCMMultiTableInfoMsg);
S
slguan 已提交
1921 1922

  for (i = 0; i < totalNum; i++) {
S
slguan 已提交
1923
    SMultiTableMeta *pMultiMeta = (SMultiTableMeta *)rsp;
1924
    STableMeta *     pMeta = pMultiMeta->metas;
S
slguan 已提交
1925 1926 1927

    pMeta->sid = htonl(pMeta->sid);
    pMeta->sversion = htons(pMeta->sversion);
H
hjxilinx 已提交
1928
    pMeta->vgId = htonl(pMeta->vgId);
S
slguan 已提交
1929 1930
    pMeta->uid = htobe64(pMeta->uid);

H
hjxilinx 已提交
1931 1932
    if (pMeta->sid <= 0 || pMeta->vgId < 0) {
      tscError("invalid meter vgId:%d, sid%d", pMeta->vgId, pMeta->sid);
S
slguan 已提交
1933 1934 1935 1936 1937
      pSql->res.code = TSDB_CODE_INVALID_VALUE;
      pSql->res.numOfTotal = i;
      return TSDB_CODE_OTHERS;
    }

H
hjxilinx 已提交
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997
    //    pMeta->numOfColumns = htons(pMeta->numOfColumns);
    //
    //    if (pMeta->numOfTags > TSDB_MAX_TAGS || pMeta->numOfTags < 0) {
    //      tscError("invalid tag value count:%d", pMeta->numOfTags);
    //      pSql->res.code = TSDB_CODE_INVALID_VALUE;
    //      pSql->res.numOfTotal = i;
    //      return TSDB_CODE_OTHERS;
    //    }
    //
    //    if (pMeta->numOfTags > TSDB_MAX_TAGS || pMeta->numOfTags < 0) {
    //      tscError("invalid numOfTags:%d", pMeta->numOfTags);
    //      pSql->res.code = TSDB_CODE_INVALID_VALUE;
    //      pSql->res.numOfTotal = i;
    //      return TSDB_CODE_OTHERS;
    //    }
    //
    //    if (pMeta->numOfColumns > TSDB_MAX_COLUMNS || pMeta->numOfColumns < 0) {
    //      tscError("invalid numOfColumns:%d", pMeta->numOfColumns);
    //      pSql->res.code = TSDB_CODE_INVALID_VALUE;
    //      pSql->res.numOfTotal = i;
    //      return TSDB_CODE_OTHERS;
    //    }
    //
    //    for (int j = 0; j < TSDB_VNODES_SUPPORT; ++j) {
    //      pMeta->vpeerDesc[j].vnode = htonl(pMeta->vpeerDesc[j].vnode);
    //    }
    //
    //    pMeta->rowSize = 0;
    //    rsp += sizeof(SMultiTableMeta);
    //    pSchema = (SSchema *)rsp;
    //
    //    int32_t numOfTotalCols = pMeta->numOfColumns + pMeta->numOfTags;
    //    for (int j = 0; j < numOfTotalCols; ++j) {
    //      pSchema->bytes = htons(pSchema->bytes);
    //      pSchema->colId = htons(pSchema->colId);
    //
    //      // ignore the tags length
    //      if (j < pMeta->numOfColumns) {
    //        pMeta->rowSize += pSchema->bytes;
    //      }
    //      pSchema++;
    //    }
    //
    //    rsp += numOfTotalCols * sizeof(SSchema);
    //
    //    int32_t  tagLen = 0;
    //    SSchema *pTagsSchema = tscGetTableTagSchema(pMeta);
    //
    //    if (pMeta->tableType == TSDB_CHILD_TABLE) {
    //      for (int32_t j = 0; j < pMeta->numOfTags; ++j) {
    //        tagLen += pTagsSchema[j].bytes;
    //      }
    //    }
    //
    //    rsp += tagLen;
    //    int32_t size = (int32_t)(rsp - ((char *)pMeta));  // Consistent with STableMeta in cache
    //
    //    pMeta->index = 0;
    //    (void)taosCachePut(tscCacheHandle, pMeta->tableId, (char *)pMeta, size, tsMeterMetaKeepTimer);
    //  }
S
slguan 已提交
1998
  }
H
hjxilinx 已提交
1999
  
S
slguan 已提交
2000 2001 2002
  pSql->res.code = TSDB_CODE_SUCCESS;
  pSql->res.numOfTotal = i;
  tscTrace("%p load multi-metermeta resp complete num:%d", pSql, pSql->res.numOfTotal);
2003 2004
#endif
  
S
slguan 已提交
2005 2006 2007
  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
2008 2009
int tscProcessSTableVgroupRsp(SSqlObj *pSql) {
#if 0
S
slguan 已提交
2010 2011
  void **      metricMetaList = NULL;
  int32_t *    sizes = NULL;
H
hjxilinx 已提交
2012
  
S
slguan 已提交
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028
  int32_t num = htons(*(int16_t *)rsp);
  rsp += sizeof(int16_t);

  metricMetaList = calloc(1, POINTER_BYTES * num);
  sizes = calloc(1, sizeof(int32_t) * num);

  // return with error code
  if (metricMetaList == NULL || sizes == NULL) {
    tfree(metricMetaList);
    tfree(sizes);
    pSql->res.code = TSDB_CODE_CLI_OUT_OF_MEMORY;

    return pSql->res.code;
  }

  for (int32_t k = 0; k < num; ++k) {
S
slguan 已提交
2029
    pMeta = (SSuperTableMeta *)rsp;
S
slguan 已提交
2030 2031

    size_t size = (size_t)pSql->res.rspLen - 1;
S
slguan 已提交
2032
    rsp = rsp + sizeof(SSuperTableMeta);
S
slguan 已提交
2033

S
slguan 已提交
2034
    pMeta->numOfTables = htonl(pMeta->numOfTables);
S
slguan 已提交
2035 2036 2037
    pMeta->numOfVnodes = htonl(pMeta->numOfVnodes);
    pMeta->tagLen = htons(pMeta->tagLen);

2038
    size += pMeta->numOfVnodes * sizeof(SVnodeSidList *) + pMeta->numOfTables * sizeof(STableIdInfo *);
H
hzcheng 已提交
2039

2040 2041
    char *pBuf = calloc(1, size);
    if (pBuf == NULL) {
S
slguan 已提交
2042 2043 2044
      pSql->res.code = TSDB_CODE_CLI_OUT_OF_MEMORY;
      goto _error_clean;
    }
H
hzcheng 已提交
2045

S
slguan 已提交
2046
    SSuperTableMeta *pNewMetricMeta = (SSuperTableMeta *)pBuf;
S
slguan 已提交
2047
    metricMetaList[k] = pNewMetricMeta;
H
hzcheng 已提交
2048

S
slguan 已提交
2049
    pNewMetricMeta->numOfTables = pMeta->numOfTables;
S
slguan 已提交
2050 2051
    pNewMetricMeta->numOfVnodes = pMeta->numOfVnodes;
    pNewMetricMeta->tagLen = pMeta->tagLen;
H
hzcheng 已提交
2052

S
slguan 已提交
2053
    pBuf = pBuf + sizeof(SSuperTableMeta) + pNewMetricMeta->numOfVnodes * sizeof(SVnodeSidList *);
H
hzcheng 已提交
2054

S
slguan 已提交
2055 2056
    for (int32_t i = 0; i < pMeta->numOfVnodes; ++i) {
      SVnodeSidList *pSidLists = (SVnodeSidList *)rsp;
2057
      memcpy(pBuf, pSidLists, sizeof(SVnodeSidList));
H
hzcheng 已提交
2058

2059 2060
      pNewMetricMeta->list[i] = pBuf - (char *)pNewMetricMeta;  // offset value
      SVnodeSidList *pLists = (SVnodeSidList *)pBuf;
H
hzcheng 已提交
2061

S
slguan 已提交
2062
      tscTrace("%p metricmeta:vid:%d,numOfTables:%d", pSql, i, pLists->numOfSids);
H
hzcheng 已提交
2063

2064
      pBuf += sizeof(SVnodeSidList) + sizeof(STableIdInfo *) * pSidLists->numOfSids;
S
slguan 已提交
2065
      rsp += sizeof(SVnodeSidList);
H
hzcheng 已提交
2066

2067
      size_t elemSize = sizeof(STableIdInfo) + pNewMetricMeta->tagLen;
S
slguan 已提交
2068
      for (int32_t j = 0; j < pSidLists->numOfSids; ++j) {
2069 2070
        pLists->pSidExtInfoList[j] = pBuf - (char *)pLists;
        memcpy(pBuf, rsp, elemSize);
2071

2072 2073
        ((STableIdInfo *)pBuf)->uid = htobe64(((STableIdInfo *)pBuf)->uid);
        ((STableIdInfo *)pBuf)->sid = htonl(((STableIdInfo *)pBuf)->sid);
2074

2075 2076
        rsp += elemSize;
        pBuf += elemSize;
S
slguan 已提交
2077
      }
H
hzcheng 已提交
2078
    }
S
slguan 已提交
2079

2080
    sizes[k] = pBuf - (char *)pNewMetricMeta;
H
hzcheng 已提交
2081 2082
  }

2083
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
S
slguan 已提交
2084 2085 2086
  for (int32_t i = 0; i < num; ++i) {
    char name[TSDB_MAX_TAGS_LEN + 1] = {0};

H
hjxilinx 已提交
2087
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, i);
H
hjxilinx 已提交
2088
    tscGetMetricMetaCacheKey(pQueryInfo, name, pTableMetaInfo->pTableMeta->uid);
H
hzcheng 已提交
2089

S
slguan 已提交
2090 2091 2092
#ifdef _DEBUG_VIEW
    printf("generate the metric key:%s, index:%d\n", name, i);
#endif
H
hzcheng 已提交
2093

S
slguan 已提交
2094
    // release the used metricmeta
H
hjxilinx 已提交
2095 2096
    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pMetricMeta), false);
    pTableMetaInfo->pMetricMeta = (SSuperTableMeta *)taosCachePut(tscCacheHandle, name, (char *)metricMetaList[i],
S
slguan 已提交
2097 2098 2099 2100
                                                                      sizes[i], tsMetricMetaKeepTimer);
    tfree(metricMetaList[i]);

    // failed to put into cache
H
hjxilinx 已提交
2101
    if (pTableMetaInfo->pMetricMeta == NULL) {
S
slguan 已提交
2102 2103 2104
      pSql->res.code = TSDB_CODE_CLI_OUT_OF_MEMORY;
      goto _error_clean;
    }
H
hzcheng 已提交
2105 2106
  }

S
slguan 已提交
2107 2108 2109 2110 2111 2112 2113 2114
_error_clean:
  // free allocated resource
  for (int32_t i = 0; i < num; ++i) {
    tfree(metricMetaList[i]);
  }

  free(sizes);
  free(metricMetaList);
H
hjxilinx 已提交
2115
#endif
2116
  SSqlRes* pRes = &pSql->res;
H
hjxilinx 已提交
2117
  
2118
  SCMSTableVgroupRspMsg *pStableVgroup = (SCMSTableVgroupRspMsg *)pRes->pRsp;
H
hjxilinx 已提交
2119 2120
  pStableVgroup->numOfDnodes = htonl(pStableVgroup->numOfDnodes);
  
2121 2122 2123
  // master sqlObj locates in param
  SSqlObj* parent = pSql->param;
  assert(parent != NULL);
H
hjxilinx 已提交
2124
  
2125
  SSqlCmd* pCmd = &parent->cmd;
H
hjxilinx 已提交
2126 2127
  STableMetaInfo* pInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
  
2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139
  pInfo->vgroupList = malloc(pRes->rspLen);
  memcpy(pInfo->vgroupList, pStableVgroup, pRes->rspLen);
  
  for(int32_t i = 0; i < pInfo->vgroupList->numOfDnodes; ++i) {
    STableDnodeVgroupInfo* pVgroups = &pInfo->vgroupList->dnodeVgroups[i];
    pVgroups->numOfVgroups = htonl(pVgroups->numOfVgroups);
    pVgroups->ipAddr.ip = htonl(pVgroups->ipAddr.ip);
    pVgroups->ipAddr.port = htons(pVgroups->ipAddr.port);
    
    for(int32_t j = 0; j < pVgroups->numOfVgroups; ++j) {
      pVgroups->vgId[j] = htonl(pVgroups->vgId[j]);
    }
H
hjxilinx 已提交
2140 2141
  }
  
S
slguan 已提交
2142
  return pSql->res.code;
H
hzcheng 已提交
2143 2144 2145 2146 2147 2148
}

/*
 * current process do not use the cache at all
 */
int tscProcessShowRsp(SSqlObj *pSql) {
H
hjxilinx 已提交
2149
  STableMetaMsg * pMetaMsg;
2150
  SCMShowRsp *pShow;
S
slguan 已提交
2151
  SSchema *    pSchema;
H
hzcheng 已提交
2152 2153
  char         key[20];

2154 2155 2156
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;

H
hjxilinx 已提交
2157
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
2158

H
hjxilinx 已提交
2159
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hzcheng 已提交
2160

2161
  pShow = (SCMShowRsp *)pRes->pRsp;
S
slguan 已提交
2162
  pShow->qhandle = htobe64(pShow->qhandle);
H
hzcheng 已提交
2163 2164
  pRes->qhandle = pShow->qhandle;

S
slguan 已提交
2165
  tscResetForNextRetrieve(pRes);
H
hjxilinx 已提交
2166
  pMetaMsg = &(pShow->tableMeta);
H
hzcheng 已提交
2167

H
hjxilinx 已提交
2168
  pMetaMsg->numOfColumns = ntohs(pMetaMsg->numOfColumns);
H
hzcheng 已提交
2169

H
hjxilinx 已提交
2170
  pSchema = pMetaMsg->schema;
H
hjxilinx 已提交
2171 2172
  pMetaMsg->sid = ntohs(pMetaMsg->sid);
  for (int i = 0; i < pMetaMsg->numOfColumns; ++i) {
H
hzcheng 已提交
2173 2174 2175 2176
    pSchema->bytes = htons(pSchema->bytes);
    pSchema++;
  }

2177
  key[0] = pCmd->msgType + 'a';
H
hzcheng 已提交
2178 2179
  strcpy(key + 1, "showlist");

H
hjxilinx 已提交
2180
  taosCacheRelease(tscCacheHandle, (void *)&(pTableMetaInfo->pTableMeta), false);
H
hjxilinx 已提交
2181 2182 2183
  size_t size = 0;
  STableMeta* pTableMeta = tscCreateTableMetaFromMsg(pMetaMsg, &size);
  
H
hjxilinx 已提交
2184
  pTableMetaInfo->pTableMeta =
H
hjxilinx 已提交
2185 2186
      (STableMeta *)taosCachePut(tscCacheHandle, key, (char *)pTableMeta, size, tsMeterMetaKeepTimer);
  
2187
  pCmd->numOfCols = pQueryInfo->fieldsInfo.numOfOutputCols;
H
hjxilinx 已提交
2188
  SSchema *pTableSchema = tscGetTableSchema(pTableMetaInfo->pTableMeta);
H
hzcheng 已提交
2189

H
hjxilinx 已提交
2190
  tscColumnBaseInfoReserve(&pQueryInfo->colList, pMetaMsg->numOfColumns);
S
slguan 已提交
2191 2192
  SColumnIndex index = {0};

H
hjxilinx 已提交
2193
  for (int16_t i = 0; i < pMetaMsg->numOfColumns; ++i) {
S
slguan 已提交
2194
    index.columnIndex = i;
2195
    tscColumnBaseInfoInsert(pQueryInfo, &index);
H
hjxilinx 已提交
2196
    tscFieldInfoSetValFromSchema(&pQueryInfo->fieldsInfo, i, &pTableSchema[i]);
H
hjxilinx 已提交
2197 2198
    
    pQueryInfo->fieldsInfo.pSqlExpr[i] = tscSqlExprInsert(pQueryInfo, i, TSDB_FUNC_TS_DUMMY, &index,
H
hjxilinx 已提交
2199
                     pTableSchema[i].type, pTableSchema[i].bytes, pTableSchema[i].bytes);
H
hzcheng 已提交
2200 2201
  }

2202
  tscFieldInfoCalOffset(pQueryInfo);
H
hjxilinx 已提交
2203 2204
  
  tfree(pTableMeta);
H
hzcheng 已提交
2205 2206 2207 2208
  return 0;
}

int tscProcessConnectRsp(SSqlObj *pSql) {
S
slguan 已提交
2209
  char temp[TSDB_TABLE_ID_LEN * 2];
H
hzcheng 已提交
2210 2211 2212
  STscObj *pObj = pSql->pTscObj;
  SSqlRes *pRes = &pSql->res;

2213
  SCMConnectRsp *pConnect = (SCMConnectRsp *)pRes->pRsp;
H
hzcheng 已提交
2214
  strcpy(pObj->acctId, pConnect->acctId);  // copy acctId from response
2215 2216
  int32_t len = sprintf(temp, "%s%s%s", pObj->acctId, TS_PATH_DELIMITER, pObj->db);

H
hjxilinx 已提交
2217 2218 2219
  assert(len <= tListLen(pObj->db));
  strncpy(pObj->db, temp, tListLen(pObj->db));
  
S
slguan 已提交
2220
//  SIpList *    pIpList;
2221
//  char *rsp = pRes->pRsp + sizeof(SCMConnectRsp);
S
slguan 已提交
2222 2223
//  pIpList = (SIpList *)rsp;
//  tscSetMgmtIpList(pIpList);
H
hzcheng 已提交
2224

S
slguan 已提交
2225
  strcpy(pObj->sversion, pConnect->serverVersion);
H
hzcheng 已提交
2226 2227 2228 2229 2230 2231 2232 2233
  pObj->writeAuth = pConnect->writeAuth;
  pObj->superAuth = pConnect->superAuth;
  taosTmrReset(tscProcessActivityTimer, tsShellActivityTimer * 500, pObj, tscTmr, &pObj->pTimer);

  return 0;
}

int tscProcessUseDbRsp(SSqlObj *pSql) {
S
slguan 已提交
2234
  STscObj *       pObj = pSql->pTscObj;
2235
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
S
slguan 已提交
2236

H
hjxilinx 已提交
2237
  strcpy(pObj->db, pTableMetaInfo->name);
H
hzcheng 已提交
2238 2239 2240 2241
  return 0;
}

int tscProcessDropDbRsp(SSqlObj *UNUSED_PARAM(pSql)) {
2242
  taosCacheEmpty(tscCacheHandle);
H
hzcheng 已提交
2243 2244 2245 2246
  return 0;
}

int tscProcessDropTableRsp(SSqlObj *pSql) {
2247
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
S
slguan 已提交
2248

H
hjxilinx 已提交
2249 2250
  STableMeta *pTableMeta = taosCacheAcquireByName(tscCacheHandle, pTableMetaInfo->name);
  if (pTableMeta == NULL) {
H
hzcheng 已提交
2251 2252 2253 2254 2255 2256 2257 2258
    /* not in cache, abort */
    return 0;
  }

  /*
   * 1. if a user drops one table, which is the only table in a vnode, remove operation will incur vnode to be removed.
   * 2. Then, a user creates a new metric followed by a table with identical name of removed table but different schema,
   * here the table will reside in a new vnode.
S
slguan 已提交
2259 2260
   * The cached information is expired, however, we may have lost the ref of original meter. So, clear whole cache
   * instead.
H
hzcheng 已提交
2261
   */
H
hjxilinx 已提交
2262 2263
  tscTrace("%p force release metermeta after drop table:%s", pSql, pTableMetaInfo->name);
  taosCacheRelease(tscCacheHandle, (void **)&pTableMeta, true);
H
hzcheng 已提交
2264

H
hjxilinx 已提交
2265 2266
  if (pTableMetaInfo->pTableMeta) {
    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pTableMeta), true);
H
hjxilinx 已提交
2267
//    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pMetricMeta), true);
H
hzcheng 已提交
2268 2269 2270 2271 2272 2273
  }

  return 0;
}

int tscProcessAlterTableMsgRsp(SSqlObj *pSql) {
2274
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
S
slguan 已提交
2275

H
hjxilinx 已提交
2276 2277
  STableMeta *pTableMeta = taosCacheAcquireByName(tscCacheHandle, pTableMetaInfo->name);
  if (pTableMeta == NULL) { /* not in cache, abort */
H
hzcheng 已提交
2278 2279 2280
    return 0;
  }

H
hjxilinx 已提交
2281 2282
  tscTrace("%p force release metermeta in cache after alter-table: %s", pSql, pTableMetaInfo->name);
  taosCacheRelease(tscCacheHandle, (void **)&pTableMeta, true);
H
hzcheng 已提交
2283

H
hjxilinx 已提交
2284
  if (pTableMetaInfo->pTableMeta) {
H
hjxilinx 已提交
2285
    bool isSuperTable = UTIL_TABLE_IS_SUPERTABLE(pTableMetaInfo);
H
hzcheng 已提交
2286

H
hjxilinx 已提交
2287
    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pTableMeta), true);
H
hjxilinx 已提交
2288
//    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pMetricMeta), true);
H
hzcheng 已提交
2289

2290
    if (isSuperTable) {  // if it is a super table, reset whole query cache
H
hjxilinx 已提交
2291
      tscTrace("%p reset query cache since table:%s is stable", pSql, pTableMetaInfo->name);
2292
      taosCacheEmpty(tscCacheHandle);
H
hzcheng 已提交
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306
    }
  }

  return 0;
}

int tscProcessAlterDbMsgRsp(SSqlObj *pSql) {
  UNUSED(pSql);
  return 0;
}

int tscProcessQueryRsp(SSqlObj *pSql) {
  SSqlRes *pRes = &pSql->res;

2307
  SQueryTableRsp *pQuery = (SQueryTableRsp *)pRes->pRsp;
S
slguan 已提交
2308 2309 2310
  pQuery->qhandle = htobe64(pQuery->qhandle);
  pRes->qhandle = pQuery->qhandle;

H
hzcheng 已提交
2311
  pRes->data = NULL;
S
slguan 已提交
2312
  tscResetForNextRetrieve(pRes);
H
hzcheng 已提交
2313 2314 2315 2316
  return 0;
}

int tscProcessRetrieveRspFromVnode(SSqlObj *pSql) {
S
slguan 已提交
2317 2318 2319
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;

S
slguan 已提交
2320
  SRetrieveTableRsp *pRetrieve = (SRetrieveTableRsp *)pRes->pRsp;
H
hzcheng 已提交
2321 2322 2323

  pRes->numOfRows = htonl(pRetrieve->numOfRows);
  pRes->precision = htons(pRetrieve->precision);
2324 2325
  pRes->offset    = htobe64(pRetrieve->offset);
  pRes->useconds  = htobe64(pRetrieve->useconds);
H
hjxilinx 已提交
2326
  pRes->completed = (pRetrieve->completed == 1);
2327
  pRes->data      = pRetrieve->data;
H
hjxilinx 已提交
2328
  
2329 2330
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  tscSetResultPointer(pQueryInfo, pRes);
2331

weixin_48148422's avatar
weixin_48148422 已提交
2332
  if (pSql->pSubscription != NULL) {
H
hjxilinx 已提交
2333 2334 2335 2336 2337
    int32_t numOfCols = pQueryInfo->fieldsInfo.numOfOutputCols;
    
    TAOS_FIELD *pField = tscFieldInfoGetField(pQueryInfo, numOfCols - 1);
    int16_t     offset = tscFieldInfoGetOffset(pQueryInfo, numOfCols - 1);
    
weixin_48148422's avatar
weixin_48148422 已提交
2338 2339
    char* p = pRes->data + (pField->bytes + offset) * pRes->numOfRows;

S
slguan 已提交
2340
    int32_t numOfTables = htonl(*(int32_t*)p);
weixin_48148422's avatar
weixin_48148422 已提交
2341
    p += sizeof(int32_t);
S
slguan 已提交
2342
    for (int i = 0; i < numOfTables; i++) {
weixin_48148422's avatar
weixin_48148422 已提交
2343 2344 2345 2346
      int64_t uid = htobe64(*(int64_t*)p);
      p += sizeof(int64_t);
      TSKEY key = htobe64(*(TSKEY*)p);
      p += sizeof(TSKEY);
2347
      tscUpdateSubscriptionProgress(pSql->pSubscription, uid, key);
weixin_48148422's avatar
weixin_48148422 已提交
2348
    }
2349 2350
  }

H
hzcheng 已提交
2351
  pRes->row = 0;
S
slguan 已提交
2352
  tscTrace("%p numOfRows:%d, offset:%d", pSql, pRes->numOfRows, pRes->offset);
H
hzcheng 已提交
2353 2354 2355 2356 2357

  return 0;
}

int tscProcessRetrieveRspFromLocal(SSqlObj *pSql) {
2358 2359
  SSqlRes *   pRes = &pSql->res;
  SSqlCmd *   pCmd = &pSql->cmd;
2360
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
2361

S
slguan 已提交
2362
  SRetrieveTableRsp *pRetrieve = (SRetrieveTableRsp *)pRes->pRsp;
H
hzcheng 已提交
2363 2364 2365

  pRes->numOfRows = htonl(pRetrieve->numOfRows);
  pRes->data = pRetrieve->data;
2366

2367
  tscSetResultPointer(pQueryInfo, pRes);
H
hzcheng 已提交
2368 2369 2370 2371
  pRes->row = 0;
  return 0;
}

H
hjxilinx 已提交
2372
void tscTableMetaCallBack(void *param, TAOS_RES *res, int code);
H
hzcheng 已提交
2373

2374
static int32_t getTableMetaFromMgmt(SSqlObj *pSql, STableMetaInfo *pTableMetaInfo) {
S
slguan 已提交
2375 2376
  SSqlObj *pNew = calloc(1, sizeof(SSqlObj));
  if (NULL == pNew) {
2377
    tscError("%p malloc failed for new sqlobj to get table meta", pSql);
S
slguan 已提交
2378 2379
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
2380

H
hzcheng 已提交
2381 2382 2383
  pNew->pTscObj = pSql->pTscObj;
  pNew->signature = pNew;
  pNew->cmd.command = TSDB_SQL_META;
S
slguan 已提交
2384

2385
  tscAddSubqueryInfo(&pNew->cmd);
2386 2387 2388 2389

  SQueryInfo *pNewQueryInfo = NULL;
  tscGetQueryInfoDetailSafely(&pNew->cmd, 0, &pNewQueryInfo);

H
hjxilinx 已提交
2390
  pNew->cmd.autoCreated = pSql->cmd.autoCreated;  // create table if not exists
S
slguan 已提交
2391
  if (TSDB_CODE_SUCCESS != tscAllocPayload(&pNew->cmd, TSDB_DEFAULT_PAYLOAD_SIZE)) {
2392
    tscError("%p malloc failed for payload to get table meta", pSql);
S
slguan 已提交
2393
    free(pNew);
2394

S
slguan 已提交
2395 2396 2397
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }

H
hjxilinx 已提交
2398
  STableMetaInfo *pNewMeterMetaInfo = tscAddEmptyMetaInfo(pNewQueryInfo);
2399
  assert(pNew->cmd.numOfClause == 1 && pNewQueryInfo->numOfTables == 1);
H
hzcheng 已提交
2400

2401
  strncpy(pNewMeterMetaInfo->name, pTableMetaInfo->name, tListLen(pNewMeterMetaInfo->name));
2402
  memcpy(pNew->cmd.payload, pSql->cmd.payload, TSDB_DEFAULT_PAYLOAD_SIZE);  // tag information if table does not exists.
S
slguan 已提交
2403
  tscTrace("%p new pSqlObj:%p to get tableMeta", pSql, pNew);
H
hzcheng 已提交
2404

H
hjxilinx 已提交
2405 2406
  pNew->fp = tscTableMetaCallBack;
  pNew->param = pSql;
H
hzcheng 已提交
2407

H
hjxilinx 已提交
2408 2409 2410
  int32_t code = tscProcessSql(pNew);
  if (code == TSDB_CODE_SUCCESS) {
    code = TSDB_CODE_ACTION_IN_PROGRESS;
H
hzcheng 已提交
2411 2412 2413 2414 2415
  }

  return code;
}

H
hjxilinx 已提交
2416
int32_t tscGetTableMeta(SSqlObj *pSql, STableMetaInfo *pTableMetaInfo) {
H
hjxilinx 已提交
2417
  assert(strlen(pTableMetaInfo->name) != 0);
S
slguan 已提交
2418

2419
  // If this STableMetaInfo owns a table meta, release it first
H
hjxilinx 已提交
2420 2421
  if (pTableMetaInfo->pTableMeta != NULL) {
    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pTableMeta), false);
2422 2423
  }
  
H
hjxilinx 已提交
2424 2425
  pTableMetaInfo->pTableMeta = (STableMeta *)taosCacheAcquireByName(tscCacheHandle, pTableMetaInfo->name);
  if (pTableMetaInfo->pTableMeta != NULL) {
H
hjxilinx 已提交
2426
    STableComInfo tinfo = tscGetTableInfo(pTableMetaInfo->pTableMeta);
2427 2428
    tscTrace("%p retrieve table Meta from cache, the number of columns:%d, numOfTags:%d, %p", pSql, tinfo.numOfColumns,
             tinfo.numOfTags, pTableMetaInfo->pTableMeta);
H
hzcheng 已提交
2429 2430 2431

    return TSDB_CODE_SUCCESS;
  }
2432 2433
  
  return getTableMetaFromMgmt(pSql, pTableMetaInfo);
H
hzcheng 已提交
2434 2435
}

H
hjxilinx 已提交
2436
int tscGetMeterMetaEx(SSqlObj *pSql, STableMetaInfo *pTableMetaInfo, bool createIfNotExists) {
H
hjxilinx 已提交
2437
  pSql->cmd.autoCreated = createIfNotExists;
H
hjxilinx 已提交
2438
  return tscGetTableMeta(pSql, pTableMetaInfo);
H
hzcheng 已提交
2439 2440 2441 2442
}

/*
 * in handling the renew metermeta problem during insertion,
S
slguan 已提交
2443
 *
H
hzcheng 已提交
2444 2445 2446 2447 2448
 * If the meter is created on demand during insertion, the routine usually waits for a short
 * period to re-issue the getMeterMeta msg, in which makes a greater change that vnode has
 * successfully created the corresponding table.
 */
static void tscWaitingForCreateTable(SSqlCmd *pCmd) {
S
slguan 已提交
2449
  if (pCmd->command == TSDB_SQL_INSERT) {
H
hzcheng 已提交
2450 2451 2452 2453 2454 2455 2456
    taosMsleep(50);  // todo: global config
  }
}

/**
 * in renew metermeta, do not retrieve metadata in cache.
 * @param pSql          sql object
S
slguan 已提交
2457
 * @param tableId       meter id
H
hzcheng 已提交
2458 2459
 * @return              status code
 */
S
slguan 已提交
2460
int tscRenewMeterMeta(SSqlObj *pSql, char *tableId) {
2461 2462
  int code = 0;

H
hjxilinx 已提交
2463
  // handle table meta renew process
H
hzcheng 已提交
2464
  SSqlCmd *pCmd = &pSql->cmd;
2465 2466

  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
hjxilinx 已提交
2467
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hzcheng 已提交
2468 2469

  /*
S
slguan 已提交
2470
   * 1. only update the metermeta in force model metricmeta is not updated
H
hzcheng 已提交
2471 2472
   * 2. if get metermeta failed, still get the metermeta
   */
H
hjxilinx 已提交
2473
  if (pTableMetaInfo->pTableMeta == NULL || !tscQueryOnMetric(pCmd)) {
2474
    STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;
H
hjxilinx 已提交
2475
    if (pTableMetaInfo->pTableMeta) {
2476 2477
      tscTrace("%p update table meta, old: numOfTags:%d, numOfCols:%d, uid:%" PRId64 ", addr:%p", pSql,
               tscGetNumOfTags(pTableMeta), tscGetNumOfColumns(pTableMeta), pTableMeta->uid, pTableMeta);
H
hzcheng 已提交
2478
    }
2479

2480
    tscWaitingForCreateTable(pCmd);
H
hjxilinx 已提交
2481
    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pTableMeta), true);
H
hzcheng 已提交
2482

2483
    code = getTableMetaFromMgmt(pSql, pTableMetaInfo);  // todo ??
H
hzcheng 已提交
2484
  } else {
H
hjxilinx 已提交
2485
    tscTrace("%p metric query not update metric meta, numOfTags:%d, numOfCols:%d, uid:%" PRId64 ", addr:%p", pSql,
H
hjxilinx 已提交
2486 2487
             tscGetNumOfTags(pTableMetaInfo->pTableMeta), pCmd->numOfCols, pTableMetaInfo->pTableMeta->uid,
             pTableMetaInfo->pTableMeta);
H
hzcheng 已提交
2488 2489 2490 2491 2492
  }

  return code;
}

H
hjxilinx 已提交
2493
int tscGetSTableVgroupInfo(SSqlObj *pSql, int32_t clauseIndex) {
S
slguan 已提交
2494 2495
  int      code = TSDB_CODE_NETWORK_UNAVAIL;
  SSqlCmd *pCmd = &pSql->cmd;
H
hzcheng 已提交
2496

H
hjxilinx 已提交
2497
  //the query condition is serialized into pCmd->payload, we need to rebuild key for stable meta info in cache.
2498
//  bool required = false;
2499

2500
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, clauseIndex);
2501
  if (pQueryInfo->pTableMetaInfo[0]->vgroupList != NULL) {
H
hjxilinx 已提交
2502 2503 2504 2505
    return TSDB_CODE_SUCCESS;
  }
  
#if 0
2506
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
S
slguan 已提交
2507 2508
    char tagstr[TSDB_MAX_TAGS_LEN + 1] = {0};

H
hjxilinx 已提交
2509
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, i);
H
hjxilinx 已提交
2510
    tscGetMetricMetaCacheKey(pQueryInfo, tagstr, pTableMetaInfo->pTableMeta->uid);
S
slguan 已提交
2511

H
hjxilinx 已提交
2512
//    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pMetricMeta), false);
S
slguan 已提交
2513

2514
    SSuperTableMeta *ppMeta = (SSuperTableMeta *)taosCacheAcquireByName(tscCacheHandle, tagstr);
S
slguan 已提交
2515
    if (ppMeta == NULL) {
2516
      required = true;
S
slguan 已提交
2517 2518
      break;
    } else {
H
hjxilinx 已提交
2519
//      pTableMetaInfo->pMetricMeta = ppMeta;
S
slguan 已提交
2520 2521
    }
  }
H
hzcheng 已提交
2522

2523 2524
  // all metricmeta for one clause are retrieved from cache, no need to retrieve metricmeta from management node
  if (!required) {
H
hzcheng 已提交
2525 2526
    return TSDB_CODE_SUCCESS;
  }
H
hjxilinx 已提交
2527 2528
#endif
  
S
slguan 已提交
2529
  SSqlObj *pNew = calloc(1, sizeof(SSqlObj));
H
hzcheng 已提交
2530 2531 2532
  pNew->pTscObj = pSql->pTscObj;
  pNew->signature = pNew;

H
hjxilinx 已提交
2533
  pNew->cmd.command = TSDB_SQL_STABLEVGROUP;
2534 2535
  
  SQueryInfo *pNewQueryInfo = NULL;
2536 2537 2538
  if ((code = tscGetQueryInfoDetailSafely(&pNew->cmd, 0, &pNewQueryInfo)) != TSDB_CODE_SUCCESS) {
    return code;
  }
2539
  
2540
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
H
hjxilinx 已提交
2541
    STableMetaInfo *pMMInfo = tscGetMetaInfo(pQueryInfo, i);
2542

H
hjxilinx 已提交
2543
    STableMeta *pTableMeta = taosCacheAcquireByName(tscCacheHandle, pMMInfo->name);
2544
    tscAddTableMetaInfo(pNewQueryInfo, pMMInfo->name, pTableMeta, NULL, pMMInfo->numOfTags, pMMInfo->tagColumnIndex);
S
slguan 已提交
2545 2546 2547 2548 2549 2550
  }

  if ((code = tscAllocPayload(&pNew->cmd, TSDB_DEFAULT_PAYLOAD_SIZE)) != TSDB_CODE_SUCCESS) {
    tscFreeSqlObj(pNew);
    return code;
  }
H
hzcheng 已提交
2551

2552
  tscTagCondCopy(&pNewQueryInfo->tagCond, &pQueryInfo->tagCond);
H
hzcheng 已提交
2553

2554 2555
  pNewQueryInfo->groupbyExpr = pQueryInfo->groupbyExpr;
  pNewQueryInfo->numOfTables = pQueryInfo->numOfTables;
H
hzcheng 已提交
2556

2557 2558
  pNewQueryInfo->slimit = pQueryInfo->slimit;
  pNewQueryInfo->order = pQueryInfo->order;
H
hjxilinx 已提交
2559 2560 2561 2562 2563
  
  STagCond* pTagCond = &pNewQueryInfo->tagCond;
  tscTrace("%p new sqlobj:%p info, numOfTables:%d, slimit:%" PRId64 ", soffset:%" PRId64 ", order:%d, tbname cond:%s",
      pSql, pNew, pNewQueryInfo->numOfTables, pNewQueryInfo->slimit.limit, pNewQueryInfo->slimit.offset,
      pNewQueryInfo->order.order, pTagCond->tbnameCond.cond)
H
hzcheng 已提交
2564

2565 2566 2567 2568
//  if (pSql->fp != NULL && pSql->pStream == NULL) {
//    pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
//    tscFreeSubqueryInfo(pCmd);
//  }
H
hzcheng 已提交
2569

H
hjxilinx 已提交
2570
  tscTrace("%p allocate new pSqlObj:%p to get stable vgroupInfo", pSql, pNew);
2571 2572 2573 2574 2575
  pNew->fp = tscTableMetaCallBack;
  pNew->param = pSql;
  code = tscProcessSql(pNew);
  if (code == TSDB_CODE_SUCCESS) {
    code = TSDB_CODE_ACTION_IN_PROGRESS;
H
hzcheng 已提交
2576 2577 2578 2579 2580
  }

  return code;
}

2581
void tscInitMsgsFp() {
S
slguan 已提交
2582 2583 2584
  tscBuildMsg[TSDB_SQL_SELECT] = tscBuildQueryMsg;
  tscBuildMsg[TSDB_SQL_INSERT] = tscBuildSubmitMsg;
  tscBuildMsg[TSDB_SQL_FETCH] = tscBuildRetrieveMsg;
H
hzcheng 已提交
2585 2586

  tscBuildMsg[TSDB_SQL_CREATE_DB] = tscBuildCreateDbMsg;
2587
  tscBuildMsg[TSDB_SQL_CREATE_USER] = tscBuildUserMsg;
H
hzcheng 已提交
2588

2589 2590
  tscBuildMsg[TSDB_SQL_CREATE_ACCT] = tscBuildAcctMsg;
  tscBuildMsg[TSDB_SQL_ALTER_ACCT] = tscBuildAcctMsg;
H
hzcheng 已提交
2591 2592

  tscBuildMsg[TSDB_SQL_CREATE_TABLE] = tscBuildCreateTableMsg;
S
[TD-16]  
slguan 已提交
2593
  tscBuildMsg[TSDB_SQL_DROP_USER] = tscBuildDropUserMsg;
H
hzcheng 已提交
2594 2595 2596
  tscBuildMsg[TSDB_SQL_DROP_ACCT] = tscBuildDropAcctMsg;
  tscBuildMsg[TSDB_SQL_DROP_DB] = tscBuildDropDbMsg;
  tscBuildMsg[TSDB_SQL_DROP_TABLE] = tscBuildDropTableMsg;
2597
  tscBuildMsg[TSDB_SQL_ALTER_USER] = tscBuildUserMsg;
S
slguan 已提交
2598 2599 2600
  tscBuildMsg[TSDB_SQL_CREATE_DNODE] = tscBuildCreateDnodeMsg;
  tscBuildMsg[TSDB_SQL_DROP_DNODE] = tscBuildDropDnodeMsg;
  tscBuildMsg[TSDB_SQL_CFG_DNODE] = tscBuildCfgDnodeMsg;
H
hzcheng 已提交
2601 2602 2603 2604 2605
  tscBuildMsg[TSDB_SQL_ALTER_TABLE] = tscBuildAlterTableMsg;
  tscBuildMsg[TSDB_SQL_ALTER_DB] = tscAlterDbMsg;

  tscBuildMsg[TSDB_SQL_CONNECT] = tscBuildConnectMsg;
  tscBuildMsg[TSDB_SQL_USE_DB] = tscBuildUseDbMsg;
H
hjxilinx 已提交
2606
  tscBuildMsg[TSDB_SQL_META] = tscBuildTableMetaMsg;
H
hjxilinx 已提交
2607
  tscBuildMsg[TSDB_SQL_STABLEVGROUP] = tscBuildSTableVgroupMsg;
S
slguan 已提交
2608
  tscBuildMsg[TSDB_SQL_MULTI_META] = tscBuildMultiMeterMetaMsg;
H
hzcheng 已提交
2609 2610 2611 2612

  tscBuildMsg[TSDB_SQL_HB] = tscBuildHeartBeatMsg;
  tscBuildMsg[TSDB_SQL_SHOW] = tscBuildShowMsg;
  tscBuildMsg[TSDB_SQL_RETRIEVE] = tscBuildRetrieveFromMgmtMsg;
2613 2614 2615
  tscBuildMsg[TSDB_SQL_KILL_QUERY] = tscBuildKillMsg;
  tscBuildMsg[TSDB_SQL_KILL_STREAM] = tscBuildKillMsg;
  tscBuildMsg[TSDB_SQL_KILL_CONNECTION] = tscBuildKillMsg;
H
hzcheng 已提交
2616 2617 2618 2619 2620 2621 2622 2623

  tscProcessMsgRsp[TSDB_SQL_SELECT] = tscProcessQueryRsp;
  tscProcessMsgRsp[TSDB_SQL_FETCH] = tscProcessRetrieveRspFromVnode;

  tscProcessMsgRsp[TSDB_SQL_DROP_DB] = tscProcessDropDbRsp;
  tscProcessMsgRsp[TSDB_SQL_DROP_TABLE] = tscProcessDropTableRsp;
  tscProcessMsgRsp[TSDB_SQL_CONNECT] = tscProcessConnectRsp;
  tscProcessMsgRsp[TSDB_SQL_USE_DB] = tscProcessUseDbRsp;
2624
  tscProcessMsgRsp[TSDB_SQL_META] = tscProcessTableMetaRsp;
H
hjxilinx 已提交
2625
  tscProcessMsgRsp[TSDB_SQL_STABLEVGROUP] = tscProcessSTableVgroupRsp;
S
slguan 已提交
2626
  tscProcessMsgRsp[TSDB_SQL_MULTI_META] = tscProcessMultiMeterMetaRsp;
H
hzcheng 已提交
2627 2628

  tscProcessMsgRsp[TSDB_SQL_SHOW] = tscProcessShowRsp;
2629
  tscProcessMsgRsp[TSDB_SQL_RETRIEVE] = tscProcessRetrieveRspFromVnode;  // rsp handled by same function.
H
hzcheng 已提交
2630
  tscProcessMsgRsp[TSDB_SQL_DESCRIBE_TABLE] = tscProcessDescribeTableRsp;
2631

H
hzcheng 已提交
2632
  tscProcessMsgRsp[TSDB_SQL_RETRIEVE_TAGS] = tscProcessTagRetrieveRsp;
H
hjxilinx 已提交
2633 2634 2635 2636 2637
  tscProcessMsgRsp[TSDB_SQL_CURRENT_DB] = tscProcessTagRetrieveRsp;
  tscProcessMsgRsp[TSDB_SQL_CURRENT_USER] = tscProcessTagRetrieveRsp;
  tscProcessMsgRsp[TSDB_SQL_SERV_VERSION] = tscProcessTagRetrieveRsp;
  tscProcessMsgRsp[TSDB_SQL_CLI_VERSION] = tscProcessTagRetrieveRsp;
  tscProcessMsgRsp[TSDB_SQL_SERV_STATUS] = tscProcessTagRetrieveRsp;
2638

H
hzcheng 已提交
2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651
  tscProcessMsgRsp[TSDB_SQL_RETRIEVE_EMPTY_RESULT] = tscProcessEmptyResultRsp;

  tscProcessMsgRsp[TSDB_SQL_RETRIEVE_METRIC] = tscProcessRetrieveMetricRsp;

  tscProcessMsgRsp[TSDB_SQL_ALTER_TABLE] = tscProcessAlterTableMsgRsp;
  tscProcessMsgRsp[TSDB_SQL_ALTER_DB] = tscProcessAlterDbMsgRsp;

  tscKeepConn[TSDB_SQL_SHOW] = 1;
  tscKeepConn[TSDB_SQL_RETRIEVE] = 1;
  tscKeepConn[TSDB_SQL_SELECT] = 1;
  tscKeepConn[TSDB_SQL_FETCH] = 1;
  tscKeepConn[TSDB_SQL_HB] = 1;
}