tscServer.c 86.7 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
#include "tscUtil.h"
#include "tschemautil.h"
#include "tsclient.h"
#include "tsocket.h"
#include "ttime.h"
#include "ttimer.h"
#include "tutil.h"
S
slguan 已提交
29
#include "tscLog.h"
H
hzcheng 已提交
30 31 32

#define TSC_MGMT_VNODE 999

S
slguan 已提交
33
SRpcIpSet  tscMgmtIpSet;
S
slguan 已提交
34 35
SRpcIpSet  tscDnodeIpSet;

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

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

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

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

48
static void tscSetDnodeIpList(SSqlObj* pSql, SCMVgroupInfo* pVgroupInfo) {
49 50
  SRpcIpSet* pIpList = &pSql->ipList;
  
51
  pIpList->numOfIps = pVgroupInfo->numOfIps;
52 53
  pIpList->inUse    = 0;
  
54 55 56
  for(int32_t i = 0; i < pVgroupInfo->numOfIps; ++i) {
    strcpy(pIpList->fqdn[i], pVgroupInfo->ipAddr[i].fqdn);
    pIpList->port[i] = pVgroupInfo->ipAddr[i].port;
57 58 59
  }
}

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

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

void tscSetMgmtIpListFromEdge() {
S
slguan 已提交
79 80 81
  if (tscMgmtIpSet.numOfIps != 1) {
    tscMgmtIpSet.numOfIps = 1;
    tscMgmtIpSet.inUse = 0;
H
hjxilinx 已提交
82
    taosGetFqdnPortFromEp(tsFirst, tscMgmtIpSet.fqdn[0], &tscMgmtIpSet.port[0]);
S
slguan 已提交
83 84 85 86 87
    tscTrace("edge mgmt IP list:");
    tscPrintMgmtIp();
  }
}

S
slguan 已提交
88
void tscUpdateIpSet(void *ahandle, SRpcIpSet *pIpSet) {
S
slguan 已提交
89
  tscMgmtIpSet = *pIpSet;
S
slguan 已提交
90 91 92 93
  tscTrace("mgmt IP list is changed for ufp is called, numOfIps:%d inUse:%d", tscMgmtIpSet.numOfIps, tscMgmtIpSet.inUse);
  for (int32_t i = 0; i < tscMgmtIpSet.numOfIps; ++i) {
    tscTrace("index:%d fqdn:%s port:%d", i, tscMgmtIpSet.fqdn[i], tscMgmtIpSet.port[i]);
  }
S
slguan 已提交
94 95
}

S
slguan 已提交
96
void tscSetMgmtIpList(SRpcIpSet *pIpList) {
S
slguan 已提交
97 98 99 100 101 102 103 104
  /*
    * 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 已提交
105 106 107
  }
}

H
hjxilinx 已提交
108 109 110 111 112 113 114
/*
 * 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.
 */
115
UNUSED_FUNC
H
hjxilinx 已提交
116 117
static int32_t tscGetMgmtConnMaxRetryTimes() {
  int32_t factor = 2;
S
slguan 已提交
118
  return tscMgmtIpSet.numOfIps * factor;
H
hjxilinx 已提交
119 120
}

H
hzcheng 已提交
121 122 123 124 125 126 127 128 129 130 131 132
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) {
133
    SCMHeartBeatRsp *pRsp = (SCMHeartBeatRsp *)pRes->pRsp;
S
slguan 已提交
134
    SRpcIpSet *      pIpList = &pRsp->ipList;
S
slguan 已提交
135
    tscSetMgmtIpList(pIpList);
S
slguan 已提交
136

H
hzcheng 已提交
137 138 139
    if (pRsp->killConnection) {
      tscKillConnection(pObj);
    } else {
S
slguan 已提交
140 141
      if (pRsp->queryId) tscKillQuery(pObj, htonl(pRsp->queryId));
      if (pRsp->streamId) tscKillStream(pObj, htonl(pRsp->streamId));
H
hzcheng 已提交
142 143
    }
  } else {
H
hjxilinx 已提交
144
    tscTrace("heart beat failed, code:%s", tstrerror(code));
H
hzcheng 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157
  }

  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 已提交
158 159 160
    SSqlObj *pSql = (SSqlObj *)calloc(1, sizeof(SSqlObj));
    if (NULL == pSql) return;

H
hzcheng 已提交
161
    pSql->fp = tscProcessHeartBeatRsp;
H
hjxilinx 已提交
162
    
163 164 165 166
    SQueryInfo *pQueryInfo = NULL;
    tscGetQueryInfoDetailSafely(&pSql->cmd, 0, &pQueryInfo);
    pQueryInfo->command = TSDB_SQL_HB;
    
167
    pSql->cmd.command = TSDB_SQL_HB;
S
slguan 已提交
168 169 170 171 172
    if (TSDB_CODE_SUCCESS != tscAllocPayload(&(pSql->cmd), TSDB_DEFAULT_PAYLOAD_SIZE)) {
      tfree(pSql);
      return;
    }

173
    pSql->cmd.command = TSDB_SQL_HB;
H
hzcheng 已提交
174 175 176 177
    pSql->param = pObj;
    pSql->pTscObj = pObj;
    pSql->signature = pSql;
    pObj->pHb = pSql;
178
    tscAddSubqueryInfo(&pObj->pHb->cmd);
179

S
slguan 已提交
180
    tscTrace("%p pHb is allocated, pObj:%p", pObj->pHb, pObj);
H
hzcheng 已提交
181 182 183
  }

  if (tscShouldFreeHeatBeat(pObj->pHb)) {
S
slguan 已提交
184
    tscTrace("%p free HB object and release connection", pObj);
H
hzcheng 已提交
185 186 187 188 189 190 191 192 193
    tscFreeSqlObj(pObj->pHb);
    tscCloseTscObj(pObj);
    return;
  }

  tscProcessSql(pObj->pHb);
}

int tscSendMsgToServer(SSqlObj *pSql) {
194
  STscObj* pObj = pSql->pTscObj;
H
hjxilinx 已提交
195 196 197
  SSqlCmd* pCmd = &pSql->cmd;
  
  char *pMsg = rpcMallocCont(pCmd->payloadLen);
S
slguan 已提交
198
  if (NULL == pMsg) {
S
slguan 已提交
199 200
    tscError("%p msg:%s malloc fail", pSql, taosMsg[pSql->cmd.msgType]);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
H
hzcheng 已提交
201 202
  }

S
slguan 已提交
203
  if (pSql->cmd.command < TSDB_SQL_MGMT) {
S
slguan 已提交
204
    memcpy(pMsg, pSql->cmd.payload + tsRpcHeadSize, pSql->cmd.payloadLen);
J
jtao1735 已提交
205 206 207 208 209
  } else {
    pSql->ipList = tscMgmtIpSet;
    memcpy(pMsg, pSql->cmd.payload, pSql->cmd.payloadLen);
  }

210
  tscTrace("%p msg:%s is sent to server", pSql, taosMsg[pSql->cmd.msgType]);
211

J
jtao1735 已提交
212
  SRpcMsg rpcMsg = {
213 214 215 216
      .msgType = pSql->cmd.msgType,
      .pCont   = pMsg,
      .contLen = pSql->cmd.payloadLen,
      .handle  = pSql,
H
hjxilinx 已提交
217
      .code    = 0
J
jtao1735 已提交
218
  };
219
  rpcSendRequest(pObj->pDnodeConn, &pSql->ipList, &rpcMsg);
H
hzcheng 已提交
220

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

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

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

  if (pSql->freed || pObj->signature != pObj) {
S
slguan 已提交
241 242
    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 已提交
243
    tscFreeSqlObj(pSql);
244
    rpcFreeCont(rpcMsg->pCont);
S
slguan 已提交
245
    return;
H
hzcheng 已提交
246 247
  }

J
jtao1735 已提交
248 249 250 251 252 253
  if (pCmd->command < TSDB_SQL_MGMT) {
    if (pIpSet) pSql->ipList = *pIpSet;
  } else {
    if (pIpSet) tscMgmtIpSet = *pIpSet;
  }

254 255
  if (rpcMsg->pCont == NULL) {
    rpcMsg->code = TSDB_CODE_NETWORK_UNAVAIL;
S
slguan 已提交
256
  } else {
257
    STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
258 259
    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 已提交
260
        rpcMsg->code == TSDB_CODE_NETWORK_UNAVAIL || rpcMsg->code == TSDB_CODE_NOT_ACTIVE_TABLE ||
261
        rpcMsg->code == TSDB_CODE_TABLE_ID_MISMATCH) {
S
slguan 已提交
262 263 264 265 266 267 268 269 270 271 272
      /*
       * 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) {
273 274
        rpcMsg->code = TSDB_CODE_NETWORK_UNAVAIL;
        rpcFreeCont(rpcMsg->pCont);
S
slguan 已提交
275 276
        return;
      } else if (pCmd->command == TSDB_SQL_HB) {
277 278
        rpcMsg->code = TSDB_CODE_NOT_READY;
        rpcFreeCont(rpcMsg->pCont);
S
slguan 已提交
279 280
        return;
      } else {
281
        tscWarn("%p it shall renew table meta, code:%s, retry:%d", pSql, tstrerror(rpcMsg->code), ++pSql->retry);
282
        
283
        pSql->res.code = rpcMsg->code;  // keep the previous error code
284 285 286 287 288 289 290 291
        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);
          }
  
292
          rpcFreeCont(rpcMsg->pCont);
S
slguan 已提交
293 294
          return;
        }
H
hzcheng 已提交
295 296
      }
    }
S
slguan 已提交
297
  }
298
  
H
hzcheng 已提交
299
  pRes->rspLen = 0;
300
  
H
hzcheng 已提交
301
  if (pRes->code != TSDB_CODE_QUERY_CANCELLED) {
302
    pRes->code = (rpcMsg->code != TSDB_CODE_SUCCESS) ? rpcMsg->code : TSDB_CODE_NETWORK_UNAVAIL;
H
hzcheng 已提交
303
  } else {
H
hjxilinx 已提交
304
    tscTrace("%p query is cancelled, code:%d", pSql, tstrerror(pRes->code));
H
hzcheng 已提交
305 306
  }

S
slguan 已提交
307 308 309 310 311
  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;
  }

S
slguan 已提交
312
  if (pRes->code != TSDB_CODE_QUERY_CANCELLED) {
313
    assert(rpcMsg->msgType == pCmd->msgType + 1);
314
    pRes->code    = rpcMsg->code;
315
    pRes->rspType = rpcMsg->msgType;
316
    pRes->rspLen  = rpcMsg->contLen;
H
hzcheng 已提交
317

318
    if (pRes->rspLen > 0 && rpcMsg->pCont) {
319 320 321 322 323
      char *tmp = (char *)realloc(pRes->pRsp, pRes->rspLen);
      if (tmp == NULL) {
        pRes->code = TSDB_CODE_CLI_OUT_OF_MEMORY;
      } else {
        pRes->pRsp = tmp;
324
        memcpy(pRes->pRsp, rpcMsg->pCont, pRes->rspLen);
S
slguan 已提交
325
      }
326 327
    } else {
      pRes->pRsp = NULL;
S
slguan 已提交
328 329
    }

H
hzcheng 已提交
330 331 332 333
    /*
     * There is not response callback function for submit response.
     * The actual inserted number of points is the first number.
     */
334
    if (rpcMsg->msgType == TSDB_MSG_TYPE_SUBMIT_RSP && pRes->pRsp != NULL) {
335
      SShellSubmitRspMsg *pMsg = (SShellSubmitRspMsg*)pRes->pRsp;
S
slguan 已提交
336 337 338 339 340 341 342
      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;
343
      tscTrace("%p cmd:%d code:%s, inserted rows:%d, rsp len:%d", pSql, pCmd->command, tstrerror(pRes->code),
H
hjxilinx 已提交
344
          pMsg->affectedRows, pRes->rspLen);
S
slguan 已提交
345
    } else {
H
hjxilinx 已提交
346
      tscTrace("%p cmd:%d code:%s rsp len:%d", pSql, pCmd->command, tstrerror(pRes->code), pRes->rspLen);
H
hzcheng 已提交
347 348
    }
  }
349
  
350 351
  if (pRes->code == TSDB_CODE_SUCCESS && tscProcessMsgRsp[pCmd->command])
    rpcMsg->code = (*tscProcessMsgRsp[pCmd->command])(pSql);
H
hjxilinx 已提交
352
  
353
  if (rpcMsg->code != TSDB_CODE_ACTION_IN_PROGRESS) {
354
    void *taosres = tscKeepConn[pCmd->command] ? pSql : NULL;
H
[td-32]  
hjxilinx 已提交
355
    rpcMsg->code = pRes->code ? pRes->code : pRes->numOfRows;
356
    
357
    tscTrace("%p SQL result:%s res:%p", pSql, tstrerror(pRes->code), pSql);
H
hzcheng 已提交
358

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

370
    if (shouldFree) {
371
      tscTrace("%p sqlObj is automatically freed", pSql);
sangshuduo's avatar
sangshuduo 已提交
372
      tscFreeSqlObj(pSql);
H
hzcheng 已提交
373 374 375
    }
  }

376
  rpcFreeCont(rpcMsg->pCont);
H
hzcheng 已提交
377 378
}

S
slguan 已提交
379 380 381
int doProcessSql(SSqlObj *pSql) {
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;
382 383
  int32_t code = TSDB_CODE_SUCCESS;
  
H
hjxilinx 已提交
384 385 386 387 388 389 390
  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 已提交
391
      pCmd->command == TSDB_SQL_STABLEVGROUP) {
392 393 394 395 396 397
    pRes->code = tscBuildMsg[pCmd->command](pSql, NULL);
  }
  
  if (pRes->code != TSDB_CODE_SUCCESS) {
    tscQueueAsyncRes(pSql);
    return pRes->code;
S
slguan 已提交
398
  }
399

400
  code = tscSendMsgToServer(pSql);
401
  if (code != TSDB_CODE_SUCCESS) {
S
slguan 已提交
402
    pRes->code = code;
H
hjxilinx 已提交
403
    tscQueueAsyncRes(pSql);
S
slguan 已提交
404
  }
H
hjxilinx 已提交
405 406
  
  return TSDB_CODE_SUCCESS;
S
slguan 已提交
407 408 409
}

int tscProcessSql(SSqlObj *pSql) {
410 411
  char *   name = NULL;
  SSqlCmd *pCmd = &pSql->cmd;
412 413
  
  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
414
  STableMetaInfo *pTableMetaInfo = NULL;
415
  uint16_t        type = 0;
416

417
  if (pQueryInfo != NULL) {
H
hjxilinx 已提交
418
    pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
419 420
    if (pTableMetaInfo != NULL) {
      name = pTableMetaInfo->name;
421
    }
422

423
    type = pQueryInfo->type;
424
  
H
hjxilinx 已提交
425
    // while numOfTables equals to 0, it must be Heartbeat
H
hjxilinx 已提交
426
    assert((pQueryInfo->numOfTables == 0 && pQueryInfo->command == TSDB_SQL_HB) || pQueryInfo->numOfTables > 0);
S
slguan 已提交
427
  }
428

429
  tscTrace("%p SQL cmd:%d will be processed, name:%s, type:%d", pSql, pCmd->command, name, type);
H
hjxilinx 已提交
430
  if (pCmd->command < TSDB_SQL_MGMT) { // the pTableMetaInfo cannot be NULL
H
hjxilinx 已提交
431
    if (pTableMetaInfo == NULL) {
H
hjxilinx 已提交
432 433 434
      pSql->res.code = TSDB_CODE_OTHERS;
      return pSql->res.code;
    }
H
hjxilinx 已提交
435 436
  } else if (pCmd->command < TSDB_SQL_LOCAL) {
    pSql->ipList = tscMgmtIpSet; //?
H
hzcheng 已提交
437 438 439
  } else {  // local handler
    return (*tscProcessMsgRsp[pCmd->command])(pSql);
  }
440
  
S
slguan 已提交
441 442
  return doProcessSql(pSql);
}
H
hzcheng 已提交
443

H
hjxilinx 已提交
444
void tscKillSTableQuery(SSqlObj *pSql) {
445 446 447
  SSqlCmd* pCmd = &pSql->cmd;
  
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
448
  if (!tscIsTwoStageSTableQuery(pQueryInfo, 0)) {
H
hzcheng 已提交
449 450 451 452 453 454
    return;
  }

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

S
slguan 已提交
455
    if (pSub == NULL) {
H
hzcheng 已提交
456 457
      continue;
    }
S
slguan 已提交
458

H
hzcheng 已提交
459 460 461 462 463
    /*
     * 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 已提交
464
    //taosStopRpcConn(pSql->pSubs[i]->thandle);
H
hzcheng 已提交
465 466 467 468 469 470 471 472 473 474 475
  }

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

H
hjxilinx 已提交
476
  while (pCmd->command != TSDB_SQL_RETRIEVE_LOCALMERGE && pCmd->command != TSDB_SQL_RETRIEVE_EMPTY_RESULT) {
H
hzcheng 已提交
477 478 479 480 481 482
    taosMsleep(100);
    if (taosGetTimestampMs() - stime > MAX_WAITING_TIME) {
      break;
    }
  }

H
hjxilinx 已提交
483
  tscTrace("%p super table query cancelled", pSql);
H
hzcheng 已提交
484 485
}

J
jtao1735 已提交
486
int tscBuildFetchMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
487 488 489 490 491
  char *pMsg, *pStart;

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

492
  SRetrieveTableMsg *pRetrieveMsg = (SRetrieveTableMsg *)pMsg;
S
slguan 已提交
493
  pRetrieveMsg->qhandle = htobe64(pSql->res.qhandle);
S
slguan 已提交
494 495
  pMsg += sizeof(pSql->res.qhandle);

496
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
S
slguan 已提交
497
  pRetrieveMsg->free = htons(pQueryInfo->type);
498
  pMsg += sizeof(pQueryInfo->type);
H
hzcheng 已提交
499

500
  // todo valid the vgroupId at the client side
H
hjxilinx 已提交
501 502 503 504
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
  
  if (UTIL_TABLE_IS_SUPERTABLE(pTableMetaInfo)) {
    int32_t vgIndex = pTableMetaInfo->vgroupIndex;
505
    
H
hjxilinx 已提交
506 507
    SVgroupsInfo* pVgroupInfo = pTableMetaInfo->vgroupList;
    pRetrieveMsg->header.vgId = htonl(pVgroupInfo->vgroups[vgIndex].vgId);
508
  } else {
H
hjxilinx 已提交
509
    STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;
H
hjxilinx 已提交
510
    pRetrieveMsg->header.vgId = htonl(pTableMeta->vgroupInfo.vgId);
511 512
  }
  
513 514 515 516
  pMsg += sizeof(SRetrieveTableMsg);
  
  pRetrieveMsg->header.contLen = htonl(pSql->cmd.payloadLen);
  
J
jtao1735 已提交
517
  pSql->cmd.msgType = TSDB_MSG_TYPE_FETCH;
518
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
519 520
}

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

H
hjxilinx 已提交
544
  // pSql->cmd.payloadLen is set during copying data into payload
S
slguan 已提交
545
  pSql->cmd.msgType = TSDB_MSG_TYPE_SUBMIT;
546
  tscSetDnodeIpList(pSql, &pTableMeta->vgroupInfo);
547
  
S
slguan 已提交
548
  tscTrace("%p build submit msg, vgId:%d numOfVgroup:%d numberOfIP:%d", pSql, vgId, htonl(pMsgDesc->numOfVnodes), pSql->ipList.numOfIps);
549
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
550 551 552
}

/*
553
 * for table query, simply return the size <= 1k
H
hzcheng 已提交
554
 */
555
static int32_t tscEstimateQueryMsgSize(SSqlCmd *pCmd, int32_t clauseIndex) {
H
hzcheng 已提交
556
  const static int32_t MIN_QUERY_MSG_PKT_SIZE = TSDB_MAX_BYTES_PER_ROW * 5;
557
  SQueryInfo *         pQueryInfo = tscGetQueryInfoDetail(pCmd, clauseIndex);
H
hzcheng 已提交
558

559
  int32_t srcColListSize = taosArrayGetSize(pQueryInfo->colList) * sizeof(SColumnInfo);
H
hjxilinx 已提交
560 561 562 563
  
  size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
  int32_t exprSize = sizeof(SSqlFuncMsg) * numOfExprs;
  
564
  return MIN_QUERY_MSG_PKT_SIZE + minMsgSize() + sizeof(SQueryTableMsg) + srcColListSize + exprSize + 4096;
H
hzcheng 已提交
565 566
}

567
static char *doSerializeTableInfo(SQueryTableMsg* pQueryMsg, SSqlObj *pSql, char *pMsg) {
568
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, pSql->cmd.clauseIndex, 0);
569

H
hjxilinx 已提交
570
  STableMeta * pTableMeta = pTableMetaInfo->pTableMeta;
571 572 573
  if (UTIL_TABLE_IS_NOMRAL_TABLE(pTableMetaInfo) || pTableMetaInfo->pVgroupTables == NULL) {
    
    SCMVgroupInfo* pVgroupInfo = NULL;
H
hjxilinx 已提交
574
    if (UTIL_TABLE_IS_SUPERTABLE(pTableMetaInfo)) {
575 576
      int32_t index = pTableMetaInfo->vgroupIndex;
      assert(index >= 0);
H
hjxilinx 已提交
577
  
578 579
      pVgroupInfo = &pTableMetaInfo->vgroupList->vgroups[index];
      tscTrace("%p query on stable, vgIndex:%d, numOfVgroups:%d", pSql, index, pTableMetaInfo->vgroupList->numOfVgroups);
H
hjxilinx 已提交
580 581
    } else {
      pVgroupInfo = &pTableMeta->vgroupInfo;
582 583 584 585 586 587 588 589 590
    }
    
    tscSetDnodeIpList(pSql, pVgroupInfo);
    pQueryMsg->head.vgId = htonl(pVgroupInfo->vgId);
    
    STableIdInfo *pTableIdInfo = (STableIdInfo *)pMsg;
    pTableIdInfo->tid = htonl(pTableMeta->sid);
    pTableIdInfo->uid = htobe64(pTableMeta->uid);
    pTableIdInfo->key = htobe64(tscGetSubscriptionProgress(pSql->pSubscription, pTableMeta->uid));
H
hjxilinx 已提交
591
  
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
    pQueryMsg->numOfTables = htonl(1);  // set the number of tables
    
    pMsg += sizeof(STableIdInfo);
  } else {
    int32_t index = pTableMetaInfo->vgroupIndex;
    int32_t numOfVgroups = taosArrayGetSize(pTableMetaInfo->pVgroupTables);
    assert(index >= 0 && index < numOfVgroups);
  
    tscTrace("%p query on stable, vgIndex:%d, numOfVgroups:%d", pSql, index, numOfVgroups);
    
    SVgroupTableInfo* pTableIdList = taosArrayGet(pTableMetaInfo->pVgroupTables, index);
    
    // set the vgroup info
    tscSetDnodeIpList(pSql, &pTableIdList->vgInfo);
    pQueryMsg->head.vgId = htonl(pTableIdList->vgInfo.vgId);
    
    int32_t numOfTables = taosArrayGetSize(pTableIdList->itemList);
    pQueryMsg->numOfTables = htonl(numOfTables);  // set the number of tables
  
    // serialize each table id info
    for(int32_t i = 0; i < numOfTables; ++i) {
      STableIdInfo* pItem = taosArrayGet(pTableIdList->itemList, i);
      
      STableIdInfo *pTableIdInfo = (STableIdInfo *)pMsg;
      pTableIdInfo->tid = htonl(pItem->tid);
      pTableIdInfo->uid = htobe64(pItem->uid);
//      pTableIdInfo->key = htobe64(tscGetSubscriptionProgress(pSql->pSubscription, pTableMeta->uid));
      pMsg += sizeof(STableIdInfo);
    }
  }
  
  tscTrace("%p vgId:%d, query on table:%s, uid:%" PRIu64, pSql, htonl(pQueryMsg->head.vgId), pTableMetaInfo->name,
      pTableMeta->uid);
H
hjxilinx 已提交
625
  
626 627 628
  return pMsg;
}

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

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

S
slguan 已提交
634 635 636 637
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
    tscError("%p failed to malloc for query msg", pSql);
    return -1;
  }
638
  
639
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
640
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
641
  STableMeta * pTableMeta = pTableMetaInfo->pTableMeta;
642
  
H
hjxilinx 已提交
643
  if (taosArrayGetSize(pQueryInfo->colList) <= 0 && !tscQueryTags(pQueryInfo)) {
644 645 646
    tscError("%p illegal value of numOfCols in query msg: %d", pSql, tscGetNumOfColumns(pTableMeta));
    return -1;
  }
647 648 649 650 651 652 653 654 655 656
  
  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;
  }
657 658

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

S
slguan 已提交
660
  SQueryTableMsg *pQueryMsg = (SQueryTableMsg *)pStart;
H
hzcheng 已提交
661

662
  int32_t numOfTags = taosArrayGetSize(pTableMetaInfo->tagColList);
663
  
664
  if (pQueryInfo->order.order == TSDB_ORDER_ASC) {
H
hjxilinx 已提交
665 666
    pQueryMsg->window.skey = htobe64(pQueryInfo->window.skey);
    pQueryMsg->window.ekey = htobe64(pQueryInfo->window.ekey);
H
hzcheng 已提交
667
  } else {
H
hjxilinx 已提交
668 669
    pQueryMsg->window.skey = htobe64(pQueryInfo->window.ekey);
    pQueryMsg->window.ekey = htobe64(pQueryInfo->window.skey);
H
hzcheng 已提交
670 671
  }

672 673 674 675 676
  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);
677
  pQueryMsg->numOfCols      = htons(taosArrayGetSize(pQueryInfo->colList));
678 679
  pQueryMsg->intervalTime   = htobe64(pQueryInfo->intervalTime);
  pQueryMsg->slidingTime    = htobe64(pQueryInfo->slidingTime);
H
hjxilinx 已提交
680
  pQueryMsg->slidingTimeUnit = pQueryInfo->slidingTimeUnit;
681
  pQueryMsg->numOfGroupCols = htons(pQueryInfo->groupbyExpr.numOfGroupCols);
682
  pQueryMsg->numOfTags      = htonl(numOfTags);
weixin_48148422's avatar
weixin_48148422 已提交
683
  pQueryMsg->tagNameRelType = htons(pQueryInfo->tagCond.relType);
684
  pQueryMsg->queryType      = htons(pQueryInfo->type);
H
hjxilinx 已提交
685 686 687
  
  size_t numOfOutput = tscSqlExprNumOfExprs(pQueryInfo);
  pQueryMsg->numOfOutput = htons(numOfOutput);
H
hjxilinx 已提交
688 689
  if (numOfOutput < 0) {
    tscError("%p illegal value of number of output columns in query msg: %d", pSql, numOfOutput);
H
hzcheng 已提交
690 691 692 693
    return -1;
  }

  // set column list ids
694 695
  size_t numOfCols = taosArrayGetSize(pQueryInfo->colList);
  char *pMsg = (char *)(pQueryMsg->colList) + numOfCols * sizeof(SColumnInfo);
H
hjxilinx 已提交
696
  SSchema *pSchema = tscGetTableSchema(pTableMeta);
697
  
698 699 700
  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumn *pCol = taosArrayGetP(pQueryInfo->colList, i);
    SSchema *pColSchema = &pSchema[pCol->colIndex.columnIndex];
H
hzcheng 已提交
701

702
    if (pCol->colIndex.columnIndex >= tscGetNumOfColumns(pTableMeta) || pColSchema->type < TSDB_DATA_TYPE_BOOL ||
703 704 705 706 707
        pColSchema->type > TSDB_DATA_TYPE_NCHAR) {
      tscError("%p sid:%d uid:%" PRIu64" id:%s, column index out of range, numOfColumns:%d, index:%d, column name:%s",
          pSql, pTableMeta->sid, pTableMeta->uid, pTableMetaInfo->name, tscGetNumOfColumns(pTableMeta), pCol->colIndex,
               pColSchema->name);

708
      return TSDB_CODE_INVALID_SQL;
709
    }
H
hzcheng 已提交
710 711 712

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

S
slguan 已提交
716 717 718
    // 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 已提交
719

S
slguan 已提交
720
      SColumnFilterInfo *pFilterMsg = (SColumnFilterInfo *)pMsg;
721
      pFilterMsg->filterstr = htons(pColFilter->filterstr);
S
slguan 已提交
722 723

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

725
      if (pColFilter->filterstr) {
S
slguan 已提交
726 727 728 729 730 731 732 733 734 735
        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 已提交
736

S
slguan 已提交
737 738 739 740 741
      if (pColFilter->lowerRelOptr == TSDB_RELATION_INVALID && pColFilter->upperRelOptr == TSDB_RELATION_INVALID) {
        tscError("invalid filter info");
        return -1;
      }
    }
H
hzcheng 已提交
742 743
  }

H
hjxilinx 已提交
744
  SSqlFuncMsg *pSqlFuncExpr = (SSqlFuncMsg *)pMsg;
H
hjxilinx 已提交
745
  for (int32_t i = 0; i < tscSqlExprNumOfExprs(pQueryInfo); ++i) {
746
    SSqlExpr *pExpr = tscSqlExprGet(pQueryInfo, i);
H
hzcheng 已提交
747

H
hjxilinx 已提交
748
    if (!tscValidateColumnId(pTableMetaInfo, pExpr->colInfo.colId)) {
749
      /* column id is not valid according to the cached table meta, the table meta is expired */
H
hzcheng 已提交
750 751 752 753
      tscError("%p table schema is not matched with parsed sql", pSql);
      return -1;
    }

754 755 756
    pSqlFuncExpr->colInfo.colId    = htons(pExpr->colInfo.colId);
    pSqlFuncExpr->colInfo.colIndex = htons(pExpr->colInfo.colIndex);
    pSqlFuncExpr->colInfo.flag     = htons(pExpr->colInfo.flag);
H
hzcheng 已提交
757

758
    pSqlFuncExpr->functionId  = htons(pExpr->functionId);
H
hzcheng 已提交
759
    pSqlFuncExpr->numOfParams = htons(pExpr->numOfParams);
H
hjxilinx 已提交
760
    pMsg += sizeof(SSqlFuncMsg);
H
hzcheng 已提交
761 762 763 764 765 766 767

    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);
768
        pMsg += pExpr->param[j].nLen;
H
hzcheng 已提交
769 770 771 772 773
      } else {
        pSqlFuncExpr->arg[j].argValue.i64 = htobe64(pExpr->param[j].i64Key);
      }
    }

H
hjxilinx 已提交
774
    pSqlFuncExpr = (SSqlFuncMsg *)pMsg;
H
hzcheng 已提交
775
  }
776
  
777
  // serialize the table info (sid, uid, tags)
778 779
  pMsg = doSerializeTableInfo(pQueryMsg, pSql, pMsg);
  
780
  SSqlGroupbyExpr *pGroupbyExpr = &pQueryInfo->groupbyExpr;
781
  if (pGroupbyExpr->numOfGroupCols > 0) {
S
slguan 已提交
782
    pQueryMsg->orderByIdx = htons(pGroupbyExpr->orderIndex);
H
hzcheng 已提交
783 784
    pQueryMsg->orderType = htons(pGroupbyExpr->orderType);

S
slguan 已提交
785
    for (int32_t j = 0; j < pGroupbyExpr->numOfGroupCols; ++j) {
786 787
      SColIndex* pCol = taosArrayGet(pGroupbyExpr->columnInfo, j);
  
S
slguan 已提交
788 789 790
      *((int16_t *)pMsg) = pCol->colId;
      pMsg += sizeof(pCol->colId);

791 792
      *((int16_t *)pMsg) += pCol->colIndex;
      pMsg += sizeof(pCol->colIndex);
S
slguan 已提交
793 794 795

      *((int16_t *)pMsg) += pCol->flag;
      pMsg += sizeof(pCol->flag);
H
hjxilinx 已提交
796 797 798
      
      memcpy(pMsg, pCol->name, tListLen(pCol->name));
      pMsg += tListLen(pCol->name);
S
slguan 已提交
799 800 801
    }
  }

802
  if (pQueryInfo->interpoType != TSDB_INTERPO_NONE) {
H
hjxilinx 已提交
803
    for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutput; ++i) {
804 805
      *((int64_t *)pMsg) = htobe64(pQueryInfo->defaultVal[i]);
      pMsg += sizeof(pQueryInfo->defaultVal[0]);
S
slguan 已提交
806 807
    }
  }
808 809 810 811 812 813 814 815 816
  
  if (numOfTags != 0) {
    int32_t numOfColumns = tscGetNumOfColumns(pTableMeta);
    int32_t numOfTagColumns = tscGetNumOfTags(pTableMeta);
    int32_t total = numOfTagColumns + numOfColumns;
    
    pSchema = tscGetTableTagSchema(pTableMeta);
    
    for (int32_t i = 0; i < numOfTags; ++i) {
H
hjxilinx 已提交
817
      SColumn *pCol = taosArrayGetP(pTableMetaInfo->tagColList, i);
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838
      SSchema *pColSchema = &pSchema[pCol->colIndex.columnIndex];

      if ((pCol->colIndex.columnIndex >= numOfTagColumns || pCol->colIndex.columnIndex < -1) ||
          (pColSchema->type < TSDB_DATA_TYPE_BOOL || pColSchema->type > TSDB_DATA_TYPE_NCHAR)) {
        tscError("%p sid:%d uid:%" PRIu64 " id:%s, tag index out of range, totalCols:%d, numOfTags:%d, index:%d, column name:%s",
                 pSql, pTableMeta->sid, pTableMeta->uid, pTableMetaInfo->name, total, numOfTagColumns,
                 pCol->colIndex, pColSchema->name);

        return TSDB_CODE_INVALID_SQL;
      }
  
      SColumnInfo* pTagCol = (SColumnInfo*) pMsg;
  
      pTagCol->colId = htons(pColSchema->colId);
      pTagCol->bytes = htons(pColSchema->bytes);
      pTagCol->type  = htons(pColSchema->type);
      pTagCol->numOfFilters = 0;
      
      pMsg += sizeof(SColumnInfo);
    }
  }
S
slguan 已提交
839 840 841 842 843 844

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

845
  if (pQueryInfo->tsBuf != NULL) {
H
hjxilinx 已提交
846
    STSVnodeBlockInfo *pBlockInfo = tsBufGetVnodeBlockInfo(pQueryInfo->tsBuf, pTableMetaInfo->vgroupIndex);
847
    assert(QUERY_IS_JOIN_QUERY(pQueryInfo->type) && pBlockInfo != NULL);  // this query should not be sent
S
slguan 已提交
848 849

    // todo refactor
850 851
    fseek(pQueryInfo->tsBuf->f, pBlockInfo->offset, SEEK_SET);
    fread(pMsg, pBlockInfo->compLen, 1, pQueryInfo->tsBuf->f);
S
slguan 已提交
852 853 854 855

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

S
slguan 已提交
858 859
  pQueryMsg->tsLen = htonl(tsLen);
  pQueryMsg->tsNumOfBlocks = htonl(numOfBlocks);
860 861
  if (pQueryInfo->tsBuf != NULL) {
    pQueryMsg->tsOrder = htonl(pQueryInfo->tsBuf->tsOrder);
H
hzcheng 已提交
862 863
  }

H
hjxilinx 已提交
864
  // serialize tag column query condition
865
  if (pQueryInfo->tagCond.pCond != NULL && taosArrayGetSize(pQueryInfo->tagCond.pCond) > 0) {
866 867
    STagCond* pTagCond = &pQueryInfo->tagCond;
    
868
    SCond *pCond = tsGetSTableQueryCond(pTagCond, pTableMeta->uid);
869
    if (pCond != NULL && pCond->cond != NULL) {
870 871
      pQueryMsg->tagCondLen = htons(pCond->len);
      memcpy(pMsg, pCond->cond, pCond->len);
872
      
873
      pMsg += pCond->len;
874 875 876
    }
  }
  
weixin_48148422's avatar
weixin_48148422 已提交
877 878 879 880 881 882 883 884
  if (pQueryInfo->tagCond.tbnameCond.cond == NULL) {
    *pMsg = 0;
    pMsg++;
  } else {
    strcpy(pMsg, pQueryInfo->tagCond.tbnameCond.cond);
    pMsg += strlen(pQueryInfo->tagCond.tbnameCond.cond) + 1;
  }

885
  int32_t msgLen = pMsg - pStart;
H
hzcheng 已提交
886 887 888

  tscTrace("%p msg built success,len:%d bytes", pSql, msgLen);
  pCmd->payloadLen = msgLen;
S
slguan 已提交
889
  pSql->cmd.msgType = TSDB_MSG_TYPE_QUERY;
H
hjxilinx 已提交
890
  
891
  pQueryMsg->head.contLen = htonl(msgLen);
H
hzcheng 已提交
892
  assert(msgLen + minMsgSize() <= size);
893 894

  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
895 896
}

897 898
int32_t tscBuildCreateDbMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
899
  pCmd->payloadLen = sizeof(SCMCreateDbMsg);
S
slguan 已提交
900
  pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_DB;
H
hzcheng 已提交
901

902
  SCMCreateDbMsg *pCreateDbMsg = (SCMCreateDbMsg*)pCmd->payload;
903

904
  assert(pCmd->numOfClause == 1);
905
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
906
  strncpy(pCreateDbMsg->db, pTableMetaInfo->name, tListLen(pCreateDbMsg->db));
H
hzcheng 已提交
907

908
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
909 910
}

911 912
int32_t tscBuildCreateDnodeMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
913
  pCmd->payloadLen = sizeof(SCMCreateDnodeMsg);
S
slguan 已提交
914 915 916 917
  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 已提交
918

919
  SCMCreateDnodeMsg *pCreate = (SCMCreateDnodeMsg *)pCmd->payload;
J
jtao1735 已提交
920 921
  strncpy(pCreate->ep, pInfo->pDCLInfo->a[0].z, pInfo->pDCLInfo->a[0].n);
  
S
slguan 已提交
922
  pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_DNODE;
H
hzcheng 已提交
923

924
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
925 926
}

927 928
int32_t tscBuildAcctMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
929
  pCmd->payloadLen = sizeof(SCMCreateAcctMsg);
S
slguan 已提交
930 931 932 933
  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 已提交
934

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

937 938
  SSQLToken *pName = &pInfo->pDCLInfo->user.user;
  SSQLToken *pPwd = &pInfo->pDCLInfo->user.passwd;
H
hzcheng 已提交
939

940 941
  strncpy(pAlterMsg->user, pName->z, pName->n);
  strncpy(pAlterMsg->pass, pPwd->z, pPwd->n);
S
slguan 已提交
942

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

945 946 947 948 949 950 951 952
  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 已提交
953

954 955 956 957 958 959 960 961 962 963 964 965 966
  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 已提交
967

S
slguan 已提交
968
  pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_ACCT;
969
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
970 971
}

972 973
int32_t tscBuildUserMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
974
  pCmd->payloadLen = sizeof(SCMCreateUserMsg);
S
slguan 已提交
975

S
slguan 已提交
976 977 978 979 980
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }

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

983 984 985
  SUserInfo *pUser = &pInfo->pDCLInfo->user;
  strncpy(pAlterMsg->user, pUser->user.z, pUser->user.n);
  pAlterMsg->flag = pUser->type;
H
hzcheng 已提交
986

987 988 989 990
  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 已提交
991 992
  } else { // create user password info
    strncpy(pAlterMsg->pass, pUser->passwd.z, pUser->passwd.n);
993
  }
H
hzcheng 已提交
994

995
  if (pUser->type == TSDB_ALTER_USER_PASSWD || pUser->type == TSDB_ALTER_USER_PRIVILEGES) {
S
slguan 已提交
996
    pCmd->msgType = TSDB_MSG_TYPE_CM_ALTER_USER;
997
  } else {
S
slguan 已提交
998
    pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_USER;
999
  }
H
hzcheng 已提交
1000

1001
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1002 1003
}

1004 1005
int32_t tscBuildCfgDnodeMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
S
slguan 已提交
1006
  pCmd->payloadLen = sizeof(SCMCfgDnodeMsg);
guanshengliang's avatar
guanshengliang 已提交
1007
  pCmd->msgType = TSDB_MSG_TYPE_CM_CONFIG_DNODE;
1008 1009
  return TSDB_CODE_SUCCESS;
}
S
slguan 已提交
1010

1011 1012
int32_t tscBuildDropDbMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
1013
  pCmd->payloadLen = sizeof(SCMDropDbMsg);
H
hzcheng 已提交
1014

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

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

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

S
slguan 已提交
1026
  pCmd->msgType = TSDB_MSG_TYPE_CM_DROP_DB;
1027
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1028 1029
}

1030 1031
int32_t tscBuildDropTableMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
1032
  pCmd->payloadLen = sizeof(SCMDropTableMsg);
H
hzcheng 已提交
1033

S
slguan 已提交
1034 1035 1036 1037
  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 已提交
1038

1039
  SCMDropTableMsg *pDropTableMsg = (SCMDropTableMsg*)pCmd->payload;
1040
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1041
  strcpy(pDropTableMsg->tableId, pTableMetaInfo->name);
S
slguan 已提交
1042
  pDropTableMsg->igNotExists = pInfo->pDCLInfo->existsCheck ? 1 : 0;
H
hzcheng 已提交
1043

S
slguan 已提交
1044
  pCmd->msgType = TSDB_MSG_TYPE_CM_DROP_TABLE;
1045
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1046 1047
}

1048
int32_t tscBuildDropDnodeMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
S
slguan 已提交
1049
  SSqlCmd *pCmd = &pSql->cmd;
1050
  pCmd->payloadLen = sizeof(SCMDropDnodeMsg);
S
slguan 已提交
1051 1052 1053 1054
  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 已提交
1055

1056
  SCMDropDnodeMsg *pDrop = (SCMDropDnodeMsg *)pCmd->payload;
1057
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
J
jtao1735 已提交
1058
  strcpy(pDrop->ep, pTableMetaInfo->name);
S
slguan 已提交
1059
  pCmd->msgType = TSDB_MSG_TYPE_CM_DROP_DNODE;
H
hzcheng 已提交
1060

1061
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1062 1063
}

S
[TD-16]  
slguan 已提交
1064
int32_t tscBuildDropUserMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
1065
  SSqlCmd *pCmd = &pSql->cmd;
1066
  pCmd->payloadLen = sizeof(SCMDropUserMsg);
S
slguan 已提交
1067
  pCmd->msgType = TSDB_MSG_TYPE_CM_DROP_USER;
H
hzcheng 已提交
1068

S
slguan 已提交
1069 1070 1071 1072
  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 已提交
1073

1074
  SCMDropUserMsg *pDropMsg = (SCMDropUserMsg*)pCmd->payload;
1075
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1076
  strcpy(pDropMsg->user, pTableMetaInfo->name);
H
hzcheng 已提交
1077

1078
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1079 1080
}

S
[TD-16]  
slguan 已提交
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
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;
}

1098 1099
int32_t tscBuildUseDbMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
1100
  pCmd->payloadLen = sizeof(SCMUseDbMsg);
H
hzcheng 已提交
1101

S
slguan 已提交
1102 1103 1104 1105
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
1106

1107
  SCMUseDbMsg *pUseDbMsg = (SCMUseDbMsg*)pCmd->payload;
1108
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1109
  strcpy(pUseDbMsg->db, pTableMetaInfo->name);
S
slguan 已提交
1110
  pCmd->msgType = TSDB_MSG_TYPE_CM_USE_DB;
H
hzcheng 已提交
1111

1112
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1113 1114
}

1115
int32_t tscBuildShowMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1116
  STscObj *pObj = pSql->pTscObj;
S
slguan 已提交
1117
  SSqlCmd *pCmd = &pSql->cmd;
S
slguan 已提交
1118
  pCmd->msgType = TSDB_MSG_TYPE_CM_SHOW;
1119
  pCmd->payloadLen = sizeof(SCMShowMsg) + 100;
H
hzcheng 已提交
1120

S
slguan 已提交
1121 1122 1123
  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 已提交
1124
  }
H
hzcheng 已提交
1125

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

1128
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1129
  size_t nameLen = strlen(pTableMetaInfo->name);
S
slguan 已提交
1130
  if (nameLen > 0) {
H
hjxilinx 已提交
1131
    strcpy(pShowMsg->db, pTableMetaInfo->name);  // prefix is set here
H
hzcheng 已提交
1132
  } else {
S
slguan 已提交
1133
    strcpy(pShowMsg->db, pObj->db);
H
hzcheng 已提交
1134 1135
  }

1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
  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 已提交
1148

1149 1150 1151 1152
    strncpy(pShowMsg->payload, pIpAddr->z, pIpAddr->n);
    pShowMsg->payloadLen = htons(pIpAddr->n);
  }

1153
  pCmd->payloadLen = sizeof(SCMShowMsg) + pShowMsg->payloadLen;
1154
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1155 1156
}

1157
int32_t tscBuildKillMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1158
  SSqlCmd *pCmd = &pSql->cmd;
1159
  pCmd->payloadLen = sizeof(SCMKillQueryMsg);
H
hzcheng 已提交
1160

S
slguan 已提交
1161 1162 1163 1164
  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 已提交
1165

1166
  SCMKillQueryMsg *pKill = (SCMKillQueryMsg*)pCmd->payload;
1167 1168 1169
  strncpy(pKill->queryId, pInfo->pDCLInfo->ip.z, pInfo->pDCLInfo->ip.n);
  switch (pCmd->command) {
    case TSDB_SQL_KILL_QUERY:
S
slguan 已提交
1170
      pCmd->msgType = TSDB_MSG_TYPE_CM_KILL_QUERY;
1171 1172
      break;
    case TSDB_SQL_KILL_CONNECTION:
S
slguan 已提交
1173
      pCmd->msgType = TSDB_MSG_TYPE_CM_KILL_CONN;
1174 1175
      break;
    case TSDB_SQL_KILL_STREAM:
S
slguan 已提交
1176
      pCmd->msgType = TSDB_MSG_TYPE_CM_KILL_STREAM;
1177 1178 1179
      break;
  }
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1180 1181
}

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

guanshengliang's avatar
guanshengliang 已提交
1185
  int32_t size = minMsgSize() + sizeof(SCMCreateTableMsg);
H
hzcheng 已提交
1186

1187
  SCreateTableSQL *pCreateTableInfo = pInfo->pCreateTableInfo;
1188
  if (pCreateTableInfo->type == TSQL_CREATE_TABLE_FROM_STABLE) {
H
hzcheng 已提交
1189 1190
    size += sizeof(STagData);
  } else {
S
slguan 已提交
1191
    size += sizeof(SSchema) * (pCmd->numOfCols + pCmd->count);
H
hzcheng 已提交
1192
  }
1193

1194 1195 1196
  if (pCreateTableInfo->pSelect != NULL) {
    size += (pCreateTableInfo->pSelect->selectToken.n + 1);
  }
H
hzcheng 已提交
1197 1198 1199 1200

  return size + TSDB_EXTRA_PAYLOAD_SIZE;
}

1201
int tscBuildCreateTableMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1202
  int              msgLen = 0;
S
slguan 已提交
1203
  SSchema *        pSchema;
H
hzcheng 已提交
1204
  int              size = 0;
1205 1206 1207
  SSqlCmd *pCmd = &pSql->cmd;

  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
hjxilinx 已提交
1208
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hzcheng 已提交
1209 1210

  // Reallocate the payload size
1211
  size = tscEstimateCreateTableMsgLength(pSql, pInfo);
S
slguan 已提交
1212 1213
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
    tscError("%p failed to malloc for create table msg", pSql);
1214
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
S
slguan 已提交
1215
  }
H
hzcheng 已提交
1216 1217


1218
  SCMCreateTableMsg *pCreateTableMsg = (SCMCreateTableMsg *)pCmd->payload;
H
hjxilinx 已提交
1219
  strcpy(pCreateTableMsg->tableId, pTableMetaInfo->name);
1220 1221

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

1224 1225 1226
  SCreateTableSQL *pCreateTable = pInfo->pCreateTableInfo;

  pCreateTableMsg->igExists = pCreateTable->existCheck ? 1 : 0;
H
hzcheng 已提交
1227 1228 1229 1230
  pCreateTableMsg->numOfColumns = htons(pCmd->numOfCols);
  pCreateTableMsg->numOfTags = htons(pCmd->count);

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

1233 1234 1235
  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 已提交
1236
    pMsg += sizeof(STagData);
1237
  } else {  // create (super) table
1238
    pSchema = (SSchema *)pCreateTableMsg->schema;
1239

H
hzcheng 已提交
1240
    for (int i = 0; i < pCmd->numOfCols + pCmd->count; ++i) {
H
hjxilinx 已提交
1241
      TAOS_FIELD *pField = tscFieldInfoGetField(&pQueryInfo->fieldsInfo, i);
H
hzcheng 已提交
1242 1243 1244 1245

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

H
hzcheng 已提交
1247 1248 1249 1250
      pSchema++;
    }

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

1254 1255 1256
      strncpy(pMsg, pQuerySql->selectToken.z, pQuerySql->selectToken.n + 1);
      pCreateTableMsg->sqlLen = htons(pQuerySql->selectToken.n + 1);
      pMsg += pQuerySql->selectToken.n + 1;
H
hzcheng 已提交
1257 1258 1259
    }
  }

H
hjxilinx 已提交
1260
  tscFieldInfoClear(&pQueryInfo->fieldsInfo);
H
hzcheng 已提交
1261

S
slguan 已提交
1262
  msgLen = pMsg - (char*)pCreateTableMsg;
S
slguan 已提交
1263
  pCreateTableMsg->contLen = htonl(msgLen);
H
hzcheng 已提交
1264
  pCmd->payloadLen = msgLen;
S
slguan 已提交
1265
  pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_TABLE;
H
hzcheng 已提交
1266 1267

  assert(msgLen + minMsgSize() <= size);
1268
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1269 1270 1271
}

int tscEstimateAlterTableMsgLength(SSqlCmd *pCmd) {
1272
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
guanshengliang's avatar
guanshengliang 已提交
1273
  return minMsgSize() + sizeof(SCMAlterTableMsg) + sizeof(SSchema) * tscNumOfFields(pQueryInfo) +
H
hzcheng 已提交
1274 1275 1276
         TSDB_EXTRA_PAYLOAD_SIZE;
}

1277
int tscBuildAlterTableMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
1278
  SCMAlterTableMsg *pAlterTableMsg;
1279
  char *          pMsg;
H
hzcheng 已提交
1280 1281 1282
  int             msgLen = 0;
  int             size = 0;

1283 1284 1285
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

H
hjxilinx 已提交
1286
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hzcheng 已提交
1287 1288

  size = tscEstimateAlterTableMsgLength(pCmd);
S
slguan 已提交
1289 1290 1291 1292
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
    tscError("%p failed to malloc for alter table msg", pSql);
    return -1;
  }
H
hzcheng 已提交
1293

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

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

1298 1299
  SAlterTableSQL *pAlterInfo = pInfo->pAlterInfo;

H
hjxilinx 已提交
1300
  strcpy(pAlterTableMsg->tableId, pTableMetaInfo->name);
1301
  pAlterTableMsg->type = htons(pAlterInfo->type);
1302

S
slguan 已提交
1303
  pAlterTableMsg->numOfCols = tscNumOfFields(pQueryInfo);
1304
  memcpy(pAlterTableMsg->tagVal, pAlterInfo->tagData.data, TSDB_MAX_TAGS_LEN);
H
hzcheng 已提交
1305

S
slguan 已提交
1306
  SSchema *pSchema = pAlterTableMsg->schema;
S
slguan 已提交
1307
  for (int i = 0; i < pAlterTableMsg->numOfCols; ++i) {
H
hjxilinx 已提交
1308
    TAOS_FIELD *pField = tscFieldInfoGetField(&pQueryInfo->fieldsInfo, i);
H
hzcheng 已提交
1309 1310 1311 1312 1313 1314 1315 1316 1317

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

  pMsg = (char *)pSchema;

S
slguan 已提交
1318
  msgLen = pMsg - (char*)pAlterTableMsg;
H
hzcheng 已提交
1319
  pCmd->payloadLen = msgLen;
S
slguan 已提交
1320
  pCmd->msgType = TSDB_MSG_TYPE_CM_ALTER_TABLE;
H
hzcheng 已提交
1321 1322

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

1324
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1325 1326
}

1327
int tscAlterDbMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
S
slguan 已提交
1328
  SSqlCmd *pCmd = &pSql->cmd;
1329
  pCmd->payloadLen = sizeof(SCMAlterDbMsg);
S
slguan 已提交
1330
  pCmd->msgType = TSDB_MSG_TYPE_CM_ALTER_DB;
H
hzcheng 已提交
1331

1332
  SCMAlterDbMsg *pAlterDbMsg = (SCMAlterDbMsg*)pCmd->payload;
1333
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1334
  strcpy(pAlterDbMsg->db, pTableMetaInfo->name);
H
hzcheng 已提交
1335

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

1339
int tscBuildRetrieveFromMgmtMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
S
slguan 已提交
1340
  SSqlCmd *pCmd = &pSql->cmd;
J
jtao1735 已提交
1341
  pCmd->msgType = TSDB_MSG_TYPE_CM_RETRIEVE;
S
slguan 已提交
1342
  pCmd->payloadLen = sizeof(SRetrieveTableMsg);
S
slguan 已提交
1343

S
slguan 已提交
1344 1345 1346
  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 已提交
1347
  }
S
slguan 已提交
1348

S
slguan 已提交
1349 1350 1351 1352
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
  SRetrieveTableMsg *pRetrieveMsg = (SRetrieveTableMsg*)pCmd->payload;
  pRetrieveMsg->qhandle = htobe64(pSql->res.qhandle);
  pRetrieveMsg->free = htons(pQueryInfo->type);
H
hzcheng 已提交
1353

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

1357
static int tscSetResultPointer(SQueryInfo *pQueryInfo, SSqlRes *pRes) {
1358
  if (tscCreateResPointerInfo(pRes, pQueryInfo) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
1359 1360 1361
    return pRes->code;
  }

H
hjxilinx 已提交
1362
  for (int i = 0; i < pQueryInfo->fieldsInfo.numOfOutput; ++i) {
H
hjxilinx 已提交
1363
    int16_t offset = tscFieldInfoGetOffset(pQueryInfo, i);
H
hjxilinx 已提交
1364
    pRes->tsrow[i] = ((char*) pRes->data + offset * pRes->numOfRows);
H
hzcheng 已提交
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
  }

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

1380
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
1381

H
hzcheng 已提交
1382 1383 1384 1385 1386 1387 1388
  pRes->code = TSDB_CODE_SUCCESS;

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

1389
    tscSetResultPointer(pQueryInfo, pRes);
H
hzcheng 已提交
1390
  } else {
S
slguan 已提交
1391
    tscResetForNextRetrieve(pRes);
H
hzcheng 已提交
1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
  }

  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 已提交
1407
  SSqlCmd *       pCmd = &pSql->cmd;
1408
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hzcheng 已提交
1409

H
hjxilinx 已提交
1410
  STableComInfo tinfo = tscGetTableInfo(pTableMetaInfo->pTableMeta);
H
hjxilinx 已提交
1411 1412
  
  int32_t numOfRes = tinfo.numOfColumns + tinfo.numOfTags;
H
hzcheng 已提交
1413 1414 1415 1416
  return tscLocalResultCommonBuilder(pSql, numOfRes);
}

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

1419 1420
//  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
//  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
S
slguan 已提交
1421 1422

  int32_t numOfRes = 0;
H
hjxilinx 已提交
1423
#if 0
1424
  if (tscSqlExprGet(pQueryInfo, 0)->functionId == TSDB_FUNC_TAGPRJ) {
H
hjxilinx 已提交
1425
    numOfRes = pTableMetaInfo->pMetricMeta->numOfTables;
H
hzcheng 已提交
1426 1427 1428
  } else {
    numOfRes = 1;  // for count function, there is only one output.
  }
H
hjxilinx 已提交
1429 1430 1431
  
#endif

H
hzcheng 已提交
1432 1433 1434
  return tscLocalResultCommonBuilder(pSql, numOfRes);
}

H
hjxilinx 已提交
1435
int tscProcessRetrieveLocalMergeRsp(SSqlObj *pSql) {
H
hzcheng 已提交
1436 1437 1438
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;

1439
  pRes->code = tscDoLocalMerge(pSql);
H
hjxilinx 已提交
1440
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hzcheng 已提交
1441 1442

  if (pRes->code == TSDB_CODE_SUCCESS && pRes->numOfRows > 0) {
1443
    tscSetResultPointer(pQueryInfo, pRes);
H
hzcheng 已提交
1444 1445 1446 1447
  }

  pRes->row = 0;

1448
  uint8_t code = pRes->code;
H
hjxilinx 已提交
1449 1450 1451 1452
  if (pRes->code == TSDB_CODE_SUCCESS) {
    (*pSql->fp)(pSql->param, pSql, pRes->numOfRows);
  } else {
    tscQueueAsyncRes(pSql);
H
hzcheng 已提交
1453 1454 1455 1456 1457
  }

  return code;
}

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

1460
int tscBuildConnectMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1461
  STscObj *pObj = pSql->pTscObj;
S
slguan 已提交
1462
  SSqlCmd *pCmd = &pSql->cmd;
S
slguan 已提交
1463
  pCmd->msgType = TSDB_MSG_TYPE_CM_CONNECT;
1464
  pCmd->payloadLen = sizeof(SCMConnectMsg);
H
hzcheng 已提交
1465

S
slguan 已提交
1466 1467 1468 1469 1470
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }

1471
  SCMConnectMsg *pConnect = (SCMConnectMsg*)pCmd->payload;
H
hzcheng 已提交
1472 1473 1474 1475 1476

  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 已提交
1477
  strcpy(pConnect->clientVersion, version);
S
slguan 已提交
1478
  strcpy(pConnect->msgVersion, "");
H
hzcheng 已提交
1479

1480
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1481 1482
}

H
hjxilinx 已提交
1483
int tscBuildTableMetaMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
1484
  SCMTableInfoMsg *pInfoMsg;
S
slguan 已提交
1485
  char *         pMsg;
H
hzcheng 已提交
1486 1487 1488 1489 1490
  int            msgLen = 0;

  char *tmpData = 0;
  if (pSql->cmd.allocSize > 0) {
    tmpData = calloc(1, pSql->cmd.allocSize);
1491 1492 1493 1494
    if (NULL == tmpData) {
      return TSDB_CODE_CLI_OUT_OF_MEMORY;
    }

H
hzcheng 已提交
1495 1496 1497 1498
    // STagData is in binary format, strncpy is not available
    memcpy(tmpData, pSql->cmd.payload, pSql->cmd.allocSize);
  }

1499 1500 1501
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);

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

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

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

H
hjxilinx 已提交
1510
  if (pSql->cmd.autoCreated) {
H
hzcheng 已提交
1511 1512 1513 1514
    memcpy(pInfoMsg->tags, tmpData, sizeof(STagData));
    pMsg += sizeof(STagData);
  }

H
hjxilinx 已提交
1515
  pCmd->payloadLen = pMsg - (char*)pInfoMsg;;
S
slguan 已提交
1516
  pCmd->msgType = TSDB_MSG_TYPE_CM_TABLE_META;
H
hzcheng 已提交
1517 1518 1519 1520

  tfree(tmpData);

  assert(msgLen + minMsgSize() <= pCmd->allocSize);
1521
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1522 1523
}

S
slguan 已提交
1524
/**
1525
 *  multi table meta req pkg format:
1526
 *  | SMgmtHead | SCMMultiTableInfoMsg | tableId0 | tableId1 | tableId2 | ......
S
slguan 已提交
1527 1528
 *      no used         4B
 **/
1529
int tscBuildMultiMeterMetaMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
guanshengliang's avatar
guanshengliang 已提交
1530
#if 0
S
slguan 已提交
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
  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 已提交
1543
  memset(pMgmt->db, 0, TSDB_TABLE_ID_LEN);  // server don't need the db
S
slguan 已提交
1544

1545
  SCMMultiTableInfoMsg *pInfoMsg = (SCMMultiTableInfoMsg *)(pCmd->payload + tsRpcHeadSize + sizeof(SMgmtHead));
S
slguan 已提交
1546
  pInfoMsg->numOfTables = htonl((int32_t)pCmd->count);
S
slguan 已提交
1547 1548

  if (pCmd->payloadLen > 0) {
S
slguan 已提交
1549
    memcpy(pInfoMsg->tableIds, tmpData, pCmd->payloadLen);
S
slguan 已提交
1550 1551 1552 1553
  }

  tfree(tmpData);

1554
  pCmd->payloadLen += sizeof(SMgmtHead) + sizeof(SCMMultiTableInfoMsg);
S
slguan 已提交
1555
  pCmd->msgType = TSDB_MSG_TYPE_CM_TABLES_META;
S
slguan 已提交
1556 1557 1558

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

S
slguan 已提交
1559
  tscTrace("%p build load multi-metermeta msg completed, numOfTables:%d, msg size:%d", pSql, pCmd->count,
S
slguan 已提交
1560 1561 1562
           pCmd->payloadLen);

  return pCmd->payloadLen;
guanshengliang's avatar
guanshengliang 已提交
1563 1564
#endif
  return 0;  
S
slguan 已提交
1565 1566
}

H
hjxilinx 已提交
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592
//static UNUSED_FUNC int32_t tscEstimateMetricMetaMsgSize(SSqlCmd *pCmd) {
////  const int32_t defaultSize =
////      minMsgSize() + sizeof(SSuperTableMetaMsg) + sizeof(SMgmtHead) + sizeof(int16_t) * TSDB_MAX_TAGS;
////  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
////
////  int32_t n = 0;
////  size_t size = taosArrayGetSize(pQueryInfo->tagCond.pCond);
////  for (int32_t i = 0; i < size; ++i) {
////    assert(0);
//////    n += strlen(pQueryInfo->tagCond.cond[i].cond);
////  }
////
////  int32_t tagLen = n * TSDB_NCHAR_SIZE;
////  if (pQueryInfo->tagCond.tbnameCond.cond != NULL) {
////    tagLen += strlen(pQueryInfo->tagCond.tbnameCond.cond) * TSDB_NCHAR_SIZE;
////  }
////
////  int32_t joinCondLen = (TSDB_TABLE_ID_LEN + sizeof(int16_t)) * 2;
////  int32_t elemSize = sizeof(SSuperTableMetaElemMsg) * pQueryInfo->numOfTables;
////
////  int32_t colSize = pQueryInfo->groupbyExpr.numOfGroupCols*sizeof(SColIndex);
////
////  int32_t len = tagLen + joinCondLen + elemSize + colSize + defaultSize;
////
////  return MAX(len, TSDB_DEFAULT_PAYLOAD_SIZE);
//}
H
hzcheng 已提交
1593

H
hjxilinx 已提交
1594 1595 1596
int tscBuildSTableVgroupMsg(SSqlObj *pSql, SSqlInfo *pInfo) {

#if 0
S
slguan 已提交
1597
  SSuperTableMetaMsg *pMetaMsg;
H
hzcheng 已提交
1598 1599
  char *          pMsg, *pStart;
  int             msgLen = 0;
S
slguan 已提交
1600
  int             tableIndex = 0;
H
hzcheng 已提交
1601

1602 1603 1604
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);

1605
  STagCond *pTagCond = &pQueryInfo->tagCond;
S
slguan 已提交
1606

H
hjxilinx 已提交
1607
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, tableIndex);
H
hzcheng 已提交
1608 1609

  int32_t size = tscEstimateMetricMetaMsgSize(pCmd);
S
slguan 已提交
1610 1611 1612 1613
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
    tscError("%p failed to malloc for metric meter msg", pSql);
    return -1;
  }
H
hzcheng 已提交
1614 1615 1616 1617 1618

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

  SMgmtHead *pMgmt = (SMgmtHead *)pMsg;
H
hjxilinx 已提交
1619
  tscGetDBInfoFromMeterId(pTableMetaInfo->name, pMgmt->db);
H
hzcheng 已提交
1620 1621 1622

  pMsg += sizeof(SMgmtHead);

S
slguan 已提交
1623
  pMetaMsg = (SSuperTableMetaMsg *)pMsg;
S
slguan 已提交
1624
  pMetaMsg->numOfTables = htonl(pQueryInfo->numOfTables);
S
slguan 已提交
1625

S
slguan 已提交
1626
  pMsg += sizeof(SSuperTableMetaMsg);
S
slguan 已提交
1627 1628 1629 1630 1631

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

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

S
slguan 已提交
1634
  memcpy(pMsg, pTagCond->joinInfo.left.tableId, TSDB_TABLE_ID_LEN);
S
slguan 已提交
1635
  pMsg += TSDB_TABLE_ID_LEN;
H
hzcheng 已提交
1636

S
slguan 已提交
1637 1638 1639
  *(int16_t *)pMsg = pTagCond->joinInfo.left.tagCol;
  pMsg += sizeof(int16_t);

S
slguan 已提交
1640
  memcpy(pMsg, pTagCond->joinInfo.right.tableId, TSDB_TABLE_ID_LEN);
S
slguan 已提交
1641
  pMsg += TSDB_TABLE_ID_LEN;
S
slguan 已提交
1642 1643 1644 1645

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

1646
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
1647
    pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, i);
H
hjxilinx 已提交
1648
    uint64_t uid = pTableMetaInfo->pTableMeta->uid;
S
slguan 已提交
1649 1650 1651 1652

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

S
slguan 已提交
1653 1654
    SSuperTableMetaElemMsg *pElem = (SSuperTableMetaElemMsg *)pMsg;
    pMsg += sizeof(SSuperTableMetaElemMsg);
S
slguan 已提交
1655 1656 1657 1658

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

H
hjxilinx 已提交
1663
        bool ret = taosMbsToUcs4(pCond->cond, condLen, pMsg, condLen * TSDB_NCHAR_SIZE);
S
slguan 已提交
1664
        if (!ret) {
1665
          tscError("%p mbs to ucs4 failed:%s", pSql, tsGetSTableQueryCond(pTagCond, uid));
S
slguan 已提交
1666 1667 1668
          return 0;
        }
      }
H
hzcheng 已提交
1669 1670
    }

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

S
slguan 已提交
1673 1674 1675
    offset = pMsg - (char *)pMetaMsg;
    pElem->cond = htonl(offset);
    pMsg += condLen * TSDB_NCHAR_SIZE;
H
hzcheng 已提交
1676

S
slguan 已提交
1677 1678 1679
    pElem->rel = htons(pTagCond->relType);
    if (pTagCond->tbnameCond.uid == uid) {
      offset = pMsg - (char *)pMetaMsg;
H
hzcheng 已提交
1680

S
slguan 已提交
1681
      pElem->tableCond = htonl(offset);
H
hjxilinx 已提交
1682 1683 1684 1685 1686 1687 1688
      
      uint32_t len = 0;
      if (pTagCond->tbnameCond.cond != NULL) {
        len = strlen(pTagCond->tbnameCond.cond);
        memcpy(pMsg, pTagCond->tbnameCond.cond, len);
      }
      
H
hjxilinx 已提交
1689 1690
      pElem->tableCondLen = htonl(len);
      pMsg += len;
S
slguan 已提交
1691 1692
    }

1693
    SSqlGroupbyExpr *pGroupby = &pQueryInfo->groupbyExpr;
S
slguan 已提交
1694

H
hjxilinx 已提交
1695
    if (pGroupby->tableIndex != i && pGroupby->numOfGroupCols > 0) {
S
slguan 已提交
1696 1697 1698 1699 1700
      pElem->orderType = 0;
      pElem->orderIndex = 0;
      pElem->numOfGroupCols = 0;
    } else {
      pElem->numOfGroupCols = htons(pGroupby->numOfGroupCols);
H
hjxilinx 已提交
1701 1702
      for (int32_t j = 0; j < pTableMetaInfo->numOfTags; ++j) {
        pElem->tagCols[j] = htons(pTableMetaInfo->tagColumnIndex[j]);
S
slguan 已提交
1703 1704 1705 1706 1707 1708 1709 1710
      }

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

        pElem->groupbyTagColumnList = htonl(offset);
1711
        for (int32_t j = 0; j < pQueryInfo->groupbyExpr.numOfGroupCols; ++j) {
1712 1713
          SColIndex *pCol = &pQueryInfo->groupbyExpr.columnInfo[j];
          SColIndex *pDestCol = (SColIndex *)pMsg;
1714

H
hjxilinx 已提交
1715
          pDestCol->colIdxInBuf = 0;
1716
          pDestCol->colIndex = htons(pCol->colIndex);
H
hjxilinx 已提交
1717 1718
          pDestCol->colId = htons(pDestCol->colId);
          pDestCol->flag = htons(pDestCol->flag);
H
hjxilinx 已提交
1719
          strncpy(pDestCol->name, pCol->name, tListLen(pCol->name));
1720

1721
          pMsg += sizeof(SColIndex);
S
slguan 已提交
1722 1723
        }
      }
H
hzcheng 已提交
1724
    }
S
slguan 已提交
1725

H
hjxilinx 已提交
1726 1727
    strcpy(pElem->tableId, pTableMetaInfo->name);
    pElem->numOfTags = htons(pTableMetaInfo->numOfTags);
S
slguan 已提交
1728 1729 1730

    int16_t len = pMsg - (char *)pElem;
    pElem->elemLen = htons(len);  // redundant data for integrate check
H
hzcheng 已提交
1731 1732 1733 1734
  }

  msgLen = pMsg - pStart;
  pCmd->payloadLen = msgLen;
S
slguan 已提交
1735
  pCmd->msgType = TSDB_MSG_TYPE_CM_STABLE_VGROUP;
H
hzcheng 已提交
1736
  assert(msgLen + minMsgSize() <= size);
H
hjxilinx 已提交
1737
#endif
1738
  
H
hjxilinx 已提交
1739
  SSqlCmd *pCmd = &pSql->cmd;
H
hjxilinx 已提交
1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
  
  char* pMsg = pCmd->payload;
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
  
  SCMSTableVgroupMsg *pStableVgroupMsg = (SCMSTableVgroupMsg *) pMsg;
  pStableVgroupMsg->numOfTables = htonl(pQueryInfo->numOfTables);
  pMsg += sizeof(SCMSTableVgroupMsg);
  
  for(int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
    STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, i);
    strncpy(pMsg, pTableMetaInfo->name, TSDB_TABLE_ID_LEN);
    pMsg += TSDB_TABLE_ID_LEN;
  }
H
hjxilinx 已提交
1753 1754

  pCmd->msgType = TSDB_MSG_TYPE_CM_STABLE_VGROUP;
H
hjxilinx 已提交
1755
  pCmd->payloadLen = (pMsg - pCmd->payload);
H
hjxilinx 已提交
1756

1757
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1758 1759
}

1760
int tscEstimateHeartBeatMsgLength(SSqlObj *pSql) {
H
hzcheng 已提交
1761 1762 1763
  int      size = 0;
  STscObj *pObj = pSql->pTscObj;

guanshengliang's avatar
guanshengliang 已提交
1764
  size += tsRpcHeadSize;
S
slguan 已提交
1765
  size += sizeof(SQqueryList);
H
hzcheng 已提交
1766 1767 1768

  SSqlObj *tpSql = pObj->sqlList;
  while (tpSql) {
S
slguan 已提交
1769
    size += sizeof(SQueryDesc);
H
hzcheng 已提交
1770 1771 1772
    tpSql = tpSql->next;
  }

S
slguan 已提交
1773
  size += sizeof(SStreamList);
H
hzcheng 已提交
1774 1775
  SSqlStream *pStream = pObj->streamList;
  while (pStream) {
S
slguan 已提交
1776
    size += sizeof(SStreamDesc);
H
hzcheng 已提交
1777 1778 1779 1780 1781 1782
    pStream = pStream->next;
  }

  return size + TSDB_EXTRA_PAYLOAD_SIZE;
}

1783
int tscBuildHeartBeatMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1784 1785 1786 1787 1788 1789 1790 1791 1792
  char *pMsg, *pStart;
  int   msgLen = 0;
  int   size = 0;

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

  pthread_mutex_lock(&pObj->mutex);

1793
  size = tscEstimateHeartBeatMsgLength(pSql);
S
slguan 已提交
1794
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
1795
    pthread_mutex_unlock(&pObj->mutex);
S
slguan 已提交
1796 1797 1798
    tscError("%p failed to malloc for heartbeat msg", pSql);
    return -1;
  }
H
hzcheng 已提交
1799

guanshengliang's avatar
guanshengliang 已提交
1800
  pMsg = pCmd->payload;
H
hzcheng 已提交
1801 1802 1803 1804 1805 1806 1807
  pStart = pMsg;

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

  msgLen = pMsg - pStart;
  pCmd->payloadLen = msgLen;
S
slguan 已提交
1808
  pCmd->msgType = TSDB_MSG_TYPE_CM_HEARTBEAT;
H
hzcheng 已提交
1809 1810

  assert(msgLen + minMsgSize() <= size);
1811
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1812 1813
}

1814 1815
int tscProcessTableMetaRsp(SSqlObj *pSql) {
  STableMetaMsg *pMetaMsg = (STableMetaMsg *)pSql->res.pRsp;
H
hzcheng 已提交
1816

1817 1818
  pMetaMsg->sid = htonl(pMetaMsg->sid);
  pMetaMsg->sversion = htons(pMetaMsg->sversion);
H
hjxilinx 已提交
1819 1820 1821
  
  pMetaMsg->vgroup.vgId = htonl(pMetaMsg->vgroup.vgId);
  
1822 1823
  pMetaMsg->uid = htobe64(pMetaMsg->uid);
  pMetaMsg->contLen = htons(pMetaMsg->contLen);
1824
  pMetaMsg->numOfColumns = htons(pMetaMsg->numOfColumns);
H
hzcheng 已提交
1825

H
hjxilinx 已提交
1826 1827
  if (pMetaMsg->sid < 0 || pMetaMsg->vgroup.numOfIps < 0) {
    tscError("invalid meter vgId:%d, sid%d", pMetaMsg->vgroup.numOfIps, pMetaMsg->sid);
H
hzcheng 已提交
1828 1829 1830
    return TSDB_CODE_INVALID_VALUE;
  }

1831 1832
  if (pMetaMsg->numOfTags > TSDB_MAX_TAGS || pMetaMsg->numOfTags < 0) {
    tscError("invalid numOfTags:%d", pMetaMsg->numOfTags);
H
hzcheng 已提交
1833 1834 1835
    return TSDB_CODE_INVALID_VALUE;
  }

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

H
hjxilinx 已提交
1841 1842
  for (int i = 0; i < pMetaMsg->vgroup.numOfIps; ++i) {
    pMetaMsg->vgroup.ipAddr[i].port = htons(pMetaMsg->vgroup.ipAddr[i].port);
H
hzcheng 已提交
1843 1844
  }

1845
  SSchema* pSchema = pMetaMsg->schema;
H
hzcheng 已提交
1846

1847
  int32_t numOfTotalCols = pMetaMsg->numOfColumns + pMetaMsg->numOfTags;
H
hzcheng 已提交
1848 1849 1850
  for (int i = 0; i < numOfTotalCols; ++i) {
    pSchema->bytes = htons(pSchema->bytes);
    pSchema->colId = htons(pSchema->colId);
H
hjxilinx 已提交
1851 1852
    
    assert(pSchema->type >= TSDB_DATA_TYPE_BOOL && pSchema->type <= TSDB_DATA_TYPE_NCHAR);
H
hzcheng 已提交
1853 1854 1855
    pSchema++;
  }

1856 1857
  size_t size = 0;
  STableMeta* pTableMeta = tscCreateTableMetaFromMsg(pMetaMsg, &size);
H
hzcheng 已提交
1858

1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869
#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 已提交
1870
  // todo add one more function: taosAddDataIfNotExists();
1871
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
H
hjxilinx 已提交
1872
  assert(pTableMetaInfo->pTableMeta == NULL);
H
hzcheng 已提交
1873

H
hjxilinx 已提交
1874
  pTableMetaInfo->pTableMeta =
H
hjxilinx 已提交
1875
      (STableMeta *) taosCachePut(tscCacheHandle, pTableMetaInfo->name, pTableMeta, size, tsTableMetaKeepTimer);
H
hjxilinx 已提交
1876
  
1877
  // todo handle out of memory case
1878
  if (pTableMetaInfo->pTableMeta == NULL) {
H
hjxilinx 已提交
1879
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
1880
  }
H
hzcheng 已提交
1881

1882
  free(pTableMeta);
1883
  
H
hjxilinx 已提交
1884
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1885 1886
}

S
slguan 已提交
1887
/**
1888
 *  multi table meta rsp pkg format:
1889
 *  | STaosRsp | ieType | SCMMultiTableInfoMsg | SMeterMeta0 | SSchema0 | SMeterMeta1 | SSchema1 | SMeterMeta2 | SSchema2
S
slguan 已提交
1890 1891 1892
 *  |...... 1B        1B            4B
 **/
int tscProcessMultiMeterMetaRsp(SSqlObj *pSql) {
1893
#if 0
S
slguan 已提交
1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
  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++;

1906
  SCMMultiTableInfoMsg *pInfo = (SCMMultiTableInfoMsg *)rsp;
S
slguan 已提交
1907
  totalNum = htonl(pInfo->numOfTables);
1908
  rsp += sizeof(SCMMultiTableInfoMsg);
S
slguan 已提交
1909 1910

  for (i = 0; i < totalNum; i++) {
S
slguan 已提交
1911
    SMultiTableMeta *pMultiMeta = (SMultiTableMeta *)rsp;
1912
    STableMeta *     pMeta = pMultiMeta->metas;
S
slguan 已提交
1913 1914 1915

    pMeta->sid = htonl(pMeta->sid);
    pMeta->sversion = htons(pMeta->sversion);
H
hjxilinx 已提交
1916
    pMeta->vgId = htonl(pMeta->vgId);
S
slguan 已提交
1917 1918
    pMeta->uid = htobe64(pMeta->uid);

H
hjxilinx 已提交
1919 1920
    if (pMeta->sid <= 0 || pMeta->vgId < 0) {
      tscError("invalid meter vgId:%d, sid%d", pMeta->vgId, pMeta->sid);
S
slguan 已提交
1921 1922 1923 1924 1925
      pSql->res.code = TSDB_CODE_INVALID_VALUE;
      pSql->res.numOfTotal = i;
      return TSDB_CODE_OTHERS;
    }

H
hjxilinx 已提交
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
    //    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;
    //    }
    //
H
hjxilinx 已提交
1949
    //    for (int j = 0; j < TSDB_REPLICA_MAX_NUM; ++j) {
H
hjxilinx 已提交
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
    //      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;
H
hjxilinx 已提交
1984
    //    (void)taosCachePut(tscCacheHandle, pMeta->tableId, (char *)pMeta, size, tsTableMetaKeepTimer);
H
hjxilinx 已提交
1985
    //  }
S
slguan 已提交
1986
  }
H
hjxilinx 已提交
1987
  
S
slguan 已提交
1988 1989 1990
  pSql->res.code = TSDB_CODE_SUCCESS;
  pSql->res.numOfTotal = i;
  tscTrace("%p load multi-metermeta resp complete num:%d", pSql, pSql->res.numOfTotal);
1991 1992
#endif
  
S
slguan 已提交
1993 1994 1995
  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
1996 1997
int tscProcessSTableVgroupRsp(SSqlObj *pSql) {
#if 0
S
slguan 已提交
1998 1999
  void **      metricMetaList = NULL;
  int32_t *    sizes = NULL;
H
hjxilinx 已提交
2000
  
S
slguan 已提交
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
  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 已提交
2017
    pMeta = (SSuperTableMeta *)rsp;
S
slguan 已提交
2018 2019

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

S
slguan 已提交
2022
    pMeta->numOfTables = htonl(pMeta->numOfTables);
S
slguan 已提交
2023 2024 2025
    pMeta->numOfVnodes = htonl(pMeta->numOfVnodes);
    pMeta->tagLen = htons(pMeta->tagLen);

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

2028 2029
    char *pBuf = calloc(1, size);
    if (pBuf == NULL) {
S
slguan 已提交
2030 2031 2032
      pSql->res.code = TSDB_CODE_CLI_OUT_OF_MEMORY;
      goto _error_clean;
    }
H
hzcheng 已提交
2033

S
slguan 已提交
2034
    SSuperTableMeta *pNewMetricMeta = (SSuperTableMeta *)pBuf;
S
slguan 已提交
2035
    metricMetaList[k] = pNewMetricMeta;
H
hzcheng 已提交
2036

S
slguan 已提交
2037
    pNewMetricMeta->numOfTables = pMeta->numOfTables;
S
slguan 已提交
2038 2039
    pNewMetricMeta->numOfVnodes = pMeta->numOfVnodes;
    pNewMetricMeta->tagLen = pMeta->tagLen;
H
hzcheng 已提交
2040

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

S
slguan 已提交
2043 2044
    for (int32_t i = 0; i < pMeta->numOfVnodes; ++i) {
      SVnodeSidList *pSidLists = (SVnodeSidList *)rsp;
2045
      memcpy(pBuf, pSidLists, sizeof(SVnodeSidList));
H
hzcheng 已提交
2046

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

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

2052
      pBuf += sizeof(SVnodeSidList) + sizeof(STableIdInfo *) * pSidLists->numOfSids;
S
slguan 已提交
2053
      rsp += sizeof(SVnodeSidList);
H
hzcheng 已提交
2054

2055
      size_t elemSize = sizeof(STableIdInfo) + pNewMetricMeta->tagLen;
S
slguan 已提交
2056
      for (int32_t j = 0; j < pSidLists->numOfSids; ++j) {
2057 2058
        pLists->pSidExtInfoList[j] = pBuf - (char *)pLists;
        memcpy(pBuf, rsp, elemSize);
2059

2060 2061
        ((STableIdInfo *)pBuf)->uid = htobe64(((STableIdInfo *)pBuf)->uid);
        ((STableIdInfo *)pBuf)->sid = htonl(((STableIdInfo *)pBuf)->sid);
2062

2063 2064
        rsp += elemSize;
        pBuf += elemSize;
S
slguan 已提交
2065
      }
H
hzcheng 已提交
2066
    }
S
slguan 已提交
2067

2068
    sizes[k] = pBuf - (char *)pNewMetricMeta;
H
hzcheng 已提交
2069 2070
  }

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

H
hjxilinx 已提交
2075
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, i);
H
hjxilinx 已提交
2076
    tscGetMetricMetaCacheKey(pQueryInfo, name, pTableMetaInfo->pTableMeta->uid);
H
hzcheng 已提交
2077

S
slguan 已提交
2078 2079 2080
#ifdef _DEBUG_VIEW
    printf("generate the metric key:%s, index:%d\n", name, i);
#endif
H
hzcheng 已提交
2081

S
slguan 已提交
2082
    // release the used metricmeta
H
hjxilinx 已提交
2083 2084
    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pMetricMeta), false);
    pTableMetaInfo->pMetricMeta = (SSuperTableMeta *)taosCachePut(tscCacheHandle, name, (char *)metricMetaList[i],
S
slguan 已提交
2085 2086 2087 2088
                                                                      sizes[i], tsMetricMetaKeepTimer);
    tfree(metricMetaList[i]);

    // failed to put into cache
H
hjxilinx 已提交
2089
    if (pTableMetaInfo->pMetricMeta == NULL) {
S
slguan 已提交
2090 2091 2092
      pSql->res.code = TSDB_CODE_CLI_OUT_OF_MEMORY;
      goto _error_clean;
    }
H
hzcheng 已提交
2093 2094
  }

S
slguan 已提交
2095 2096 2097 2098 2099 2100 2101 2102
_error_clean:
  // free allocated resource
  for (int32_t i = 0; i < num; ++i) {
    tfree(metricMetaList[i]);
  }

  free(sizes);
  free(metricMetaList);
H
hjxilinx 已提交
2103
#endif
2104
  SSqlRes* pRes = &pSql->res;
H
hjxilinx 已提交
2105
  
H
hjxilinx 已提交
2106
  // NOTE: the order of several table must be preserved.
2107
  SCMSTableVgroupRspMsg *pStableVgroup = (SCMSTableVgroupRspMsg *)pRes->pRsp;
H
hjxilinx 已提交
2108 2109
  pStableVgroup->numOfTables = htonl(pStableVgroup->numOfTables);
  char* pMsg = pRes->pRsp + sizeof(SCMSTableVgroupRspMsg);
H
hjxilinx 已提交
2110
  
2111 2112 2113
  // master sqlObj locates in param
  SSqlObj* parent = pSql->param;
  assert(parent != NULL);
H
hjxilinx 已提交
2114
  
2115
  SSqlCmd* pCmd = &parent->cmd;
H
hjxilinx 已提交
2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136
  for(int32_t i = 0; i < pStableVgroup->numOfTables; ++i) {
    STableMetaInfo *pInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, i);
    SVgroupsInfo *  pVgroupInfo = (SVgroupsInfo *)pMsg;
    pVgroupInfo->numOfVgroups = htonl(pVgroupInfo->numOfVgroups);

    size_t size = sizeof(SCMVgroupInfo) * pVgroupInfo->numOfVgroups + sizeof(SVgroupsInfo);
    pInfo->vgroupList = calloc(1, size);
    assert(pInfo->vgroupList != NULL);

    memcpy(pInfo->vgroupList, pVgroupInfo, size);
    for (int32_t j = 0; j < pInfo->vgroupList->numOfVgroups; ++j) {
      SCMVgroupInfo *pVgroups = &pInfo->vgroupList->vgroups[j];

      pVgroups->vgId = htonl(pVgroups->vgId);
      assert(pVgroups->numOfIps >= 1);

      for (int32_t k = 0; k < pVgroups->numOfIps; ++k) {
        pVgroups->ipAddr[k].port = htons(pVgroups->ipAddr[k].port);
      }

      pMsg += size;
2137
    }
H
hjxilinx 已提交
2138 2139
  }
  
S
slguan 已提交
2140
  return pSql->res.code;
H
hzcheng 已提交
2141 2142 2143 2144 2145 2146
}

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

2152 2153 2154
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;

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

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

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

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

H
hjxilinx 已提交
2166
  pMetaMsg->numOfColumns = ntohs(pMetaMsg->numOfColumns);
H
hzcheng 已提交
2167

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

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

H
hjxilinx 已提交
2178
  taosCacheRelease(tscCacheHandle, (void *)&(pTableMetaInfo->pTableMeta), false);
H
hjxilinx 已提交
2179
  
H
hjxilinx 已提交
2180 2181 2182
  size_t size = 0;
  STableMeta* pTableMeta = tscCreateTableMetaFromMsg(pMetaMsg, &size);
  
H
hjxilinx 已提交
2183
  pTableMetaInfo->pTableMeta = taosCachePut(tscCacheHandle, key, (char *)pTableMeta, size, tsTableMetaKeepTimer);
H
hjxilinx 已提交
2184
  SSchema *pTableSchema = tscGetTableSchema(pTableMetaInfo->pTableMeta);
H
hzcheng 已提交
2185

2186 2187 2188 2189
  if (pQueryInfo->colList == NULL) {
    pQueryInfo->colList = taosArrayInit(4, POINTER_BYTES);
  }
  
H
hjxilinx 已提交
2190 2191
  SFieldInfo* pFieldInfo = &pQueryInfo->fieldsInfo;
  
S
slguan 已提交
2192
  SColumnIndex index = {0};
H
hjxilinx 已提交
2193 2194 2195
  pSchema = pMetaMsg->schema;
  
  for (int16_t i = 0; i < pMetaMsg->numOfColumns; ++i, ++pSchema) {
S
slguan 已提交
2196
    index.columnIndex = i;
2197 2198
    tscColumnListInsert(pQueryInfo->colList, &index);
    
H
hjxilinx 已提交
2199 2200
    TAOS_FIELD f = tscCreateField(pSchema->type, pSchema->name, pSchema->bytes);
    SFieldSupInfo* pInfo = tscFieldInfoAppend(pFieldInfo, &f);
H
hjxilinx 已提交
2201
    
H
hjxilinx 已提交
2202
    pInfo->pSqlExpr = tscSqlExprAppend(pQueryInfo, TSDB_FUNC_TS_DUMMY, &index,
2203
                     pTableSchema[i].type, pTableSchema[i].bytes, pTableSchema[i].bytes, false);
H
hzcheng 已提交
2204
  }
H
hjxilinx 已提交
2205 2206
  
  pCmd->numOfCols = pQueryInfo->fieldsInfo.numOfOutput;
H
hjxilinx 已提交
2207
  tscFieldInfoUpdateOffset(pQueryInfo);
H
hjxilinx 已提交
2208 2209
  
  tfree(pTableMeta);
H
hzcheng 已提交
2210 2211 2212 2213
  return 0;
}

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

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

H
hjxilinx 已提交
2222 2223 2224
  assert(len <= tListLen(pObj->db));
  strncpy(pObj->db, temp, tListLen(pObj->db));
  
S
slguan 已提交
2225
  tscSetMgmtIpList(&pConnect->ipList);
H
hzcheng 已提交
2226

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

  return 0;
}

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

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

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

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

H
hjxilinx 已提交
2251 2252
  STableMeta *pTableMeta = taosCacheAcquireByName(tscCacheHandle, pTableMetaInfo->name);
  if (pTableMeta == NULL) {
H
hzcheng 已提交
2253 2254 2255 2256 2257 2258 2259 2260
    /* 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 已提交
2261 2262
   * The cached information is expired, however, we may have lost the ref of original meter. So, clear whole cache
   * instead.
H
hzcheng 已提交
2263
   */
H
hjxilinx 已提交
2264 2265
  tscTrace("%p force release metermeta after drop table:%s", pSql, pTableMetaInfo->name);
  taosCacheRelease(tscCacheHandle, (void **)&pTableMeta, true);
H
hzcheng 已提交
2266

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

  return 0;
}

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

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

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

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

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

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

  return 0;
}

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

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

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

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

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

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

  pRes->numOfRows = htonl(pRetrieve->numOfRows);
  pRes->precision = htons(pRetrieve->precision);
2325 2326
  pRes->offset    = htobe64(pRetrieve->offset);
  pRes->useconds  = htobe64(pRetrieve->useconds);
H
hjxilinx 已提交
2327
  pRes->completed = (pRetrieve->completed == 1);
2328
  pRes->data      = pRetrieve->data;
H
hjxilinx 已提交
2329
  
2330
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
2331 2332 2333 2334
  if (tscCreateResPointerInfo(pRes, pQueryInfo) != TSDB_CODE_SUCCESS) {
    return pRes->code;
  }
  
weixin_48148422's avatar
weixin_48148422 已提交
2335
  if (pSql->pSubscription != NULL) {
H
hjxilinx 已提交
2336
    int32_t numOfCols = pQueryInfo->fieldsInfo.numOfOutput;
H
hjxilinx 已提交
2337
    
H
hjxilinx 已提交
2338
    TAOS_FIELD *pField = tscFieldInfoGetField(&pQueryInfo->fieldsInfo, numOfCols - 1);
H
hjxilinx 已提交
2339 2340
    int16_t     offset = tscFieldInfoGetOffset(pQueryInfo, numOfCols - 1);
    
weixin_48148422's avatar
weixin_48148422 已提交
2341 2342
    char* p = pRes->data + (pField->bytes + offset) * pRes->numOfRows;

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

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

  return 0;
}

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

S
slguan 已提交
2365
  SRetrieveTableRsp *pRetrieve = (SRetrieveTableRsp *)pRes->pRsp;
H
hzcheng 已提交
2366 2367 2368

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

2370
  tscSetResultPointer(pQueryInfo, pRes);
H
hzcheng 已提交
2371 2372 2373 2374
  pRes->row = 0;
  return 0;
}

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

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

H
hzcheng 已提交
2384 2385 2386
  pNew->pTscObj = pSql->pTscObj;
  pNew->signature = pNew;
  pNew->cmd.command = TSDB_SQL_META;
S
slguan 已提交
2387

2388
  tscAddSubqueryInfo(&pNew->cmd);
2389 2390 2391 2392

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

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

S
slguan 已提交
2398 2399 2400
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }

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

2404
  strncpy(pNewMeterMetaInfo->name, pTableMetaInfo->name, tListLen(pNewMeterMetaInfo->name));
2405
  memcpy(pNew->cmd.payload, pSql->cmd.payload, TSDB_DEFAULT_PAYLOAD_SIZE);  // tag information if table does not exists.
2406
  tscTrace("%p new pSqlObj:%p to get tableMeta, auto create:%d", pSql, pNew, pNew->cmd.autoCreated);
H
hzcheng 已提交
2407

H
hjxilinx 已提交
2408 2409
  pNew->fp = tscTableMetaCallBack;
  pNew->param = pSql;
H
hzcheng 已提交
2410

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

  return code;
}

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

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

    return TSDB_CODE_SUCCESS;
  }
2435 2436
  
  return getTableMetaFromMgmt(pSql, pTableMetaInfo);
H
hzcheng 已提交
2437 2438
}

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

/*
 * in handling the renew metermeta problem during insertion,
S
slguan 已提交
2446
 *
H
hzcheng 已提交
2447 2448 2449 2450 2451
 * 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 已提交
2452
  if (pCmd->command == TSDB_SQL_INSERT) {
H
hzcheng 已提交
2453 2454 2455 2456 2457 2458 2459
    taosMsleep(50);  // todo: global config
  }
}

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

H
hjxilinx 已提交
2466
  // handle table meta renew process
H
hzcheng 已提交
2467
  SSqlCmd *pCmd = &pSql->cmd;
2468 2469

  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
hjxilinx 已提交
2470
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hzcheng 已提交
2471 2472

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

2483
    tscWaitingForCreateTable(pCmd);
H
hjxilinx 已提交
2484
    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pTableMeta), true);
H
hzcheng 已提交
2485

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

  return code;
}

H
hjxilinx 已提交
2496
static bool allVgroupInfoRetrieved(SSqlCmd* pCmd, int32_t clauseIndex) {
2497
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, clauseIndex);
2498
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
H
hjxilinx 已提交
2499
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, i);
H
hjxilinx 已提交
2500 2501
    if (pTableMetaInfo->vgroupList == NULL) {
      return false;
S
slguan 已提交
2502 2503
    }
  }
H
hjxilinx 已提交
2504 2505 2506 2507
  
  // all super tables vgroupinfo are retrieved, no need to retrieve vgroup info anymore
  return true;
}
H
hzcheng 已提交
2508

H
hjxilinx 已提交
2509 2510 2511 2512 2513
int tscGetSTableVgroupInfo(SSqlObj *pSql, int32_t clauseIndex) {
  int      code = TSDB_CODE_NETWORK_UNAVAIL;
  SSqlCmd *pCmd = &pSql->cmd;
  
  if (allVgroupInfoRetrieved(pCmd, clauseIndex)) {
H
hzcheng 已提交
2514 2515
    return TSDB_CODE_SUCCESS;
  }
H
hjxilinx 已提交
2516

S
slguan 已提交
2517
  SSqlObj *pNew = calloc(1, sizeof(SSqlObj));
H
hzcheng 已提交
2518 2519 2520
  pNew->pTscObj = pSql->pTscObj;
  pNew->signature = pNew;

H
hjxilinx 已提交
2521
  pNew->cmd.command = TSDB_SQL_STABLEVGROUP;
2522 2523
  
  SQueryInfo *pNewQueryInfo = NULL;
2524 2525 2526
  if ((code = tscGetQueryInfoDetailSafely(&pNew->cmd, 0, &pNewQueryInfo)) != TSDB_CODE_SUCCESS) {
    return code;
  }
2527
  
H
hjxilinx 已提交
2528
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, clauseIndex);
2529
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
H
hjxilinx 已提交
2530 2531 2532
    STableMetaInfo *pMInfo = tscGetMetaInfo(pQueryInfo, i);
    STableMeta *pTableMeta = taosCacheAcquireByData(tscCacheHandle, pMInfo->pTableMeta);
    tscAddTableMetaInfo(pNewQueryInfo, pMInfo->name, pTableMeta, NULL, pMInfo->tagColList);
S
slguan 已提交
2533 2534 2535 2536 2537 2538
  }

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

2540
  pNewQueryInfo->numOfTables = pQueryInfo->numOfTables;
H
hjxilinx 已提交
2541
  tscTrace("%p new sqlObj:%p to get vgroupInfo, numOfTables:%d", pSql, pNew, pNewQueryInfo->numOfTables);
H
hzcheng 已提交
2542

2543 2544 2545 2546 2547
  pNew->fp = tscTableMetaCallBack;
  pNew->param = pSql;
  code = tscProcessSql(pNew);
  if (code == TSDB_CODE_SUCCESS) {
    code = TSDB_CODE_ACTION_IN_PROGRESS;
H
hzcheng 已提交
2548 2549 2550 2551 2552
  }

  return code;
}

2553
void tscInitMsgsFp() {
S
slguan 已提交
2554 2555
  tscBuildMsg[TSDB_SQL_SELECT] = tscBuildQueryMsg;
  tscBuildMsg[TSDB_SQL_INSERT] = tscBuildSubmitMsg;
J
jtao1735 已提交
2556
  tscBuildMsg[TSDB_SQL_FETCH] = tscBuildFetchMsg;
H
hzcheng 已提交
2557 2558

  tscBuildMsg[TSDB_SQL_CREATE_DB] = tscBuildCreateDbMsg;
2559
  tscBuildMsg[TSDB_SQL_CREATE_USER] = tscBuildUserMsg;
H
hzcheng 已提交
2560

2561 2562
  tscBuildMsg[TSDB_SQL_CREATE_ACCT] = tscBuildAcctMsg;
  tscBuildMsg[TSDB_SQL_ALTER_ACCT] = tscBuildAcctMsg;
H
hzcheng 已提交
2563 2564

  tscBuildMsg[TSDB_SQL_CREATE_TABLE] = tscBuildCreateTableMsg;
S
[TD-16]  
slguan 已提交
2565
  tscBuildMsg[TSDB_SQL_DROP_USER] = tscBuildDropUserMsg;
H
hzcheng 已提交
2566 2567 2568
  tscBuildMsg[TSDB_SQL_DROP_ACCT] = tscBuildDropAcctMsg;
  tscBuildMsg[TSDB_SQL_DROP_DB] = tscBuildDropDbMsg;
  tscBuildMsg[TSDB_SQL_DROP_TABLE] = tscBuildDropTableMsg;
2569
  tscBuildMsg[TSDB_SQL_ALTER_USER] = tscBuildUserMsg;
S
slguan 已提交
2570 2571 2572
  tscBuildMsg[TSDB_SQL_CREATE_DNODE] = tscBuildCreateDnodeMsg;
  tscBuildMsg[TSDB_SQL_DROP_DNODE] = tscBuildDropDnodeMsg;
  tscBuildMsg[TSDB_SQL_CFG_DNODE] = tscBuildCfgDnodeMsg;
H
hzcheng 已提交
2573 2574 2575 2576 2577
  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 已提交
2578
  tscBuildMsg[TSDB_SQL_META] = tscBuildTableMetaMsg;
H
hjxilinx 已提交
2579
  tscBuildMsg[TSDB_SQL_STABLEVGROUP] = tscBuildSTableVgroupMsg;
S
slguan 已提交
2580
  tscBuildMsg[TSDB_SQL_MULTI_META] = tscBuildMultiMeterMetaMsg;
H
hzcheng 已提交
2581 2582 2583 2584

  tscBuildMsg[TSDB_SQL_HB] = tscBuildHeartBeatMsg;
  tscBuildMsg[TSDB_SQL_SHOW] = tscBuildShowMsg;
  tscBuildMsg[TSDB_SQL_RETRIEVE] = tscBuildRetrieveFromMgmtMsg;
2585 2586 2587
  tscBuildMsg[TSDB_SQL_KILL_QUERY] = tscBuildKillMsg;
  tscBuildMsg[TSDB_SQL_KILL_STREAM] = tscBuildKillMsg;
  tscBuildMsg[TSDB_SQL_KILL_CONNECTION] = tscBuildKillMsg;
H
hzcheng 已提交
2588 2589

  tscProcessMsgRsp[TSDB_SQL_SELECT] = tscProcessQueryRsp;
H
hjxilinx 已提交
2590
  tscProcessMsgRsp[TSDB_SQL_FETCH] = tscProcessRetrieveRspFromNode;
H
hzcheng 已提交
2591 2592 2593 2594 2595

  tscProcessMsgRsp[TSDB_SQL_DROP_DB] = tscProcessDropDbRsp;
  tscProcessMsgRsp[TSDB_SQL_DROP_TABLE] = tscProcessDropTableRsp;
  tscProcessMsgRsp[TSDB_SQL_CONNECT] = tscProcessConnectRsp;
  tscProcessMsgRsp[TSDB_SQL_USE_DB] = tscProcessUseDbRsp;
2596
  tscProcessMsgRsp[TSDB_SQL_META] = tscProcessTableMetaRsp;
H
hjxilinx 已提交
2597
  tscProcessMsgRsp[TSDB_SQL_STABLEVGROUP] = tscProcessSTableVgroupRsp;
S
slguan 已提交
2598
  tscProcessMsgRsp[TSDB_SQL_MULTI_META] = tscProcessMultiMeterMetaRsp;
H
hzcheng 已提交
2599 2600

  tscProcessMsgRsp[TSDB_SQL_SHOW] = tscProcessShowRsp;
H
hjxilinx 已提交
2601
  tscProcessMsgRsp[TSDB_SQL_RETRIEVE] = tscProcessRetrieveRspFromNode;  // rsp handled by same function.
H
hzcheng 已提交
2602
  tscProcessMsgRsp[TSDB_SQL_DESCRIBE_TABLE] = tscProcessDescribeTableRsp;
2603

H
hjxilinx 已提交
2604 2605 2606 2607 2608
  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;
2609

H
hzcheng 已提交
2610 2611
  tscProcessMsgRsp[TSDB_SQL_RETRIEVE_EMPTY_RESULT] = tscProcessEmptyResultRsp;

H
hjxilinx 已提交
2612
  tscProcessMsgRsp[TSDB_SQL_RETRIEVE_LOCALMERGE] = tscProcessRetrieveLocalMergeRsp;
H
hzcheng 已提交
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622

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