tscServer.c 85.9 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"
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
30
#include "qsqltype.h"
H
hzcheng 已提交
31 32 33

#define TSC_MGMT_VNODE 999

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

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

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

B
Bomin Zhang 已提交
43
TSKEY tscGetSubscriptionProgress(void* sub, int64_t uid, TSKEY dflt);
44 45
void tscUpdateSubscriptionProgress(void* sub, int64_t uid, TSKEY ts);
void tscSaveSubscriptionProgress(void* sub);
H
hzcheng 已提交
46

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

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

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

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

S
slguan 已提交
79
void tscUpdateIpSet(void *ahandle, SRpcIpSet *pIpSet) {
S
slguan 已提交
80
  tscMgmtIpSet = *pIpSet;
S
Shengliang Guan 已提交
81
  tscTrace("mnode IP list is changed for ufp is called, numOfIps:%d inUse:%d", tscMgmtIpSet.numOfIps, tscMgmtIpSet.inUse);
S
slguan 已提交
82 83 84
  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 已提交
85 86
}

H
hjxilinx 已提交
87 88 89 90 91 92 93
/*
 * 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.
 */
94
UNUSED_FUNC
H
hjxilinx 已提交
95 96
static int32_t tscGetMgmtConnMaxRetryTimes() {
  int32_t factor = 2;
S
slguan 已提交
97
  return tscMgmtIpSet.numOfIps * factor;
H
hjxilinx 已提交
98 99
}

H
hzcheng 已提交
100 101 102 103 104 105 106 107 108 109 110 111
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) {
112
    SCMHeartBeatRsp *pRsp = (SCMHeartBeatRsp *)pRes->pRsp;
S
slguan 已提交
113
    SRpcIpSet *      pIpList = &pRsp->ipList;
114 115
    if (pIpList->numOfIps > 0) 
      tscSetMgmtIpList(pIpList);
S
slguan 已提交
116

S
Shengliang Guan 已提交
117 118
    pSql->pTscObj->connId = htonl(pRsp->connId);

H
hzcheng 已提交
119 120 121
    if (pRsp->killConnection) {
      tscKillConnection(pObj);
    } else {
S
slguan 已提交
122 123
      if (pRsp->queryId) tscKillQuery(pObj, htonl(pRsp->queryId));
      if (pRsp->streamId) tscKillStream(pObj, htonl(pRsp->streamId));
H
hzcheng 已提交
124 125
    }
  } else {
H
hjxilinx 已提交
126
    tscTrace("heart beat failed, code:%s", tstrerror(code));
H
hzcheng 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139
  }

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

H
hzcheng 已提交
143
    pSql->fp = tscProcessHeartBeatRsp;
H
hjxilinx 已提交
144
    
145 146 147 148
    SQueryInfo *pQueryInfo = NULL;
    tscGetQueryInfoDetailSafely(&pSql->cmd, 0, &pQueryInfo);
    pQueryInfo->command = TSDB_SQL_HB;
    
149
    pSql->cmd.command = TSDB_SQL_HB;
S
slguan 已提交
150 151 152 153 154
    if (TSDB_CODE_SUCCESS != tscAllocPayload(&(pSql->cmd), TSDB_DEFAULT_PAYLOAD_SIZE)) {
      tfree(pSql);
      return;
    }

155
    pSql->cmd.command = TSDB_SQL_HB;
H
hzcheng 已提交
156 157 158 159
    pSql->param = pObj;
    pSql->pTscObj = pObj;
    pSql->signature = pSql;
    pObj->pHb = pSql;
160
    tscAddSubqueryInfo(&pObj->pHb->cmd);
161

S
slguan 已提交
162
    tscTrace("%p pHb is allocated, pObj:%p", pObj->pHb, pObj);
H
hzcheng 已提交
163 164 165
  }

  if (tscShouldFreeHeatBeat(pObj->pHb)) {
S
slguan 已提交
166
    tscTrace("%p free HB object and release connection", pObj);
H
hzcheng 已提交
167 168 169 170 171 172 173 174 175
    tscFreeSqlObj(pObj->pHb);
    tscCloseTscObj(pObj);
    return;
  }

  tscProcessSql(pObj->pHb);
}

int tscSendMsgToServer(SSqlObj *pSql) {
176
  STscObj* pObj = pSql->pTscObj;
H
hjxilinx 已提交
177 178 179
  SSqlCmd* pCmd = &pSql->cmd;
  
  char *pMsg = rpcMallocCont(pCmd->payloadLen);
S
slguan 已提交
180
  if (NULL == pMsg) {
S
slguan 已提交
181
    tscError("%p msg:%s malloc fail", pSql, taosMsg[pSql->cmd.msgType]);
182
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hzcheng 已提交
183 184
  }

S
slguan 已提交
185
  if (pSql->cmd.command < TSDB_SQL_MGMT) {
S
slguan 已提交
186
    memcpy(pMsg, pSql->cmd.payload + tsRpcHeadSize, pSql->cmd.payloadLen);
J
jtao1735 已提交
187 188 189 190 191
  } else {
    pSql->ipList = tscMgmtIpSet;
    memcpy(pMsg, pSql->cmd.payload, pSql->cmd.payloadLen);
  }

陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
192
  // tscTrace("%p msg:%s is sent to server", pSql, taosMsg[pSql->cmd.msgType]);
193

J
jtao1735 已提交
194
  SRpcMsg rpcMsg = {
195 196 197 198
      .msgType = pSql->cmd.msgType,
      .pCont   = pMsg,
      .contLen = pSql->cmd.payloadLen,
      .handle  = pSql,
H
hjxilinx 已提交
199
      .code    = 0
J
jtao1735 已提交
200
  };
201
  rpcSendRequest(pObj->pDnodeConn, &pSql->ipList, &rpcMsg);
H
hzcheng 已提交
202

S
slguan 已提交
203
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
204 205
}

J
jtao1735 已提交
206
void tscProcessMsgFromServer(SRpcMsg *rpcMsg, SRpcIpSet *pIpSet) {
207
  SSqlObj *pSql = (SSqlObj *)rpcMsg->handle;
208 209 210 211 212
  if (pSql == NULL) {
    tscError("%p sql is already released", pSql->signature);
    return;
  }
  if (pSql->signature != pSql) {
H
hzcheng 已提交
213
    tscError("%p sql is already released, signature:%p", pSql, pSql->signature);
S
slguan 已提交
214
    return;
H
hzcheng 已提交
215 216
  }

S
slguan 已提交
217 218 219
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;
  STscObj *pObj = pSql->pTscObj;
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
220
  // tscTrace("%p msg:%s is received from server", pSql, taosMsg[rpcMsg->msgType]);
H
hzcheng 已提交
221

222
  if (pObj->signature != pObj) {
S
slguan 已提交
223 224
    tscTrace("%p sql is already released or DB connection is closed, freed:%d pObj:%p signature:%p", pSql, pSql->freed,
             pObj, pObj->signature);
H
Haojun Liao 已提交
225
    tscFreeSqlObj(pSql);
226
    rpcFreeCont(rpcMsg->pCont);
S
slguan 已提交
227
    return;
H
hzcheng 已提交
228 229
  }

J
jtao1735 已提交
230 231 232 233 234 235
  if (pCmd->command < TSDB_SQL_MGMT) {
    if (pIpSet) pSql->ipList = *pIpSet;
  } else {
    if (pIpSet) tscMgmtIpSet = *pIpSet;
  }

236
  if (rpcMsg->pCont == NULL) {
237
    rpcMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
S
slguan 已提交
238
  } else {
239
    STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
240 241
    if (rpcMsg->code == TSDB_CODE_TDB_INVALID_TABLE_ID || rpcMsg->code == TSDB_CODE_VND_INVALID_VGROUP_ID || 
        rpcMsg->code == TSDB_CODE_RPC_NETWORK_UNAVAIL) {
S
slguan 已提交
242 243 244 245 246 247 248 249 250 251 252
      /*
       * 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) {
253
        rpcMsg->code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
254
        rpcFreeCont(rpcMsg->pCont);
S
slguan 已提交
255 256
        return;
      } else if (pCmd->command == TSDB_SQL_HB) {
257
        rpcMsg->code = TSDB_CODE_RPC_NOT_READY;
258
        rpcFreeCont(rpcMsg->pCont);
S
slguan 已提交
259
        return;
H
Haojun Liao 已提交
260 261 262
      } else if (pCmd->command == TSDB_SQL_META) {
//        rpcFreeCont(rpcMsg->pCont);
//        return;
S
slguan 已提交
263
      } else {
264
        tscWarn("%p it shall renew table meta, code:%s, retry:%d", pSql, tstrerror(rpcMsg->code), ++pSql->retry);
265
        
266
        pSql->res.code = rpcMsg->code;  // keep the previous error code
267 268 269 270 271 272 273 274
        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);
          }
  
275
          rpcFreeCont(rpcMsg->pCont);
S
slguan 已提交
276 277
          return;
        }
H
hzcheng 已提交
278 279
      }
    }
S
slguan 已提交
280
  }
281
  
H
hzcheng 已提交
282
  pRes->rspLen = 0;
283
  
284 285
  if (pRes->code != TSDB_CODE_TSC_QUERY_CANCELLED) {
    pRes->code = (rpcMsg->code != TSDB_CODE_SUCCESS) ? rpcMsg->code : TSDB_CODE_RPC_NETWORK_UNAVAIL;
H
hzcheng 已提交
286
  } else {
H
hjxilinx 已提交
287
    tscTrace("%p query is cancelled, code:%d", pSql, tstrerror(pRes->code));
H
hzcheng 已提交
288 289
  }

S
slguan 已提交
290 291 292 293 294
  if (pRes->code == TSDB_CODE_SUCCESS) {
    tscTrace("%p reset retry counter to be 0 due to success rsp, old:%d", pSql, pSql->retry);
    pSql->retry = 0;
  }

295
  if (pRes->code != TSDB_CODE_TSC_QUERY_CANCELLED) {
296
    assert(rpcMsg->msgType == pCmd->msgType + 1);
297
    pRes->code    = rpcMsg->code;
298
    pRes->rspType = rpcMsg->msgType;
299
    pRes->rspLen  = rpcMsg->contLen;
H
hzcheng 已提交
300

301
    if (pRes->rspLen > 0 && rpcMsg->pCont) {
302 303
      char *tmp = (char *)realloc(pRes->pRsp, pRes->rspLen);
      if (tmp == NULL) {
304
        pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
305 306
      } else {
        pRes->pRsp = tmp;
307
        memcpy(pRes->pRsp, rpcMsg->pCont, pRes->rspLen);
S
slguan 已提交
308
      }
309 310
    } else {
      pRes->pRsp = NULL;
S
slguan 已提交
311 312
    }

H
hzcheng 已提交
313 314 315 316
    /*
     * There is not response callback function for submit response.
     * The actual inserted number of points is the first number.
     */
317
    if (rpcMsg->msgType == TSDB_MSG_TYPE_SUBMIT_RSP && pRes->pRsp != NULL) {
318
      SShellSubmitRspMsg *pMsg = (SShellSubmitRspMsg*)pRes->pRsp;
S
slguan 已提交
319 320 321 322 323 324 325
      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;
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
326 327
      tscTrace("%p SQL cmd:%s, code:%s inserted rows:%d rspLen:%d", pSql, sqlCmd[pCmd->command], 
          tstrerror(pRes->code), pMsg->affectedRows, pRes->rspLen);
S
slguan 已提交
328
    } else {
陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
329
      tscTrace("%p SQL cmd:%s, code:%s rspLen:%d", pSql, sqlCmd[pCmd->command], tstrerror(pRes->code), pRes->rspLen);
H
hzcheng 已提交
330 331
    }
  }
332
  
333 334
  if (pRes->code == TSDB_CODE_SUCCESS && tscProcessMsgRsp[pCmd->command])
    rpcMsg->code = (*tscProcessMsgRsp[pCmd->command])(pSql);
H
hjxilinx 已提交
335
  
336
  if (rpcMsg->code != TSDB_CODE_TSC_ACTION_IN_PROGRESS) {
H
[td-32]  
hjxilinx 已提交
337
    rpcMsg->code = pRes->code ? pRes->code : pRes->numOfRows;
338
    
339
    tscTrace("%p SQL result:%s res:%p", pSql, tstrerror(pRes->code), pSql);
H
hjxilinx 已提交
340
    bool shouldFree = tscShouldBeFreed(pSql);
H
Haojun Liao 已提交
341
    (*pSql->fp)(pSql->param, pSql, rpcMsg->code);
H
hzcheng 已提交
342

343
    if (shouldFree) {
344
      tscTrace("%p sqlObj is automatically freed", pSql);
sangshuduo's avatar
sangshuduo 已提交
345
      tscFreeSqlObj(pSql);
H
hzcheng 已提交
346 347 348
    }
  }

349
  rpcFreeCont(rpcMsg->pCont);
H
hzcheng 已提交
350 351
}

S
slguan 已提交
352 353 354
int doProcessSql(SSqlObj *pSql) {
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;
355 356
  int32_t code = TSDB_CODE_SUCCESS;
  
H
hjxilinx 已提交
357 358 359 360 361 362 363
  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 已提交
364
      pCmd->command == TSDB_SQL_STABLEVGROUP) {
365 366 367 368 369 370
    pRes->code = tscBuildMsg[pCmd->command](pSql, NULL);
  }
  
  if (pRes->code != TSDB_CODE_SUCCESS) {
    tscQueueAsyncRes(pSql);
    return pRes->code;
S
slguan 已提交
371
  }
372

373
  code = tscSendMsgToServer(pSql);
374
  if (code != TSDB_CODE_SUCCESS) {
S
slguan 已提交
375
    pRes->code = code;
H
hjxilinx 已提交
376
    tscQueueAsyncRes(pSql);
S
slguan 已提交
377
  }
H
hjxilinx 已提交
378 379
  
  return TSDB_CODE_SUCCESS;
S
slguan 已提交
380 381 382
}

int tscProcessSql(SSqlObj *pSql) {
383 384
  char *   name = NULL;
  SSqlCmd *pCmd = &pSql->cmd;
385 386
  
  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
387
  STableMetaInfo *pTableMetaInfo = NULL;
388
  uint16_t        type = 0;
389

390
  if (pQueryInfo != NULL) {
H
hjxilinx 已提交
391
    pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
392 393
    if (pTableMetaInfo != NULL) {
      name = pTableMetaInfo->name;
394
    }
395

396
    type = pQueryInfo->type;
397
  
H
hjxilinx 已提交
398
    // while numOfTables equals to 0, it must be Heartbeat
H
hjxilinx 已提交
399
    assert((pQueryInfo->numOfTables == 0 && pQueryInfo->command == TSDB_SQL_HB) || pQueryInfo->numOfTables > 0);
S
slguan 已提交
400
  }
401

陶建辉(Jeff)'s avatar
陶建辉(Jeff) 已提交
402
  tscTrace("%p SQL cmd:%s will be processed, name:%s, type:%d", pSql, sqlCmd[pCmd->command], name, type);
H
hjxilinx 已提交
403
  if (pCmd->command < TSDB_SQL_MGMT) { // the pTableMetaInfo cannot be NULL
H
hjxilinx 已提交
404
    if (pTableMetaInfo == NULL) {
405
      pSql->res.code = TSDB_CODE_TSC_APP_ERROR;
H
hjxilinx 已提交
406 407
      return pSql->res.code;
    }
H
hjxilinx 已提交
408 409
  } else if (pCmd->command < TSDB_SQL_LOCAL) {
    pSql->ipList = tscMgmtIpSet; //?
H
hzcheng 已提交
410 411 412
  } else {  // local handler
    return (*tscProcessMsgRsp[pCmd->command])(pSql);
  }
413
  
S
slguan 已提交
414 415
  return doProcessSql(pSql);
}
H
hzcheng 已提交
416

H
hjxilinx 已提交
417
void tscKillSTableQuery(SSqlObj *pSql) {
418 419 420
  SSqlCmd* pCmd = &pSql->cmd;
  
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
421
  if (!tscIsTwoStageSTableQuery(pQueryInfo, 0)) {
H
hzcheng 已提交
422 423 424 425 426 427
    return;
  }

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

S
slguan 已提交
428
    if (pSub == NULL) {
H
hzcheng 已提交
429 430
      continue;
    }
S
slguan 已提交
431

H
hzcheng 已提交
432 433 434 435
    /*
     * 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.
     */
436
    pSql->pSubs[i]->res.code = TSDB_CODE_TSC_QUERY_CANCELLED;
S
slguan 已提交
437
    //taosStopRpcConn(pSql->pSubs[i]->thandle);
H
hzcheng 已提交
438 439 440 441 442 443 444 445 446 447 448
  }

  /*
   * 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 已提交
449
  while (pCmd->command != TSDB_SQL_RETRIEVE_LOCALMERGE && pCmd->command != TSDB_SQL_RETRIEVE_EMPTY_RESULT) {
H
hzcheng 已提交
450 451 452 453 454 455
    taosMsleep(100);
    if (taosGetTimestampMs() - stime > MAX_WAITING_TIME) {
      break;
    }
  }

H
hjxilinx 已提交
456
  tscTrace("%p super table query cancelled", pSql);
H
hzcheng 已提交
457 458
}

J
jtao1735 已提交
459
int tscBuildFetchMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
460 461 462 463 464
  char *pMsg, *pStart;

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

465
  SRetrieveTableMsg *pRetrieveMsg = (SRetrieveTableMsg *)pMsg;
S
slguan 已提交
466
  pRetrieveMsg->qhandle = htobe64(pSql->res.qhandle);
S
slguan 已提交
467 468
  pMsg += sizeof(pSql->res.qhandle);

469
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
S
slguan 已提交
470
  pRetrieveMsg->free = htons(pQueryInfo->type);
471
  pMsg += sizeof(pQueryInfo->type);
H
hzcheng 已提交
472

473
  // todo valid the vgroupId at the client side
H
hjxilinx 已提交
474 475
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
  
weixin_48148422's avatar
weixin_48148422 已提交
476
  if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
H
hjxilinx 已提交
477
    int32_t vgIndex = pTableMetaInfo->vgroupIndex;
478
    
H
hjxilinx 已提交
479 480
    SVgroupsInfo* pVgroupInfo = pTableMetaInfo->vgroupList;
    pRetrieveMsg->header.vgId = htonl(pVgroupInfo->vgroups[vgIndex].vgId);
481
  } else {
H
hjxilinx 已提交
482
    STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;
H
hjxilinx 已提交
483
    pRetrieveMsg->header.vgId = htonl(pTableMeta->vgroupInfo.vgId);
484 485
  }
  
486 487 488 489
  pMsg += sizeof(SRetrieveTableMsg);
  
  pRetrieveMsg->header.contLen = htonl(pSql->cmd.payloadLen);
  
J
jtao1735 已提交
490
  pSql->cmd.msgType = TSDB_MSG_TYPE_FETCH;
491
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
492 493
}

494
int tscBuildSubmitMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hjxilinx 已提交
495
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
H
hjxilinx 已提交
496
  STableMeta* pTableMeta = tscGetMetaInfo(pQueryInfo, 0)->pTableMeta;
H
hjxilinx 已提交
497
  
498 499 500 501
  char* pMsg = pSql->cmd.payload + tsRpcHeadSize;
  
  // NOTE: shell message size should not include SMsgDesc
  int32_t size = pSql->cmd.payloadLen - sizeof(SMsgDesc);
H
hjxilinx 已提交
502
  
503
  SMsgDesc* pMsgDesc = (SMsgDesc*) pMsg;
504 505
  
  pMsgDesc->numOfVnodes = htonl(1);       //todo set the right number of vnodes
506
  pMsg += sizeof(SMsgDesc);
H
hjxilinx 已提交
507
  
508
  SSubmitMsg *pShellMsg = (SSubmitMsg *)pMsg;
H
hjxilinx 已提交
509
  int32_t vgId = pTableMeta->vgroupInfo.vgId;
510
  
H
hjxilinx 已提交
511
  pShellMsg->header.vgId = htonl(vgId);
512
  pShellMsg->header.contLen = htonl(size);
513
  pShellMsg->length = pShellMsg->header.contLen;
H
hjxilinx 已提交
514
  
515
  pShellMsg->numOfBlocks = htonl(pSql->cmd.numOfTablesInSubmit);  // number of meters to be inserted
H
hzcheng 已提交
516

H
hjxilinx 已提交
517
  // pSql->cmd.payloadLen is set during copying data into payload
S
slguan 已提交
518
  pSql->cmd.msgType = TSDB_MSG_TYPE_SUBMIT;
519
  tscSetDnodeIpList(pSql, &pTableMeta->vgroupInfo);
520
  
S
slguan 已提交
521
  tscTrace("%p build submit msg, vgId:%d numOfVgroup:%d numberOfIP:%d", pSql, vgId, htonl(pMsgDesc->numOfVnodes), pSql->ipList.numOfIps);
522
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
523 524 525
}

/*
526
 * for table query, simply return the size <= 1k
H
hzcheng 已提交
527
 */
528
static int32_t tscEstimateQueryMsgSize(SSqlCmd *pCmd, int32_t clauseIndex) {
H
hzcheng 已提交
529
  const static int32_t MIN_QUERY_MSG_PKT_SIZE = TSDB_MAX_BYTES_PER_ROW * 5;
530
  SQueryInfo *         pQueryInfo = tscGetQueryInfoDetail(pCmd, clauseIndex);
H
hzcheng 已提交
531

532
  int32_t srcColListSize = taosArrayGetSize(pQueryInfo->colList) * sizeof(SColumnInfo);
H
hjxilinx 已提交
533 534 535 536
  
  size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
  int32_t exprSize = sizeof(SSqlFuncMsg) * numOfExprs;
  
537
  return MIN_QUERY_MSG_PKT_SIZE + minMsgSize() + sizeof(SQueryTableMsg) + srcColListSize + exprSize + 4096;
H
hzcheng 已提交
538 539
}

540
static char *doSerializeTableInfo(SQueryTableMsg* pQueryMsg, SSqlObj *pSql, char *pMsg) {
541
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, pSql->cmd.clauseIndex, 0);
B
Bomin Zhang 已提交
542
  TSKEY dfltKey = htobe64(pQueryMsg->window.skey);
543

H
hjxilinx 已提交
544
  STableMeta * pTableMeta = pTableMetaInfo->pTableMeta;
weixin_48148422's avatar
weixin_48148422 已提交
545
  if (UTIL_TABLE_IS_NORMAL_TABLE(pTableMetaInfo) || pTableMetaInfo->pVgroupTables == NULL) {
546 547
    
    SCMVgroupInfo* pVgroupInfo = NULL;
weixin_48148422's avatar
weixin_48148422 已提交
548
    if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
549 550
      int32_t index = pTableMetaInfo->vgroupIndex;
      assert(index >= 0);
H
hjxilinx 已提交
551
  
552 553
      pVgroupInfo = &pTableMetaInfo->vgroupList->vgroups[index];
      tscTrace("%p query on stable, vgIndex:%d, numOfVgroups:%d", pSql, index, pTableMetaInfo->vgroupList->numOfVgroups);
H
hjxilinx 已提交
554 555
    } else {
      pVgroupInfo = &pTableMeta->vgroupInfo;
556
    }
weixin_48148422's avatar
weixin_48148422 已提交
557

558 559
    tscSetDnodeIpList(pSql, pVgroupInfo);
    pQueryMsg->head.vgId = htonl(pVgroupInfo->vgId);
weixin_48148422's avatar
weixin_48148422 已提交
560

561 562 563
    STableIdInfo *pTableIdInfo = (STableIdInfo *)pMsg;
    pTableIdInfo->tid = htonl(pTableMeta->sid);
    pTableIdInfo->uid = htobe64(pTableMeta->uid);
B
Bomin Zhang 已提交
564
    pTableIdInfo->key = htobe64(tscGetSubscriptionProgress(pSql->pSubscription, pTableMeta->uid, dfltKey));
weixin_48148422's avatar
weixin_48148422 已提交
565

566 567 568 569 570 571
    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);
weixin_48148422's avatar
weixin_48148422 已提交
572

573
    tscTrace("%p query on stable, vgIndex:%d, numOfVgroups:%d", pSql, index, numOfVgroups);
weixin_48148422's avatar
weixin_48148422 已提交
574

575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
    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);
B
Bomin Zhang 已提交
591
      pTableIdInfo->key = htobe64(tscGetSubscriptionProgress(pSql->pSubscription, pItem->uid, dfltKey));
592 593 594 595
      pMsg += sizeof(STableIdInfo);
    }
  }
  
H
Haojun Liao 已提交
596 597
  tscTrace("%p vgId:%d, query on table:%s, tid:%d, uid:%" PRIu64, pSql, htonl(pQueryMsg->head.vgId), pTableMetaInfo->name,
      pTableMeta->sid, pTableMeta->uid);
H
hjxilinx 已提交
598
  
599 600 601
  return pMsg;
}

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

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

S
slguan 已提交
607 608 609 610
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
    tscError("%p failed to malloc for query msg", pSql);
    return -1;
  }
611
  
612
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
613
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
614
  STableMeta * pTableMeta = pTableMetaInfo->pTableMeta;
615
  
H
hjxilinx 已提交
616
  if (taosArrayGetSize(pQueryInfo->colList) <= 0 && !tscQueryTags(pQueryInfo)) {
617 618 619
    tscError("%p illegal value of numOfCols in query msg: %d", pSql, tscGetNumOfColumns(pTableMeta));
    return -1;
  }
620 621 622 623 624 625 626 627 628 629
  
  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;
  }
630 631

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

S
slguan 已提交
633
  SQueryTableMsg *pQueryMsg = (SQueryTableMsg *)pStart;
H
hzcheng 已提交
634

635
  int32_t numOfTags = taosArrayGetSize(pTableMetaInfo->tagColList);
636
  
637
  if (pQueryInfo->order.order == TSDB_ORDER_ASC) {
H
hjxilinx 已提交
638 639
    pQueryMsg->window.skey = htobe64(pQueryInfo->window.skey);
    pQueryMsg->window.ekey = htobe64(pQueryInfo->window.ekey);
H
hzcheng 已提交
640
  } else {
H
hjxilinx 已提交
641 642
    pQueryMsg->window.skey = htobe64(pQueryInfo->window.ekey);
    pQueryMsg->window.ekey = htobe64(pQueryInfo->window.skey);
H
hzcheng 已提交
643 644
  }

645 646
  pQueryMsg->order          = htons(pQueryInfo->order.order);
  pQueryMsg->orderColId     = htons(pQueryInfo->order.orderColId);
H
Haojun Liao 已提交
647
  pQueryMsg->fillType       = htons(pQueryInfo->fillType);
648 649
  pQueryMsg->limit          = htobe64(pQueryInfo->limit.limit);
  pQueryMsg->offset         = htobe64(pQueryInfo->limit.offset);
650
  pQueryMsg->numOfCols      = htons(taosArrayGetSize(pQueryInfo->colList));
651 652
  pQueryMsg->intervalTime   = htobe64(pQueryInfo->intervalTime);
  pQueryMsg->slidingTime    = htobe64(pQueryInfo->slidingTime);
H
hjxilinx 已提交
653
  pQueryMsg->slidingTimeUnit = pQueryInfo->slidingTimeUnit;
654
  pQueryMsg->numOfGroupCols = htons(pQueryInfo->groupbyExpr.numOfGroupCols);
655
  pQueryMsg->numOfTags      = htonl(numOfTags);
weixin_48148422's avatar
weixin_48148422 已提交
656
  pQueryMsg->tagNameRelType = htons(pQueryInfo->tagCond.relType);
657
  pQueryMsg->queryType      = htons(pQueryInfo->type);
H
hjxilinx 已提交
658 659 660
  
  size_t numOfOutput = tscSqlExprNumOfExprs(pQueryInfo);
  pQueryMsg->numOfOutput = htons(numOfOutput);
H
hjxilinx 已提交
661 662
  if (numOfOutput < 0) {
    tscError("%p illegal value of number of output columns in query msg: %d", pSql, numOfOutput);
H
hzcheng 已提交
663 664 665 666
    return -1;
  }

  // set column list ids
667 668
  size_t numOfCols = taosArrayGetSize(pQueryInfo->colList);
  char *pMsg = (char *)(pQueryMsg->colList) + numOfCols * sizeof(SColumnInfo);
H
hjxilinx 已提交
669
  SSchema *pSchema = tscGetTableSchema(pTableMeta);
670
  
671 672 673
  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumn *pCol = taosArrayGetP(pQueryInfo->colList, i);
    SSchema *pColSchema = &pSchema[pCol->colIndex.columnIndex];
H
hzcheng 已提交
674

675
    if (pCol->colIndex.columnIndex >= tscGetNumOfColumns(pTableMeta) || pColSchema->type < TSDB_DATA_TYPE_BOOL ||
676 677 678 679 680
        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);

681
      return TSDB_CODE_TSC_INVALID_SQL;
682
    }
H
hzcheng 已提交
683 684 685

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

S
slguan 已提交
689 690 691
    // 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 已提交
692

S
slguan 已提交
693
      SColumnFilterInfo *pFilterMsg = (SColumnFilterInfo *)pMsg;
694
      pFilterMsg->filterstr = htons(pColFilter->filterstr);
S
slguan 已提交
695 696

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

698
      if (pColFilter->filterstr) {
S
slguan 已提交
699 700 701 702 703 704 705 706 707 708
        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 已提交
709

S
slguan 已提交
710 711 712 713 714
      if (pColFilter->lowerRelOptr == TSDB_RELATION_INVALID && pColFilter->upperRelOptr == TSDB_RELATION_INVALID) {
        tscError("invalid filter info");
        return -1;
      }
    }
H
hzcheng 已提交
715 716
  }

H
hjxilinx 已提交
717
  SSqlFuncMsg *pSqlFuncExpr = (SSqlFuncMsg *)pMsg;
H
hjxilinx 已提交
718
  for (int32_t i = 0; i < tscSqlExprNumOfExprs(pQueryInfo); ++i) {
719
    SSqlExpr *pExpr = tscSqlExprGet(pQueryInfo, i);
H
hzcheng 已提交
720

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

727 728 729
    pSqlFuncExpr->colInfo.colId    = htons(pExpr->colInfo.colId);
    pSqlFuncExpr->colInfo.colIndex = htons(pExpr->colInfo.colIndex);
    pSqlFuncExpr->colInfo.flag     = htons(pExpr->colInfo.flag);
H
hzcheng 已提交
730

731
    pSqlFuncExpr->functionId  = htons(pExpr->functionId);
H
hzcheng 已提交
732
    pSqlFuncExpr->numOfParams = htons(pExpr->numOfParams);
H
hjxilinx 已提交
733
    pMsg += sizeof(SSqlFuncMsg);
H
hzcheng 已提交
734 735 736 737 738 739 740

    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);
741
        pMsg += pExpr->param[j].nLen;
H
hzcheng 已提交
742 743 744 745 746
      } else {
        pSqlFuncExpr->arg[j].argValue.i64 = htobe64(pExpr->param[j].i64Key);
      }
    }

H
hjxilinx 已提交
747
    pSqlFuncExpr = (SSqlFuncMsg *)pMsg;
H
hzcheng 已提交
748
  }
749
  
750
  // serialize the table info (sid, uid, tags)
751 752
  pMsg = doSerializeTableInfo(pQueryMsg, pSql, pMsg);
  
753
  SSqlGroupbyExpr *pGroupbyExpr = &pQueryInfo->groupbyExpr;
754
  if (pGroupbyExpr->numOfGroupCols > 0) {
S
slguan 已提交
755
    pQueryMsg->orderByIdx = htons(pGroupbyExpr->orderIndex);
H
hzcheng 已提交
756 757
    pQueryMsg->orderType = htons(pGroupbyExpr->orderType);

S
slguan 已提交
758
    for (int32_t j = 0; j < pGroupbyExpr->numOfGroupCols; ++j) {
759 760
      SColIndex* pCol = taosArrayGet(pGroupbyExpr->columnInfo, j);
  
S
slguan 已提交
761 762 763
      *((int16_t *)pMsg) = pCol->colId;
      pMsg += sizeof(pCol->colId);

764 765
      *((int16_t *)pMsg) += pCol->colIndex;
      pMsg += sizeof(pCol->colIndex);
S
slguan 已提交
766 767 768

      *((int16_t *)pMsg) += pCol->flag;
      pMsg += sizeof(pCol->flag);
H
hjxilinx 已提交
769 770 771
      
      memcpy(pMsg, pCol->name, tListLen(pCol->name));
      pMsg += tListLen(pCol->name);
S
slguan 已提交
772 773 774
    }
  }

775
  if (pQueryInfo->fillType != TSDB_FILL_NONE) {
H
hjxilinx 已提交
776
    for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutput; ++i) {
777 778
      *((int64_t *)pMsg) = htobe64(pQueryInfo->fillVal[i]);
      pMsg += sizeof(pQueryInfo->fillVal[0]);
S
slguan 已提交
779 780
    }
  }
781 782 783 784 785 786 787 788 789
  
  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 已提交
790
      SColumn *pCol = taosArrayGetP(pTableMetaInfo->tagColList, i);
791 792 793 794 795 796 797 798
      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);

799
        return TSDB_CODE_TSC_INVALID_SQL;
800 801 802 803 804 805 806 807 808 809 810 811
      }
  
      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 已提交
812 813 814 815 816 817

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

818
  if (pQueryInfo->tsBuf != NULL) {
H
hjxilinx 已提交
819
    STSVnodeBlockInfo *pBlockInfo = tsBufGetVnodeBlockInfo(pQueryInfo->tsBuf, pTableMetaInfo->vgroupIndex);
820
    assert(QUERY_IS_JOIN_QUERY(pQueryInfo->type) && pBlockInfo != NULL);  // this query should not be sent
S
slguan 已提交
821 822

    // todo refactor
823 824
    fseek(pQueryInfo->tsBuf->f, pBlockInfo->offset, SEEK_SET);
    fread(pMsg, pBlockInfo->compLen, 1, pQueryInfo->tsBuf->f);
S
slguan 已提交
825 826 827 828

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

S
slguan 已提交
831 832
  pQueryMsg->tsLen = htonl(tsLen);
  pQueryMsg->tsNumOfBlocks = htonl(numOfBlocks);
833 834
  if (pQueryInfo->tsBuf != NULL) {
    pQueryMsg->tsOrder = htonl(pQueryInfo->tsBuf->tsOrder);
H
hzcheng 已提交
835 836
  }

H
hjxilinx 已提交
837
  // serialize tag column query condition
838
  if (pQueryInfo->tagCond.pCond != NULL && taosArrayGetSize(pQueryInfo->tagCond.pCond) > 0) {
839 840
    STagCond* pTagCond = &pQueryInfo->tagCond;
    
841
    SCond *pCond = tsGetSTableQueryCond(pTagCond, pTableMeta->uid);
842
    if (pCond != NULL && pCond->cond != NULL) {
843 844
      pQueryMsg->tagCondLen = htons(pCond->len);
      memcpy(pMsg, pCond->cond, pCond->len);
845
      
846
      pMsg += pCond->len;
847 848 849
    }
  }
  
weixin_48148422's avatar
weixin_48148422 已提交
850 851 852 853 854 855 856 857
  if (pQueryInfo->tagCond.tbnameCond.cond == NULL) {
    *pMsg = 0;
    pMsg++;
  } else {
    strcpy(pMsg, pQueryInfo->tagCond.tbnameCond.cond);
    pMsg += strlen(pQueryInfo->tagCond.tbnameCond.cond) + 1;
  }

858
  int32_t msgLen = pMsg - pStart;
H
hzcheng 已提交
859 860 861

  tscTrace("%p msg built success,len:%d bytes", pSql, msgLen);
  pCmd->payloadLen = msgLen;
S
slguan 已提交
862
  pSql->cmd.msgType = TSDB_MSG_TYPE_QUERY;
H
hjxilinx 已提交
863
  
864
  pQueryMsg->head.contLen = htonl(msgLen);
H
hzcheng 已提交
865
  assert(msgLen + minMsgSize() <= size);
866 867

  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
868 869
}

870 871
int32_t tscBuildCreateDbMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
872
  pCmd->payloadLen = sizeof(SCMCreateDbMsg);
S
slguan 已提交
873
  pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_DB;
H
hzcheng 已提交
874

875
  SCMCreateDbMsg *pCreateDbMsg = (SCMCreateDbMsg*)pCmd->payload;
876

877
  assert(pCmd->numOfClause == 1);
878
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
879
  strncpy(pCreateDbMsg->db, pTableMetaInfo->name, tListLen(pCreateDbMsg->db));
H
hzcheng 已提交
880

881
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
882 883
}

884 885
int32_t tscBuildCreateDnodeMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
886
  pCmd->payloadLen = sizeof(SCMCreateDnodeMsg);
S
slguan 已提交
887 888
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
889
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
890
  }
H
hzcheng 已提交
891

892
  SCMCreateDnodeMsg *pCreate = (SCMCreateDnodeMsg *)pCmd->payload;
J
jtao1735 已提交
893 894
  strncpy(pCreate->ep, pInfo->pDCLInfo->a[0].z, pInfo->pDCLInfo->a[0].n);
  
S
slguan 已提交
895
  pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_DNODE;
H
hzcheng 已提交
896

897
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
898 899
}

900 901
int32_t tscBuildAcctMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
902
  pCmd->payloadLen = sizeof(SCMCreateAcctMsg);
S
slguan 已提交
903 904
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
905
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
906
  }
H
hzcheng 已提交
907

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

910 911
  SSQLToken *pName = &pInfo->pDCLInfo->user.user;
  SSQLToken *pPwd = &pInfo->pDCLInfo->user.passwd;
H
hzcheng 已提交
912

913 914
  strncpy(pAlterMsg->user, pName->z, pName->n);
  strncpy(pAlterMsg->pass, pPwd->z, pPwd->n);
S
slguan 已提交
915

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

918 919 920 921 922 923 924 925
  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 已提交
926

927 928 929 930 931 932 933 934 935 936 937 938 939
  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 已提交
940

S
slguan 已提交
941
  pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_ACCT;
942
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
943 944
}

945 946
int32_t tscBuildUserMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
947
  pCmd->payloadLen = sizeof(SCMCreateUserMsg);
S
slguan 已提交
948

S
slguan 已提交
949 950
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
951
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
952 953
  }

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

956 957 958
  SUserInfo *pUser = &pInfo->pDCLInfo->user;
  strncpy(pAlterMsg->user, pUser->user.z, pUser->user.n);
  pAlterMsg->flag = pUser->type;
H
hzcheng 已提交
959

960 961 962 963
  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 已提交
964 965
  } else { // create user password info
    strncpy(pAlterMsg->pass, pUser->passwd.z, pUser->passwd.n);
966
  }
H
hzcheng 已提交
967

968
  if (pUser->type == TSDB_ALTER_USER_PASSWD || pUser->type == TSDB_ALTER_USER_PRIVILEGES) {
S
slguan 已提交
969
    pCmd->msgType = TSDB_MSG_TYPE_CM_ALTER_USER;
970
  } else {
S
slguan 已提交
971
    pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_USER;
972
  }
H
hzcheng 已提交
973

974
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
975 976
}

977 978
int32_t tscBuildCfgDnodeMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
S
slguan 已提交
979
  pCmd->payloadLen = sizeof(SCMCfgDnodeMsg);
guanshengliang's avatar
guanshengliang 已提交
980
  pCmd->msgType = TSDB_MSG_TYPE_CM_CONFIG_DNODE;
981 982
  return TSDB_CODE_SUCCESS;
}
S
slguan 已提交
983

984 985
int32_t tscBuildDropDbMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
986
  pCmd->payloadLen = sizeof(SCMDropDbMsg);
H
hzcheng 已提交
987

S
slguan 已提交
988 989
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
990
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
991 992
  }

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

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

S
slguan 已提交
999
  pCmd->msgType = TSDB_MSG_TYPE_CM_DROP_DB;
1000
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1001 1002
}

1003 1004
int32_t tscBuildDropTableMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
1005
  pCmd->payloadLen = sizeof(SCMDropTableMsg);
H
hzcheng 已提交
1006

S
slguan 已提交
1007 1008
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
1009
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
1010
  }
H
hzcheng 已提交
1011

1012
  SCMDropTableMsg *pDropTableMsg = (SCMDropTableMsg*)pCmd->payload;
1013
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1014
  strcpy(pDropTableMsg->tableId, pTableMetaInfo->name);
S
slguan 已提交
1015
  pDropTableMsg->igNotExists = pInfo->pDCLInfo->existsCheck ? 1 : 0;
H
hzcheng 已提交
1016

S
slguan 已提交
1017
  pCmd->msgType = TSDB_MSG_TYPE_CM_DROP_TABLE;
1018
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1019 1020
}

1021
int32_t tscBuildDropDnodeMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
S
slguan 已提交
1022
  SSqlCmd *pCmd = &pSql->cmd;
1023
  pCmd->payloadLen = sizeof(SCMDropDnodeMsg);
S
slguan 已提交
1024 1025
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
1026
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
1027
  }
H
hzcheng 已提交
1028

1029
  SCMDropDnodeMsg *pDrop = (SCMDropDnodeMsg *)pCmd->payload;
1030
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
J
jtao1735 已提交
1031
  strcpy(pDrop->ep, pTableMetaInfo->name);
S
slguan 已提交
1032
  pCmd->msgType = TSDB_MSG_TYPE_CM_DROP_DNODE;
H
hzcheng 已提交
1033

1034
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1035 1036
}

S
[TD-16]  
slguan 已提交
1037
int32_t tscBuildDropUserMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
1038
  SSqlCmd *pCmd = &pSql->cmd;
1039
  pCmd->payloadLen = sizeof(SCMDropUserMsg);
S
slguan 已提交
1040
  pCmd->msgType = TSDB_MSG_TYPE_CM_DROP_USER;
H
hzcheng 已提交
1041

S
slguan 已提交
1042 1043
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
1044
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
1045
  }
H
hzcheng 已提交
1046

1047
  SCMDropUserMsg *pDropMsg = (SCMDropUserMsg*)pCmd->payload;
1048
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1049
  strcpy(pDropMsg->user, pTableMetaInfo->name);
H
hzcheng 已提交
1050

1051
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1052 1053
}

S
[TD-16]  
slguan 已提交
1054 1055 1056 1057 1058 1059 1060
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);
1061
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
[TD-16]  
slguan 已提交
1062 1063 1064 1065 1066 1067 1068 1069 1070
  }

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

  return TSDB_CODE_SUCCESS;
}

1071 1072
int32_t tscBuildUseDbMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
1073
  pCmd->payloadLen = sizeof(SCMUseDbMsg);
H
hzcheng 已提交
1074

S
slguan 已提交
1075 1076
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
1077
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
1078
  }
1079

1080
  SCMUseDbMsg *pUseDbMsg = (SCMUseDbMsg*)pCmd->payload;
1081
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1082
  strcpy(pUseDbMsg->db, pTableMetaInfo->name);
S
slguan 已提交
1083
  pCmd->msgType = TSDB_MSG_TYPE_CM_USE_DB;
H
hzcheng 已提交
1084

1085
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1086 1087
}

1088
int32_t tscBuildShowMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1089
  STscObj *pObj = pSql->pTscObj;
S
slguan 已提交
1090
  SSqlCmd *pCmd = &pSql->cmd;
S
slguan 已提交
1091
  pCmd->msgType = TSDB_MSG_TYPE_CM_SHOW;
1092
  pCmd->payloadLen = sizeof(SCMShowMsg) + 100;
H
hzcheng 已提交
1093

S
slguan 已提交
1094 1095
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
1096
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
1097
  }
H
hzcheng 已提交
1098

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

1101
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1102
  size_t nameLen = strlen(pTableMetaInfo->name);
S
slguan 已提交
1103
  if (nameLen > 0) {
H
hjxilinx 已提交
1104
    strcpy(pShowMsg->db, pTableMetaInfo->name);  // prefix is set here
H
hzcheng 已提交
1105
  } else {
S
slguan 已提交
1106
    strcpy(pShowMsg->db, pObj->db);
H
hzcheng 已提交
1107 1108
  }

1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
  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 已提交
1121

1122 1123 1124 1125
    strncpy(pShowMsg->payload, pIpAddr->z, pIpAddr->n);
    pShowMsg->payloadLen = htons(pIpAddr->n);
  }

1126
  pCmd->payloadLen = sizeof(SCMShowMsg) + pShowMsg->payloadLen;
1127
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1128 1129
}

1130
int32_t tscBuildKillMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1131
  SSqlCmd *pCmd = &pSql->cmd;
1132
  pCmd->payloadLen = sizeof(SCMKillQueryMsg);
H
hzcheng 已提交
1133

1134 1135
  switch (pCmd->command) {
    case TSDB_SQL_KILL_QUERY:
S
slguan 已提交
1136
      pCmd->msgType = TSDB_MSG_TYPE_CM_KILL_QUERY;
1137 1138
      break;
    case TSDB_SQL_KILL_CONNECTION:
S
slguan 已提交
1139
      pCmd->msgType = TSDB_MSG_TYPE_CM_KILL_CONN;
1140 1141
      break;
    case TSDB_SQL_KILL_STREAM:
S
slguan 已提交
1142
      pCmd->msgType = TSDB_MSG_TYPE_CM_KILL_STREAM;
1143 1144 1145
      break;
  }
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1146 1147
}

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

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

1153
  SCreateTableSQL *pCreateTableInfo = pInfo->pCreateTableInfo;
1154
  if (pCreateTableInfo->type == TSQL_CREATE_TABLE_FROM_STABLE) {
H
hzcheng 已提交
1155 1156
    size += sizeof(STagData);
  } else {
S
slguan 已提交
1157
    size += sizeof(SSchema) * (pCmd->numOfCols + pCmd->count);
H
hzcheng 已提交
1158
  }
1159

1160 1161 1162
  if (pCreateTableInfo->pSelect != NULL) {
    size += (pCreateTableInfo->pSelect->selectToken.n + 1);
  }
H
hzcheng 已提交
1163 1164 1165 1166

  return size + TSDB_EXTRA_PAYLOAD_SIZE;
}

1167
int tscBuildCreateTableMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1168
  int              msgLen = 0;
S
slguan 已提交
1169
  SSchema *        pSchema;
H
hzcheng 已提交
1170
  int              size = 0;
1171 1172 1173
  SSqlCmd *pCmd = &pSql->cmd;

  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
hjxilinx 已提交
1174
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hzcheng 已提交
1175 1176

  // Reallocate the payload size
1177
  size = tscEstimateCreateTableMsgLength(pSql, pInfo);
S
slguan 已提交
1178 1179
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
    tscError("%p failed to malloc for create table msg", pSql);
1180
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
1181
  }
H
hzcheng 已提交
1182 1183


1184
  SCMCreateTableMsg *pCreateTableMsg = (SCMCreateTableMsg *)pCmd->payload;
H
hjxilinx 已提交
1185
  strcpy(pCreateTableMsg->tableId, pTableMetaInfo->name);
1186 1187

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

1190 1191 1192
  SCreateTableSQL *pCreateTable = pInfo->pCreateTableInfo;

  pCreateTableMsg->igExists = pCreateTable->existCheck ? 1 : 0;
H
hzcheng 已提交
1193 1194 1195 1196
  pCreateTableMsg->numOfColumns = htons(pCmd->numOfCols);
  pCreateTableMsg->numOfTags = htons(pCmd->count);

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

1199 1200
  int8_t type = pInfo->pCreateTableInfo->type;
  if (type == TSQL_CREATE_TABLE_FROM_STABLE) {  // create by using super table, tags value
1201 1202 1203 1204 1205 1206 1207
    STagData* pTag = &pInfo->pCreateTableInfo->usingInfo.tagdata;
    *(int32_t*)pMsg = htonl(pTag->dataLen);
    pMsg += sizeof(int32_t);
    memcpy(pMsg, pTag->name, sizeof(pTag->name));
    pMsg += sizeof(pTag->name);
    memcpy(pMsg, pTag->data, pTag->dataLen);
    pMsg += pTag->dataLen;
1208
  } else {  // create (super) table
1209
    pSchema = (SSchema *)pCreateTableMsg->schema;
1210

H
hzcheng 已提交
1211
    for (int i = 0; i < pCmd->numOfCols + pCmd->count; ++i) {
H
hjxilinx 已提交
1212
      TAOS_FIELD *pField = tscFieldInfoGetField(&pQueryInfo->fieldsInfo, i);
H
hzcheng 已提交
1213 1214 1215 1216

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

H
hzcheng 已提交
1218 1219 1220 1221
      pSchema++;
    }

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

1225 1226 1227
      strncpy(pMsg, pQuerySql->selectToken.z, pQuerySql->selectToken.n + 1);
      pCreateTableMsg->sqlLen = htons(pQuerySql->selectToken.n + 1);
      pMsg += pQuerySql->selectToken.n + 1;
H
hzcheng 已提交
1228 1229 1230
    }
  }

H
hjxilinx 已提交
1231
  tscFieldInfoClear(&pQueryInfo->fieldsInfo);
H
hzcheng 已提交
1232

S
slguan 已提交
1233
  msgLen = pMsg - (char*)pCreateTableMsg;
S
slguan 已提交
1234
  pCreateTableMsg->contLen = htonl(msgLen);
H
hzcheng 已提交
1235
  pCmd->payloadLen = msgLen;
S
slguan 已提交
1236
  pCmd->msgType = TSDB_MSG_TYPE_CM_CREATE_TABLE;
H
hzcheng 已提交
1237 1238

  assert(msgLen + minMsgSize() <= size);
1239
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1240 1241 1242
}

int tscEstimateAlterTableMsgLength(SSqlCmd *pCmd) {
1243
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
guanshengliang's avatar
guanshengliang 已提交
1244
  return minMsgSize() + sizeof(SCMAlterTableMsg) + sizeof(SSchema) * tscNumOfFields(pQueryInfo) +
H
hzcheng 已提交
1245 1246 1247
         TSDB_EXTRA_PAYLOAD_SIZE;
}

1248
int tscBuildAlterTableMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
1249 1250
  char *pMsg;
  int   msgLen = 0;
H
hzcheng 已提交
1251

1252
  SSqlCmd    *pCmd = &pSql->cmd;
1253 1254
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);

H
hjxilinx 已提交
1255
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
1256 1257 1258
  
  SAlterTableSQL *pAlterInfo = pInfo->pAlterInfo;
  int size = tscEstimateAlterTableMsgLength(pCmd);
S
slguan 已提交
1259 1260 1261 1262
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
    tscError("%p failed to malloc for alter table msg", pSql);
    return -1;
  }
1263 1264
  
  SCMAlterTableMsg *pAlterTableMsg = (SCMAlterTableMsg *)pCmd->payload;
H
hjxilinx 已提交
1265
  tscGetDBInfoFromMeterId(pTableMetaInfo->name, pAlterTableMsg->db);
H
hzcheng 已提交
1266

H
hjxilinx 已提交
1267
  strcpy(pAlterTableMsg->tableId, pTableMetaInfo->name);
1268
  pAlterTableMsg->type = htons(pAlterInfo->type);
1269

1270
  pAlterTableMsg->numOfCols = htons(tscNumOfFields(pQueryInfo));
S
slguan 已提交
1271
  SSchema *pSchema = pAlterTableMsg->schema;
1272
  for (int i = 0; i < tscNumOfFields(pQueryInfo); ++i) {
H
hjxilinx 已提交
1273
    TAOS_FIELD *pField = tscFieldInfoGetField(&pQueryInfo->fieldsInfo, i);
1274
  
H
hzcheng 已提交
1275 1276 1277 1278 1279 1280 1281
    pSchema->type = pField->type;
    strcpy(pSchema->name, pField->name);
    pSchema->bytes = htons(pField->bytes);
    pSchema++;
  }

  pMsg = (char *)pSchema;
1282 1283 1284
  pAlterTableMsg->tagValLen = htonl(pAlterInfo->tagData.dataLen);
  memcpy(pMsg, pAlterInfo->tagData.data, pAlterInfo->tagData.dataLen);
  pMsg += pAlterInfo->tagData.dataLen;
H
hzcheng 已提交
1285

S
slguan 已提交
1286
  msgLen = pMsg - (char*)pAlterTableMsg;
1287

H
hzcheng 已提交
1288
  pCmd->payloadLen = msgLen;
S
slguan 已提交
1289
  pCmd->msgType = TSDB_MSG_TYPE_CM_ALTER_TABLE;
H
hzcheng 已提交
1290 1291

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

1293
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1294 1295
}

1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
int tscBuildUpdateTagMsg(SSqlObj* pSql, SSqlInfo *pInfo) {
  SSqlCmd* pCmd = &pSql->cmd;
  pCmd->msgType = TSDB_MSG_TYPE_UPDATE_TAG_VAL;
  
  SUpdateTableTagValMsg* pUpdateMsg = (SUpdateTableTagValMsg*) (pCmd->payload + tsRpcHeadSize);
  pCmd->payloadLen = htonl(pUpdateMsg->head.contLen);
  
  return TSDB_CODE_SUCCESS;
}

1306
int tscAlterDbMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
S
slguan 已提交
1307
  SSqlCmd *pCmd = &pSql->cmd;
1308
  pCmd->payloadLen = sizeof(SCMAlterDbMsg);
S
slguan 已提交
1309
  pCmd->msgType = TSDB_MSG_TYPE_CM_ALTER_DB;
H
hzcheng 已提交
1310

1311
  SCMAlterDbMsg *pAlterDbMsg = (SCMAlterDbMsg*)pCmd->payload;
1312
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1313
  strcpy(pAlterDbMsg->db, pTableMetaInfo->name);
H
hzcheng 已提交
1314

1315
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1316 1317
}

1318
int tscBuildRetrieveFromMgmtMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
S
slguan 已提交
1319
  SSqlCmd *pCmd = &pSql->cmd;
J
jtao1735 已提交
1320
  pCmd->msgType = TSDB_MSG_TYPE_CM_RETRIEVE;
S
slguan 已提交
1321
  pCmd->payloadLen = sizeof(SRetrieveTableMsg);
S
slguan 已提交
1322

S
slguan 已提交
1323 1324
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
1325
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hzcheng 已提交
1326
  }
S
slguan 已提交
1327

S
slguan 已提交
1328 1329 1330 1331
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
  SRetrieveTableMsg *pRetrieveMsg = (SRetrieveTableMsg*)pCmd->payload;
  pRetrieveMsg->qhandle = htobe64(pSql->res.qhandle);
  pRetrieveMsg->free = htons(pQueryInfo->type);
H
hzcheng 已提交
1332

1333
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1334 1335
}

1336
static int tscSetResultPointer(SQueryInfo *pQueryInfo, SSqlRes *pRes) {
1337
  if (tscCreateResPointerInfo(pRes, pQueryInfo) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
1338 1339 1340
    return pRes->code;
  }

H
hjxilinx 已提交
1341
  for (int i = 0; i < pQueryInfo->fieldsInfo.numOfOutput; ++i) {
H
hjxilinx 已提交
1342
    int16_t offset = tscFieldInfoGetOffset(pQueryInfo, i);
H
hjxilinx 已提交
1343
    pRes->tsrow[i] = ((char*) pRes->data + offset * pRes->numOfRows);
H
hzcheng 已提交
1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
  }

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

1359
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
1360

H
hzcheng 已提交
1361 1362 1363 1364 1365 1366 1367
  pRes->code = TSDB_CODE_SUCCESS;

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

1368
    tscSetResultPointer(pQueryInfo, pRes);
H
hzcheng 已提交
1369
  } else {
S
slguan 已提交
1370
    tscResetForNextRetrieve(pRes);
H
hzcheng 已提交
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
  }

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

H
hjxilinx 已提交
1389
  STableComInfo tinfo = tscGetTableInfo(pTableMetaInfo->pTableMeta);
H
hjxilinx 已提交
1390 1391
  
  int32_t numOfRes = tinfo.numOfColumns + tinfo.numOfTags;
H
hzcheng 已提交
1392 1393 1394 1395
  return tscLocalResultCommonBuilder(pSql, numOfRes);
}

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

1398 1399
//  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
//  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
S
slguan 已提交
1400 1401

  int32_t numOfRes = 0;
H
hjxilinx 已提交
1402
#if 0
1403
  if (tscSqlExprGet(pQueryInfo, 0)->functionId == TSDB_FUNC_TAGPRJ) {
H
hjxilinx 已提交
1404
    numOfRes = pTableMetaInfo->pMetricMeta->numOfTables;
H
hzcheng 已提交
1405 1406 1407
  } else {
    numOfRes = 1;  // for count function, there is only one output.
  }
H
hjxilinx 已提交
1408 1409 1410
  
#endif

H
hzcheng 已提交
1411 1412 1413
  return tscLocalResultCommonBuilder(pSql, numOfRes);
}

H
hjxilinx 已提交
1414
int tscProcessRetrieveLocalMergeRsp(SSqlObj *pSql) {
H
hzcheng 已提交
1415 1416 1417
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;

1418
  pRes->code = tscDoLocalMerge(pSql);
H
hjxilinx 已提交
1419
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hzcheng 已提交
1420 1421

  if (pRes->code == TSDB_CODE_SUCCESS && pRes->numOfRows > 0) {
1422
    tscSetResultPointer(pQueryInfo, pRes);
H
hzcheng 已提交
1423 1424 1425
  }

  pRes->row = 0;
1426
  pRes->completed = (pRes->numOfRows == 0);
H
hzcheng 已提交
1427

1428
  int32_t code = pRes->code;
H
hjxilinx 已提交
1429 1430 1431 1432
  if (pRes->code == TSDB_CODE_SUCCESS) {
    (*pSql->fp)(pSql->param, pSql, pRes->numOfRows);
  } else {
    tscQueueAsyncRes(pSql);
H
hzcheng 已提交
1433 1434 1435 1436 1437
  }

  return code;
}

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

1440
int tscBuildConnectMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
H
hzcheng 已提交
1441
  STscObj *pObj = pSql->pTscObj;
S
slguan 已提交
1442
  SSqlCmd *pCmd = &pSql->cmd;
S
slguan 已提交
1443
  pCmd->msgType = TSDB_MSG_TYPE_CM_CONNECT;
1444
  pCmd->payloadLen = sizeof(SCMConnectMsg);
H
hzcheng 已提交
1445

S
slguan 已提交
1446 1447
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, pCmd->payloadLen)) {
    tscError("%p failed to malloc for query msg", pSql);
1448
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
1449 1450
  }

1451
  SCMConnectMsg *pConnect = (SCMConnectMsg*)pCmd->payload;
H
hzcheng 已提交
1452 1453 1454 1455 1456

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

1460
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1461 1462
}

H
hjxilinx 已提交
1463
int tscBuildTableMetaMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
1464
  SCMTableInfoMsg *pInfoMsg;
S
slguan 已提交
1465
  char *         pMsg;
H
hzcheng 已提交
1466 1467
  int            msgLen = 0;

B
Bomin Zhang 已提交
1468 1469 1470 1471
  char *tmpData = NULL;
  uint32_t len = pSql->cmd.payloadLen;
  if (len > 0) {
    tmpData = calloc(1, len);
1472
    if (NULL == tmpData) {
1473
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
1474 1475
    }

H
hzcheng 已提交
1476
    // STagData is in binary format, strncpy is not available
B
Bomin Zhang 已提交
1477
    memcpy(tmpData, pSql->cmd.payload, len);
H
hzcheng 已提交
1478 1479
  }

1480 1481 1482
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);

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

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

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

B
Bomin Zhang 已提交
1491 1492 1493
  if (pSql->cmd.autoCreated && len > 0) {
    memcpy(pInfoMsg->tags, tmpData, len);
    pMsg += len;
H
hzcheng 已提交
1494 1495
  }

H
hjxilinx 已提交
1496
  pCmd->payloadLen = pMsg - (char*)pInfoMsg;;
S
slguan 已提交
1497
  pCmd->msgType = TSDB_MSG_TYPE_CM_TABLE_META;
H
hzcheng 已提交
1498 1499 1500 1501

  tfree(tmpData);

  assert(msgLen + minMsgSize() <= pCmd->allocSize);
1502
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1503 1504
}

S
slguan 已提交
1505
/**
1506
 *  multi table meta req pkg format:
1507
 *  | SMgmtHead | SCMMultiTableInfoMsg | tableId0 | tableId1 | tableId2 | ......
S
slguan 已提交
1508 1509
 *      no used         4B
 **/
1510
int tscBuildMultiMeterMetaMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
guanshengliang's avatar
guanshengliang 已提交
1511
#if 0
S
slguan 已提交
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
  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 已提交
1524
  memset(pMgmt->db, 0, TSDB_TABLE_ID_LEN);  // server don't need the db
S
slguan 已提交
1525

1526
  SCMMultiTableInfoMsg *pInfoMsg = (SCMMultiTableInfoMsg *)(pCmd->payload + tsRpcHeadSize + sizeof(SMgmtHead));
S
slguan 已提交
1527
  pInfoMsg->numOfTables = htonl((int32_t)pCmd->count);
S
slguan 已提交
1528 1529

  if (pCmd->payloadLen > 0) {
S
slguan 已提交
1530
    memcpy(pInfoMsg->tableIds, tmpData, pCmd->payloadLen);
S
slguan 已提交
1531 1532 1533 1534
  }

  tfree(tmpData);

1535
  pCmd->payloadLen += sizeof(SMgmtHead) + sizeof(SCMMultiTableInfoMsg);
S
slguan 已提交
1536
  pCmd->msgType = TSDB_MSG_TYPE_CM_TABLES_META;
S
slguan 已提交
1537 1538 1539

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

S
slguan 已提交
1540
  tscTrace("%p build load multi-metermeta msg completed, numOfTables:%d, msg size:%d", pSql, pCmd->count,
S
slguan 已提交
1541 1542 1543
           pCmd->payloadLen);

  return pCmd->payloadLen;
guanshengliang's avatar
guanshengliang 已提交
1544 1545
#endif
  return 0;  
S
slguan 已提交
1546 1547
}

H
hjxilinx 已提交
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573
//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 已提交
1574

H
hjxilinx 已提交
1575 1576 1577
int tscBuildSTableVgroupMsg(SSqlObj *pSql, SSqlInfo *pInfo) {

#if 0
S
slguan 已提交
1578
  SSuperTableMetaMsg *pMetaMsg;
H
hzcheng 已提交
1579 1580
  char *          pMsg, *pStart;
  int             msgLen = 0;
S
slguan 已提交
1581
  int             tableIndex = 0;
H
hzcheng 已提交
1582

1583 1584 1585
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);

1586
  STagCond *pTagCond = &pQueryInfo->tagCond;
S
slguan 已提交
1587

H
hjxilinx 已提交
1588
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, tableIndex);
H
hzcheng 已提交
1589 1590

  int32_t size = tscEstimateMetricMetaMsgSize(pCmd);
S
slguan 已提交
1591 1592 1593 1594
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
    tscError("%p failed to malloc for metric meter msg", pSql);
    return -1;
  }
H
hzcheng 已提交
1595 1596 1597 1598 1599

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

  SMgmtHead *pMgmt = (SMgmtHead *)pMsg;
H
hjxilinx 已提交
1600
  tscGetDBInfoFromMeterId(pTableMetaInfo->name, pMgmt->db);
H
hzcheng 已提交
1601 1602 1603

  pMsg += sizeof(SMgmtHead);

S
slguan 已提交
1604
  pMetaMsg = (SSuperTableMetaMsg *)pMsg;
S
slguan 已提交
1605
  pMetaMsg->numOfTables = htonl(pQueryInfo->numOfTables);
S
slguan 已提交
1606

S
slguan 已提交
1607
  pMsg += sizeof(SSuperTableMetaMsg);
S
slguan 已提交
1608 1609 1610 1611 1612

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

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

S
slguan 已提交
1615
  memcpy(pMsg, pTagCond->joinInfo.left.tableId, TSDB_TABLE_ID_LEN);
S
slguan 已提交
1616
  pMsg += TSDB_TABLE_ID_LEN;
H
hzcheng 已提交
1617

S
slguan 已提交
1618 1619 1620
  *(int16_t *)pMsg = pTagCond->joinInfo.left.tagCol;
  pMsg += sizeof(int16_t);

S
slguan 已提交
1621
  memcpy(pMsg, pTagCond->joinInfo.right.tableId, TSDB_TABLE_ID_LEN);
S
slguan 已提交
1622
  pMsg += TSDB_TABLE_ID_LEN;
S
slguan 已提交
1623 1624 1625 1626

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

1627
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
1628
    pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, i);
H
hjxilinx 已提交
1629
    uint64_t uid = pTableMetaInfo->pTableMeta->uid;
S
slguan 已提交
1630 1631 1632 1633

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

S
slguan 已提交
1634 1635
    SSuperTableMetaElemMsg *pElem = (SSuperTableMetaElemMsg *)pMsg;
    pMsg += sizeof(SSuperTableMetaElemMsg);
S
slguan 已提交
1636 1637 1638 1639

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

H
hjxilinx 已提交
1644
        bool ret = taosMbsToUcs4(pCond->cond, condLen, pMsg, condLen * TSDB_NCHAR_SIZE);
S
slguan 已提交
1645
        if (!ret) {
1646
          tscError("%p mbs to ucs4 failed:%s", pSql, tsGetSTableQueryCond(pTagCond, uid));
S
slguan 已提交
1647 1648 1649
          return 0;
        }
      }
H
hzcheng 已提交
1650 1651
    }

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

S
slguan 已提交
1654 1655 1656
    offset = pMsg - (char *)pMetaMsg;
    pElem->cond = htonl(offset);
    pMsg += condLen * TSDB_NCHAR_SIZE;
H
hzcheng 已提交
1657

S
slguan 已提交
1658 1659 1660
    pElem->rel = htons(pTagCond->relType);
    if (pTagCond->tbnameCond.uid == uid) {
      offset = pMsg - (char *)pMetaMsg;
H
hzcheng 已提交
1661

S
slguan 已提交
1662
      pElem->tableCond = htonl(offset);
H
hjxilinx 已提交
1663 1664 1665 1666 1667 1668 1669
      
      uint32_t len = 0;
      if (pTagCond->tbnameCond.cond != NULL) {
        len = strlen(pTagCond->tbnameCond.cond);
        memcpy(pMsg, pTagCond->tbnameCond.cond, len);
      }
      
H
hjxilinx 已提交
1670 1671
      pElem->tableCondLen = htonl(len);
      pMsg += len;
S
slguan 已提交
1672 1673
    }

1674
    SSqlGroupbyExpr *pGroupby = &pQueryInfo->groupbyExpr;
S
slguan 已提交
1675

H
hjxilinx 已提交
1676
    if (pGroupby->tableIndex != i && pGroupby->numOfGroupCols > 0) {
S
slguan 已提交
1677 1678 1679 1680 1681
      pElem->orderType = 0;
      pElem->orderIndex = 0;
      pElem->numOfGroupCols = 0;
    } else {
      pElem->numOfGroupCols = htons(pGroupby->numOfGroupCols);
H
hjxilinx 已提交
1682 1683
      for (int32_t j = 0; j < pTableMetaInfo->numOfTags; ++j) {
        pElem->tagCols[j] = htons(pTableMetaInfo->tagColumnIndex[j]);
S
slguan 已提交
1684 1685 1686 1687 1688 1689 1690 1691
      }

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

        pElem->groupbyTagColumnList = htonl(offset);
1692
        for (int32_t j = 0; j < pQueryInfo->groupbyExpr.numOfGroupCols; ++j) {
1693 1694
          SColIndex *pCol = &pQueryInfo->groupbyExpr.columnInfo[j];
          SColIndex *pDestCol = (SColIndex *)pMsg;
1695

H
hjxilinx 已提交
1696
          pDestCol->colIdxInBuf = 0;
1697
          pDestCol->colIndex = htons(pCol->colIndex);
H
hjxilinx 已提交
1698 1699
          pDestCol->colId = htons(pDestCol->colId);
          pDestCol->flag = htons(pDestCol->flag);
H
hjxilinx 已提交
1700
          strncpy(pDestCol->name, pCol->name, tListLen(pCol->name));
1701

1702
          pMsg += sizeof(SColIndex);
S
slguan 已提交
1703 1704
        }
      }
H
hzcheng 已提交
1705
    }
S
slguan 已提交
1706

H
hjxilinx 已提交
1707 1708
    strcpy(pElem->tableId, pTableMetaInfo->name);
    pElem->numOfTags = htons(pTableMetaInfo->numOfTags);
S
slguan 已提交
1709 1710 1711

    int16_t len = pMsg - (char *)pElem;
    pElem->elemLen = htons(len);  // redundant data for integrate check
H
hzcheng 已提交
1712 1713 1714 1715
  }

  msgLen = pMsg - pStart;
  pCmd->payloadLen = msgLen;
S
slguan 已提交
1716
  pCmd->msgType = TSDB_MSG_TYPE_CM_STABLE_VGROUP;
H
hzcheng 已提交
1717
  assert(msgLen + minMsgSize() <= size);
H
hjxilinx 已提交
1718
#endif
1719
  
H
hjxilinx 已提交
1720
  SSqlCmd *pCmd = &pSql->cmd;
H
hjxilinx 已提交
1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
  
  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 已提交
1734 1735

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

1738
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1739 1740
}

1741 1742
int tscBuildHeartBeatMsg(SSqlObj *pSql, SSqlInfo *pInfo) {
  SSqlCmd *pCmd = &pSql->cmd;
H
hzcheng 已提交
1743 1744
  STscObj *pObj = pSql->pTscObj;

1745
  pthread_mutex_lock(&pObj->mutex);
H
hzcheng 已提交
1746

S
Shengliang Guan 已提交
1747
  int32_t numOfQueries = 2;
H
hzcheng 已提交
1748 1749 1750
  SSqlObj *tpSql = pObj->sqlList;
  while (tpSql) {
    tpSql = tpSql->next;
1751
    numOfQueries++;
H
hzcheng 已提交
1752 1753
  }

S
Shengliang Guan 已提交
1754
  int32_t numOfStreams = 2;
H
hzcheng 已提交
1755 1756 1757
  SSqlStream *pStream = pObj->streamList;
  while (pStream) {
    pStream = pStream->next;
1758
    numOfStreams++;
H
hzcheng 已提交
1759 1760
  }

1761
  int size = numOfQueries * sizeof(SQueryDesc) + numOfStreams * sizeof(SStreamDesc) + sizeof(SCMHeartBeatMsg) + 100;
S
slguan 已提交
1762
  if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, size)) {
1763
    pthread_mutex_unlock(&pObj->mutex);
S
slguan 已提交
1764 1765 1766
    tscError("%p failed to malloc for heartbeat msg", pSql);
    return -1;
  }
H
hzcheng 已提交
1767

1768
  SCMHeartBeatMsg *pHeartbeat = (SCMHeartBeatMsg *)pCmd->payload;
1769 1770
  pHeartbeat->numOfQueries = numOfQueries;
  pHeartbeat->numOfStreams = numOfStreams;
1771
  int msgLen = tscBuildQueryStreamDesc(pHeartbeat, pObj);
H
hzcheng 已提交
1772 1773 1774

  pthread_mutex_unlock(&pObj->mutex);

1775
  pCmd->payloadLen = msgLen;
S
slguan 已提交
1776
  pCmd->msgType = TSDB_MSG_TYPE_CM_HEARTBEAT;
H
hzcheng 已提交
1777

1778
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1779 1780
}

1781 1782
int tscProcessTableMetaRsp(SSqlObj *pSql) {
  STableMetaMsg *pMetaMsg = (STableMetaMsg *)pSql->res.pRsp;
H
hzcheng 已提交
1783

1784 1785
  pMetaMsg->sid = htonl(pMetaMsg->sid);
  pMetaMsg->sversion = htons(pMetaMsg->sversion);
1786
  pMetaMsg->tversion = htons(pMetaMsg->tversion);
H
hjxilinx 已提交
1787 1788
  pMetaMsg->vgroup.vgId = htonl(pMetaMsg->vgroup.vgId);
  
1789 1790
  pMetaMsg->uid = htobe64(pMetaMsg->uid);
  pMetaMsg->contLen = htons(pMetaMsg->contLen);
1791
  pMetaMsg->numOfColumns = htons(pMetaMsg->numOfColumns);
H
hzcheng 已提交
1792

H
hjxilinx 已提交
1793 1794
  if (pMetaMsg->sid < 0 || pMetaMsg->vgroup.numOfIps < 0) {
    tscError("invalid meter vgId:%d, sid%d", pMetaMsg->vgroup.numOfIps, pMetaMsg->sid);
1795
    return TSDB_CODE_TSC_INVALID_VALUE;
H
hzcheng 已提交
1796 1797
  }

1798 1799
  if (pMetaMsg->numOfTags > TSDB_MAX_TAGS || pMetaMsg->numOfTags < 0) {
    tscError("invalid numOfTags:%d", pMetaMsg->numOfTags);
1800
    return TSDB_CODE_TSC_INVALID_VALUE;
H
hzcheng 已提交
1801 1802
  }

1803 1804
  if (pMetaMsg->numOfColumns > TSDB_MAX_COLUMNS || pMetaMsg->numOfColumns <= 0) {
    tscError("invalid numOfColumns:%d", pMetaMsg->numOfColumns);
1805
    return TSDB_CODE_TSC_INVALID_VALUE;
H
hzcheng 已提交
1806 1807
  }

H
hjxilinx 已提交
1808 1809
  for (int i = 0; i < pMetaMsg->vgroup.numOfIps; ++i) {
    pMetaMsg->vgroup.ipAddr[i].port = htons(pMetaMsg->vgroup.ipAddr[i].port);
H
hzcheng 已提交
1810 1811
  }

1812
  SSchema* pSchema = pMetaMsg->schema;
H
hzcheng 已提交
1813

1814
  int32_t numOfTotalCols = pMetaMsg->numOfColumns + pMetaMsg->numOfTags;
H
hzcheng 已提交
1815 1816 1817
  for (int i = 0; i < numOfTotalCols; ++i) {
    pSchema->bytes = htons(pSchema->bytes);
    pSchema->colId = htons(pSchema->colId);
H
hjxilinx 已提交
1818 1819
    
    assert(pSchema->type >= TSDB_DATA_TYPE_BOOL && pSchema->type <= TSDB_DATA_TYPE_NCHAR);
H
hzcheng 已提交
1820 1821 1822
    pSchema++;
  }

1823 1824
  size_t size = 0;
  STableMeta* pTableMeta = tscCreateTableMetaFromMsg(pMetaMsg, &size);
1825
  
H
hzcheng 已提交
1826
  // todo add one more function: taosAddDataIfNotExists();
1827
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
H
hjxilinx 已提交
1828
  assert(pTableMetaInfo->pTableMeta == NULL);
H
hzcheng 已提交
1829

H
hjxilinx 已提交
1830
  pTableMetaInfo->pTableMeta =
H
hjxilinx 已提交
1831
      (STableMeta *) taosCachePut(tscCacheHandle, pTableMetaInfo->name, pTableMeta, size, tsTableMetaKeepTimer);
H
hjxilinx 已提交
1832
  
1833
  // todo handle out of memory case
1834
  if (pTableMetaInfo->pTableMeta == NULL) {
1835
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
1836
  }
H
hzcheng 已提交
1837

H
Haojun Liao 已提交
1838
  tscTrace("%p recv table meta: %"PRId64 ", tid:%d, name:%s", pSql, pTableMeta->uid, pTableMeta->sid, pTableMetaInfo->name);
1839
  free(pTableMeta);
1840
  
H
hjxilinx 已提交
1841
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1842 1843
}

S
slguan 已提交
1844
/**
1845
 *  multi table meta rsp pkg format:
1846
 *  | STaosRsp | ieType | SCMMultiTableInfoMsg | SMeterMeta0 | SSchema0 | SMeterMeta1 | SSchema1 | SMeterMeta2 | SSchema2
S
slguan 已提交
1847 1848 1849
 *  |...... 1B        1B            4B
 **/
int tscProcessMultiMeterMetaRsp(SSqlObj *pSql) {
1850
#if 0
S
slguan 已提交
1851 1852 1853 1854 1855
  char *rsp = pSql->res.pRsp;

  ieType = *rsp;
  if (ieType != TSDB_IE_TYPE_META) {
    tscError("invalid ie type:%d", ieType);
1856
    pSql->res.code = TSDB_CODE_TSC_INVALID_IE;
S
slguan 已提交
1857
    pSql->res.numOfTotal = 0;
1858
    return TSDB_CODE_TSC_APP_ERROR;
S
slguan 已提交
1859 1860 1861 1862
  }

  rsp++;

1863
  SCMMultiTableInfoMsg *pInfo = (SCMMultiTableInfoMsg *)rsp;
S
slguan 已提交
1864
  totalNum = htonl(pInfo->numOfTables);
1865
  rsp += sizeof(SCMMultiTableInfoMsg);
S
slguan 已提交
1866 1867

  for (i = 0; i < totalNum; i++) {
S
slguan 已提交
1868
    SMultiTableMeta *pMultiMeta = (SMultiTableMeta *)rsp;
1869
    STableMeta *     pMeta = pMultiMeta->metas;
S
slguan 已提交
1870 1871 1872

    pMeta->sid = htonl(pMeta->sid);
    pMeta->sversion = htons(pMeta->sversion);
H
hjxilinx 已提交
1873
    pMeta->vgId = htonl(pMeta->vgId);
S
slguan 已提交
1874 1875
    pMeta->uid = htobe64(pMeta->uid);

H
hjxilinx 已提交
1876 1877
    if (pMeta->sid <= 0 || pMeta->vgId < 0) {
      tscError("invalid meter vgId:%d, sid%d", pMeta->vgId, pMeta->sid);
1878
      pSql->res.code = TSDB_CODE_TSC_INVALID_VALUE;
S
slguan 已提交
1879
      pSql->res.numOfTotal = i;
1880
      return TSDB_CODE_TSC_APP_ERROR;
S
slguan 已提交
1881 1882
    }

H
hjxilinx 已提交
1883 1884 1885 1886
    //    pMeta->numOfColumns = htons(pMeta->numOfColumns);
    //
    //    if (pMeta->numOfTags > TSDB_MAX_TAGS || pMeta->numOfTags < 0) {
    //      tscError("invalid tag value count:%d", pMeta->numOfTags);
1887
    //      pSql->res.code = TSDB_CODE_TSC_INVALID_VALUE;
H
hjxilinx 已提交
1888
    //      pSql->res.numOfTotal = i;
1889
    //      return TSDB_CODE_TSC_APP_ERROR;
H
hjxilinx 已提交
1890 1891 1892 1893
    //    }
    //
    //    if (pMeta->numOfTags > TSDB_MAX_TAGS || pMeta->numOfTags < 0) {
    //      tscError("invalid numOfTags:%d", pMeta->numOfTags);
1894
    //      pSql->res.code = TSDB_CODE_TSC_INVALID_VALUE;
H
hjxilinx 已提交
1895
    //      pSql->res.numOfTotal = i;
1896
    //      return TSDB_CODE_TSC_APP_ERROR;
H
hjxilinx 已提交
1897 1898 1899 1900
    //    }
    //
    //    if (pMeta->numOfColumns > TSDB_MAX_COLUMNS || pMeta->numOfColumns < 0) {
    //      tscError("invalid numOfColumns:%d", pMeta->numOfColumns);
1901
    //      pSql->res.code = TSDB_CODE_TSC_INVALID_VALUE;
H
hjxilinx 已提交
1902
    //      pSql->res.numOfTotal = i;
1903
    //      return TSDB_CODE_TSC_APP_ERROR;
H
hjxilinx 已提交
1904 1905
    //    }
    //
H
hjxilinx 已提交
1906
    //    for (int j = 0; j < TSDB_REPLICA_MAX_NUM; ++j) {
H
hjxilinx 已提交
1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
    //      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 已提交
1941
    //    (void)taosCachePut(tscCacheHandle, pMeta->tableId, (char *)pMeta, size, tsTableMetaKeepTimer);
H
hjxilinx 已提交
1942
    //  }
S
slguan 已提交
1943
  }
H
hjxilinx 已提交
1944
  
S
slguan 已提交
1945 1946
  pSql->res.code = TSDB_CODE_SUCCESS;
  pSql->res.numOfTotal = i;
H
Haojun Liao 已提交
1947
  tscTrace("%p load multi-metermeta resp from complete num:%d", pSql, pSql->res.numOfTotal);
1948 1949
#endif
  
S
slguan 已提交
1950 1951 1952
  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
1953 1954
int tscProcessSTableVgroupRsp(SSqlObj *pSql) {
#if 0
S
slguan 已提交
1955 1956
  void **      metricMetaList = NULL;
  int32_t *    sizes = NULL;
H
hjxilinx 已提交
1957
  
S
slguan 已提交
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
  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);
1968
    pSql->res.code = TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
1969 1970 1971 1972 1973

    return pSql->res.code;
  }

  for (int32_t k = 0; k < num; ++k) {
S
slguan 已提交
1974
    pMeta = (SSuperTableMeta *)rsp;
S
slguan 已提交
1975 1976

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

S
slguan 已提交
1979
    pMeta->numOfTables = htonl(pMeta->numOfTables);
S
slguan 已提交
1980 1981 1982
    pMeta->numOfVnodes = htonl(pMeta->numOfVnodes);
    pMeta->tagLen = htons(pMeta->tagLen);

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

1985 1986
    char *pBuf = calloc(1, size);
    if (pBuf == NULL) {
1987
      pSql->res.code = TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
1988 1989
      goto _error_clean;
    }
H
hzcheng 已提交
1990

S
slguan 已提交
1991
    SSuperTableMeta *pNewMetricMeta = (SSuperTableMeta *)pBuf;
S
slguan 已提交
1992
    metricMetaList[k] = pNewMetricMeta;
H
hzcheng 已提交
1993

S
slguan 已提交
1994
    pNewMetricMeta->numOfTables = pMeta->numOfTables;
S
slguan 已提交
1995 1996
    pNewMetricMeta->numOfVnodes = pMeta->numOfVnodes;
    pNewMetricMeta->tagLen = pMeta->tagLen;
H
hzcheng 已提交
1997

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

S
slguan 已提交
2000 2001
    for (int32_t i = 0; i < pMeta->numOfVnodes; ++i) {
      SVnodeSidList *pSidLists = (SVnodeSidList *)rsp;
2002
      memcpy(pBuf, pSidLists, sizeof(SVnodeSidList));
H
hzcheng 已提交
2003

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

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

2009
      pBuf += sizeof(SVnodeSidList) + sizeof(STableIdInfo *) * pSidLists->numOfSids;
S
slguan 已提交
2010
      rsp += sizeof(SVnodeSidList);
H
hzcheng 已提交
2011

2012
      size_t elemSize = sizeof(STableIdInfo) + pNewMetricMeta->tagLen;
S
slguan 已提交
2013
      for (int32_t j = 0; j < pSidLists->numOfSids; ++j) {
2014 2015
        pLists->pSidExtInfoList[j] = pBuf - (char *)pLists;
        memcpy(pBuf, rsp, elemSize);
2016

2017 2018
        ((STableIdInfo *)pBuf)->uid = htobe64(((STableIdInfo *)pBuf)->uid);
        ((STableIdInfo *)pBuf)->sid = htonl(((STableIdInfo *)pBuf)->sid);
2019

2020 2021
        rsp += elemSize;
        pBuf += elemSize;
S
slguan 已提交
2022
      }
H
hzcheng 已提交
2023
    }
S
slguan 已提交
2024

2025
    sizes[k] = pBuf - (char *)pNewMetricMeta;
H
hzcheng 已提交
2026 2027
  }

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

H
hjxilinx 已提交
2032
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, i);
H
hjxilinx 已提交
2033
    tscGetMetricMetaCacheKey(pQueryInfo, name, pTableMetaInfo->pTableMeta->uid);
H
hzcheng 已提交
2034

S
slguan 已提交
2035 2036 2037
#ifdef _DEBUG_VIEW
    printf("generate the metric key:%s, index:%d\n", name, i);
#endif
H
hzcheng 已提交
2038

S
slguan 已提交
2039
    // release the used metricmeta
H
hjxilinx 已提交
2040 2041
    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pMetricMeta), false);
    pTableMetaInfo->pMetricMeta = (SSuperTableMeta *)taosCachePut(tscCacheHandle, name, (char *)metricMetaList[i],
S
slguan 已提交
2042 2043 2044 2045
                                                                      sizes[i], tsMetricMetaKeepTimer);
    tfree(metricMetaList[i]);

    // failed to put into cache
H
hjxilinx 已提交
2046
    if (pTableMetaInfo->pMetricMeta == NULL) {
2047
      pSql->res.code = TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
2048 2049
      goto _error_clean;
    }
H
hzcheng 已提交
2050 2051
  }

S
slguan 已提交
2052 2053 2054 2055 2056 2057 2058 2059
_error_clean:
  // free allocated resource
  for (int32_t i = 0; i < num; ++i) {
    tfree(metricMetaList[i]);
  }

  free(sizes);
  free(metricMetaList);
H
hjxilinx 已提交
2060
#endif
2061
  SSqlRes* pRes = &pSql->res;
H
hjxilinx 已提交
2062
  
H
hjxilinx 已提交
2063
  // NOTE: the order of several table must be preserved.
2064
  SCMSTableVgroupRspMsg *pStableVgroup = (SCMSTableVgroupRspMsg *)pRes->pRsp;
H
hjxilinx 已提交
2065 2066
  pStableVgroup->numOfTables = htonl(pStableVgroup->numOfTables);
  char* pMsg = pRes->pRsp + sizeof(SCMSTableVgroupRspMsg);
H
hjxilinx 已提交
2067
  
2068 2069 2070
  // master sqlObj locates in param
  SSqlObj* parent = pSql->param;
  assert(parent != NULL);
H
hjxilinx 已提交
2071
  
2072
  SSqlCmd* pCmd = &parent->cmd;
H
hjxilinx 已提交
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093
  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;
2094
    }
H
hjxilinx 已提交
2095 2096
  }
  
S
slguan 已提交
2097
  return pSql->res.code;
H
hzcheng 已提交
2098 2099 2100 2101 2102 2103
}

/*
 * current process do not use the cache at all
 */
int tscProcessShowRsp(SSqlObj *pSql) {
H
hjxilinx 已提交
2104
  STableMetaMsg * pMetaMsg;
2105
  SCMShowRsp *pShow;
S
slguan 已提交
2106
  SSchema *    pSchema;
H
hzcheng 已提交
2107 2108
  char         key[20];

2109 2110 2111
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;

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

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

2116
  pShow = (SCMShowRsp *)pRes->pRsp;
S
slguan 已提交
2117
  pShow->qhandle = htobe64(pShow->qhandle);
H
hzcheng 已提交
2118 2119
  pRes->qhandle = pShow->qhandle;

S
slguan 已提交
2120
  tscResetForNextRetrieve(pRes);
H
hjxilinx 已提交
2121
  pMetaMsg = &(pShow->tableMeta);
H
hzcheng 已提交
2122

H
hjxilinx 已提交
2123
  pMetaMsg->numOfColumns = ntohs(pMetaMsg->numOfColumns);
H
hzcheng 已提交
2124

H
hjxilinx 已提交
2125
  pSchema = pMetaMsg->schema;
H
hjxilinx 已提交
2126 2127
  pMetaMsg->sid = ntohs(pMetaMsg->sid);
  for (int i = 0; i < pMetaMsg->numOfColumns; ++i) {
H
hzcheng 已提交
2128 2129 2130 2131
    pSchema->bytes = htons(pSchema->bytes);
    pSchema++;
  }

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

H
hjxilinx 已提交
2135
  taosCacheRelease(tscCacheHandle, (void *)&(pTableMetaInfo->pTableMeta), false);
H
hjxilinx 已提交
2136
  
H
hjxilinx 已提交
2137 2138 2139
  size_t size = 0;
  STableMeta* pTableMeta = tscCreateTableMetaFromMsg(pMetaMsg, &size);
  
H
hjxilinx 已提交
2140
  pTableMetaInfo->pTableMeta = taosCachePut(tscCacheHandle, key, (char *)pTableMeta, size, tsTableMetaKeepTimer);
H
hjxilinx 已提交
2141
  SSchema *pTableSchema = tscGetTableSchema(pTableMetaInfo->pTableMeta);
H
hzcheng 已提交
2142

2143 2144 2145 2146
  if (pQueryInfo->colList == NULL) {
    pQueryInfo->colList = taosArrayInit(4, POINTER_BYTES);
  }
  
H
hjxilinx 已提交
2147 2148
  SFieldInfo* pFieldInfo = &pQueryInfo->fieldsInfo;
  
S
slguan 已提交
2149
  SColumnIndex index = {0};
H
hjxilinx 已提交
2150 2151 2152
  pSchema = pMetaMsg->schema;
  
  for (int16_t i = 0; i < pMetaMsg->numOfColumns; ++i, ++pSchema) {
S
slguan 已提交
2153
    index.columnIndex = i;
2154 2155
    tscColumnListInsert(pQueryInfo->colList, &index);
    
H
hjxilinx 已提交
2156 2157
    TAOS_FIELD f = tscCreateField(pSchema->type, pSchema->name, pSchema->bytes);
    SFieldSupInfo* pInfo = tscFieldInfoAppend(pFieldInfo, &f);
H
hjxilinx 已提交
2158
    
H
hjxilinx 已提交
2159
    pInfo->pSqlExpr = tscSqlExprAppend(pQueryInfo, TSDB_FUNC_TS_DUMMY, &index,
2160
                     pTableSchema[i].type, pTableSchema[i].bytes, pTableSchema[i].bytes, false);
H
hzcheng 已提交
2161
  }
H
hjxilinx 已提交
2162 2163
  
  pCmd->numOfCols = pQueryInfo->fieldsInfo.numOfOutput;
H
hjxilinx 已提交
2164
  tscFieldInfoUpdateOffset(pQueryInfo);
H
hjxilinx 已提交
2165 2166
  
  tfree(pTableMeta);
H
hzcheng 已提交
2167 2168 2169 2170
  return 0;
}

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

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

H
hjxilinx 已提交
2179 2180 2181
  assert(len <= tListLen(pObj->db));
  strncpy(pObj->db, temp, tListLen(pObj->db));
  
2182 2183
  if (pConnect->ipList.numOfIps > 0) 
    tscSetMgmtIpList(&pConnect->ipList);
H
hzcheng 已提交
2184

S
slguan 已提交
2185
  strcpy(pObj->sversion, pConnect->serverVersion);
H
hzcheng 已提交
2186 2187
  pObj->writeAuth = pConnect->writeAuth;
  pObj->superAuth = pConnect->superAuth;
S
Shengliang Guan 已提交
2188
  pObj->connId = htonl(pConnect->connId);
S
scripts  
slguan 已提交
2189
  taosTmrReset(tscProcessActivityTimer, tsShellActivityTimer * 500, pObj, tscTmr, &pObj->pTimer);
H
hzcheng 已提交
2190 2191 2192 2193 2194

  return 0;
}

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

H
hjxilinx 已提交
2198
  strcpy(pObj->db, pTableMetaInfo->name);
H
hzcheng 已提交
2199 2200 2201 2202
  return 0;
}

int tscProcessDropDbRsp(SSqlObj *UNUSED_PARAM(pSql)) {
2203
  taosCacheEmpty(tscCacheHandle);
H
hzcheng 已提交
2204 2205 2206 2207
  return 0;
}

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

H
hjxilinx 已提交
2210 2211
  STableMeta *pTableMeta = taosCacheAcquireByName(tscCacheHandle, pTableMetaInfo->name);
  if (pTableMeta == NULL) {
H
hzcheng 已提交
2212 2213 2214 2215 2216 2217 2218 2219
    /* 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 已提交
2220 2221
   * The cached information is expired, however, we may have lost the ref of original meter. So, clear whole cache
   * instead.
H
hzcheng 已提交
2222
   */
H
hjxilinx 已提交
2223 2224
  tscTrace("%p force release metermeta after drop table:%s", pSql, pTableMetaInfo->name);
  taosCacheRelease(tscCacheHandle, (void **)&pTableMeta, true);
H
hzcheng 已提交
2225

H
hjxilinx 已提交
2226 2227
  if (pTableMetaInfo->pTableMeta) {
    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pTableMeta), true);
H
hzcheng 已提交
2228 2229 2230 2231 2232 2233
  }

  return 0;
}

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

H
hjxilinx 已提交
2236 2237
  STableMeta *pTableMeta = taosCacheAcquireByName(tscCacheHandle, pTableMetaInfo->name);
  if (pTableMeta == NULL) { /* not in cache, abort */
H
hzcheng 已提交
2238 2239 2240
    return 0;
  }

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

H
hjxilinx 已提交
2244
  if (pTableMetaInfo->pTableMeta) {
weixin_48148422's avatar
weixin_48148422 已提交
2245
    bool isSuperTable = UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo);
H
hzcheng 已提交
2246

H
hjxilinx 已提交
2247
    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pTableMeta), true);
H
hjxilinx 已提交
2248
//    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pMetricMeta), true);
H
hzcheng 已提交
2249

2250
    if (isSuperTable) {  // if it is a super table, reset whole query cache
H
hjxilinx 已提交
2251
      tscTrace("%p reset query cache since table:%s is stable", pSql, pTableMetaInfo->name);
2252
      taosCacheEmpty(tscCacheHandle);
H
hzcheng 已提交
2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
    }
  }

  return 0;
}

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

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

2267
  SQueryTableRsp *pQuery = (SQueryTableRsp *)pRes->pRsp;
S
slguan 已提交
2268 2269 2270
  pQuery->qhandle = htobe64(pQuery->qhandle);
  pRes->qhandle = pQuery->qhandle;

H
hzcheng 已提交
2271
  pRes->data = NULL;
S
slguan 已提交
2272
  tscResetForNextRetrieve(pRes);
H
hzcheng 已提交
2273 2274 2275
  return 0;
}

H
hjxilinx 已提交
2276
int tscProcessRetrieveRspFromNode(SSqlObj *pSql) {
S
slguan 已提交
2277 2278 2279
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;

S
slguan 已提交
2280
  SRetrieveTableRsp *pRetrieve = (SRetrieveTableRsp *)pRes->pRsp;
H
hzcheng 已提交
2281 2282 2283

  pRes->numOfRows = htonl(pRetrieve->numOfRows);
  pRes->precision = htons(pRetrieve->precision);
2284 2285
  pRes->offset    = htobe64(pRetrieve->offset);
  pRes->useconds  = htobe64(pRetrieve->useconds);
H
hjxilinx 已提交
2286
  pRes->completed = (pRetrieve->completed == 1);
2287
  pRes->data      = pRetrieve->data;
H
hjxilinx 已提交
2288
  
2289
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
2290 2291 2292 2293
  if (tscCreateResPointerInfo(pRes, pQueryInfo) != TSDB_CODE_SUCCESS) {
    return pRes->code;
  }
  
weixin_48148422's avatar
weixin_48148422 已提交
2294
  if (pSql->pSubscription != NULL) {
H
hjxilinx 已提交
2295
    int32_t numOfCols = pQueryInfo->fieldsInfo.numOfOutput;
H
hjxilinx 已提交
2296
    
H
hjxilinx 已提交
2297
    TAOS_FIELD *pField = tscFieldInfoGetField(&pQueryInfo->fieldsInfo, numOfCols - 1);
H
hjxilinx 已提交
2298 2299
    int16_t     offset = tscFieldInfoGetOffset(pQueryInfo, numOfCols - 1);
    
weixin_48148422's avatar
weixin_48148422 已提交
2300 2301
    char* p = pRes->data + (pField->bytes + offset) * pRes->numOfRows;

S
slguan 已提交
2302
    int32_t numOfTables = htonl(*(int32_t*)p);
weixin_48148422's avatar
weixin_48148422 已提交
2303
    p += sizeof(int32_t);
S
slguan 已提交
2304
    for (int i = 0; i < numOfTables; i++) {
weixin_48148422's avatar
weixin_48148422 已提交
2305 2306
      int64_t uid = htobe64(*(int64_t*)p);
      p += sizeof(int64_t);
weixin_48148422's avatar
weixin_48148422 已提交
2307
      p += sizeof(int32_t); // skip tid
weixin_48148422's avatar
weixin_48148422 已提交
2308 2309
      TSKEY key = htobe64(*(TSKEY*)p);
      p += sizeof(TSKEY);
2310
      tscUpdateSubscriptionProgress(pSql->pSubscription, uid, key);
weixin_48148422's avatar
weixin_48148422 已提交
2311
    }
2312 2313
  }

H
hzcheng 已提交
2314
  pRes->row = 0;
S
slguan 已提交
2315
  tscTrace("%p numOfRows:%d, offset:%d", pSql, pRes->numOfRows, pRes->offset);
H
hzcheng 已提交
2316 2317 2318 2319 2320

  return 0;
}

int tscProcessRetrieveRspFromLocal(SSqlObj *pSql) {
2321 2322
  SSqlRes *   pRes = &pSql->res;
  SSqlCmd *   pCmd = &pSql->cmd;
2323
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
2324

S
slguan 已提交
2325
  SRetrieveTableRsp *pRetrieve = (SRetrieveTableRsp *)pRes->pRsp;
H
hzcheng 已提交
2326 2327 2328

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

2330
  tscSetResultPointer(pQueryInfo, pRes);
H
hzcheng 已提交
2331 2332 2333 2334
  pRes->row = 0;
  return 0;
}

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

2337
static int32_t getTableMetaFromMgmt(SSqlObj *pSql, STableMetaInfo *pTableMetaInfo) {
S
slguan 已提交
2338 2339
  SSqlObj *pNew = calloc(1, sizeof(SSqlObj));
  if (NULL == pNew) {
2340
    tscError("%p malloc failed for new sqlobj to get table meta", pSql);
2341
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
2342
  }
2343

H
hzcheng 已提交
2344 2345 2346
  pNew->pTscObj = pSql->pTscObj;
  pNew->signature = pNew;
  pNew->cmd.command = TSDB_SQL_META;
S
slguan 已提交
2347

2348
  tscAddSubqueryInfo(&pNew->cmd);
2349 2350 2351 2352

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

H
hjxilinx 已提交
2353
  pNew->cmd.autoCreated = pSql->cmd.autoCreated;  // create table if not exists
B
Bomin Zhang 已提交
2354
  if (TSDB_CODE_SUCCESS != tscAllocPayload(&pNew->cmd, TSDB_DEFAULT_PAYLOAD_SIZE + pSql->cmd.payloadLen)) {
2355
    tscError("%p malloc failed for payload to get table meta", pSql);
S
slguan 已提交
2356
    free(pNew);
2357

2358
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
2359 2360
  }

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

2364
  strncpy(pNewMeterMetaInfo->name, pTableMetaInfo->name, tListLen(pNewMeterMetaInfo->name));
B
Bomin Zhang 已提交
2365 2366
  memcpy(pNew->cmd.payload, pSql->cmd.payload, pSql->cmd.payloadLen);  // tag information if table does not exists.
  pNew->cmd.payloadLen = pSql->cmd.payloadLen;
2367
  tscTrace("%p new pSqlObj:%p to get tableMeta, auto create:%d", pSql, pNew, pNew->cmd.autoCreated);
H
hzcheng 已提交
2368

H
hjxilinx 已提交
2369 2370
  pNew->fp = tscTableMetaCallBack;
  pNew->param = pSql;
H
hzcheng 已提交
2371

H
hjxilinx 已提交
2372 2373
  int32_t code = tscProcessSql(pNew);
  if (code == TSDB_CODE_SUCCESS) {
2374
    code = TSDB_CODE_TSC_ACTION_IN_PROGRESS;
H
hzcheng 已提交
2375 2376 2377 2378 2379
  }

  return code;
}

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

2383
  // If this STableMetaInfo owns a table meta, release it first
H
hjxilinx 已提交
2384 2385
  if (pTableMetaInfo->pTableMeta != NULL) {
    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pTableMeta), false);
2386 2387
  }
  
H
hjxilinx 已提交
2388 2389
  pTableMetaInfo->pTableMeta = (STableMeta *)taosCacheAcquireByName(tscCacheHandle, pTableMetaInfo->name);
  if (pTableMetaInfo->pTableMeta != NULL) {
H
hjxilinx 已提交
2390
    STableComInfo tinfo = tscGetTableInfo(pTableMetaInfo->pTableMeta);
2391 2392
    tscTrace("%p retrieve table Meta from cache, the number of columns:%d, numOfTags:%d, %p", pSql, tinfo.numOfColumns,
             tinfo.numOfTags, pTableMetaInfo->pTableMeta);
H
hzcheng 已提交
2393 2394 2395

    return TSDB_CODE_SUCCESS;
  }
2396 2397
  
  return getTableMetaFromMgmt(pSql, pTableMetaInfo);
H
hzcheng 已提交
2398 2399
}

H
hjxilinx 已提交
2400
int tscGetMeterMetaEx(SSqlObj *pSql, STableMetaInfo *pTableMetaInfo, bool createIfNotExists) {
H
hjxilinx 已提交
2401
  pSql->cmd.autoCreated = createIfNotExists;
H
hjxilinx 已提交
2402
  return tscGetTableMeta(pSql, pTableMetaInfo);
H
hzcheng 已提交
2403 2404 2405 2406
}

/*
 * in handling the renew metermeta problem during insertion,
S
slguan 已提交
2407
 *
H
hzcheng 已提交
2408 2409 2410 2411 2412
 * 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 已提交
2413
  if (pCmd->command == TSDB_SQL_INSERT) {
H
hzcheng 已提交
2414 2415 2416 2417 2418 2419 2420
    taosMsleep(50);  // todo: global config
  }
}

/**
 * in renew metermeta, do not retrieve metadata in cache.
 * @param pSql          sql object
S
slguan 已提交
2421
 * @param tableId       meter id
H
hzcheng 已提交
2422 2423
 * @return              status code
 */
S
slguan 已提交
2424
int tscRenewMeterMeta(SSqlObj *pSql, char *tableId) {
2425 2426
  int code = 0;

H
hjxilinx 已提交
2427
  // handle table meta renew process
H
hzcheng 已提交
2428
  SSqlCmd *pCmd = &pSql->cmd;
2429 2430

  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
hjxilinx 已提交
2431
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hzcheng 已提交
2432 2433

  /*
S
slguan 已提交
2434
   * 1. only update the metermeta in force model metricmeta is not updated
H
hzcheng 已提交
2435 2436
   * 2. if get metermeta failed, still get the metermeta
   */
2437
  if (pTableMetaInfo->pTableMeta == NULL || !tscQueryOnSTable(pCmd)) {
2438
    STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;
H
hjxilinx 已提交
2439
    if (pTableMetaInfo->pTableMeta) {
2440 2441
      tscTrace("%p update table meta, old: numOfTags:%d, numOfCols:%d, uid:%" PRId64 ", addr:%p", pSql,
               tscGetNumOfTags(pTableMeta), tscGetNumOfColumns(pTableMeta), pTableMeta->uid, pTableMeta);
H
hzcheng 已提交
2442
    }
2443

2444
    tscWaitingForCreateTable(pCmd);
H
hjxilinx 已提交
2445
    taosCacheRelease(tscCacheHandle, (void **)&(pTableMetaInfo->pTableMeta), true);
H
hzcheng 已提交
2446

2447
    code = getTableMetaFromMgmt(pSql, pTableMetaInfo);  // todo ??
H
hzcheng 已提交
2448
  } else {
H
hjxilinx 已提交
2449
    tscTrace("%p metric query not update metric meta, numOfTags:%d, numOfCols:%d, uid:%" PRId64 ", addr:%p", pSql,
H
hjxilinx 已提交
2450 2451
             tscGetNumOfTags(pTableMetaInfo->pTableMeta), pCmd->numOfCols, pTableMetaInfo->pTableMeta->uid,
             pTableMetaInfo->pTableMeta);
H
hzcheng 已提交
2452 2453 2454 2455 2456
  }

  return code;
}

H
hjxilinx 已提交
2457
static bool allVgroupInfoRetrieved(SSqlCmd* pCmd, int32_t clauseIndex) {
2458
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, clauseIndex);
2459
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
H
hjxilinx 已提交
2460
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, i);
H
hjxilinx 已提交
2461 2462
    if (pTableMetaInfo->vgroupList == NULL) {
      return false;
S
slguan 已提交
2463 2464
    }
  }
H
hjxilinx 已提交
2465 2466 2467 2468
  
  // all super tables vgroupinfo are retrieved, no need to retrieve vgroup info anymore
  return true;
}
H
hzcheng 已提交
2469

H
hjxilinx 已提交
2470
int tscGetSTableVgroupInfo(SSqlObj *pSql, int32_t clauseIndex) {
2471
  int      code = TSDB_CODE_RPC_NETWORK_UNAVAIL;
H
hjxilinx 已提交
2472 2473 2474
  SSqlCmd *pCmd = &pSql->cmd;
  
  if (allVgroupInfoRetrieved(pCmd, clauseIndex)) {
H
hzcheng 已提交
2475 2476
    return TSDB_CODE_SUCCESS;
  }
H
hjxilinx 已提交
2477

S
slguan 已提交
2478
  SSqlObj *pNew = calloc(1, sizeof(SSqlObj));
H
hzcheng 已提交
2479 2480 2481
  pNew->pTscObj = pSql->pTscObj;
  pNew->signature = pNew;

H
hjxilinx 已提交
2482
  pNew->cmd.command = TSDB_SQL_STABLEVGROUP;
2483 2484
  
  SQueryInfo *pNewQueryInfo = NULL;
2485 2486 2487
  if ((code = tscGetQueryInfoDetailSafely(&pNew->cmd, 0, &pNewQueryInfo)) != TSDB_CODE_SUCCESS) {
    return code;
  }
2488
  
H
hjxilinx 已提交
2489
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, clauseIndex);
2490
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
H
hjxilinx 已提交
2491 2492 2493
    STableMetaInfo *pMInfo = tscGetMetaInfo(pQueryInfo, i);
    STableMeta *pTableMeta = taosCacheAcquireByData(tscCacheHandle, pMInfo->pTableMeta);
    tscAddTableMetaInfo(pNewQueryInfo, pMInfo->name, pTableMeta, NULL, pMInfo->tagColList);
S
slguan 已提交
2494 2495 2496 2497 2498 2499
  }

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

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

2504 2505 2506 2507
  pNew->fp = tscTableMetaCallBack;
  pNew->param = pSql;
  code = tscProcessSql(pNew);
  if (code == TSDB_CODE_SUCCESS) {
2508
    code = TSDB_CODE_TSC_ACTION_IN_PROGRESS;
H
hzcheng 已提交
2509 2510 2511 2512 2513
  }

  return code;
}

2514
void tscInitMsgsFp() {
S
slguan 已提交
2515 2516
  tscBuildMsg[TSDB_SQL_SELECT] = tscBuildQueryMsg;
  tscBuildMsg[TSDB_SQL_INSERT] = tscBuildSubmitMsg;
J
jtao1735 已提交
2517
  tscBuildMsg[TSDB_SQL_FETCH] = tscBuildFetchMsg;
H
hzcheng 已提交
2518 2519

  tscBuildMsg[TSDB_SQL_CREATE_DB] = tscBuildCreateDbMsg;
2520
  tscBuildMsg[TSDB_SQL_CREATE_USER] = tscBuildUserMsg;
H
hzcheng 已提交
2521

2522 2523
  tscBuildMsg[TSDB_SQL_CREATE_ACCT] = tscBuildAcctMsg;
  tscBuildMsg[TSDB_SQL_ALTER_ACCT] = tscBuildAcctMsg;
H
hzcheng 已提交
2524 2525

  tscBuildMsg[TSDB_SQL_CREATE_TABLE] = tscBuildCreateTableMsg;
S
[TD-16]  
slguan 已提交
2526
  tscBuildMsg[TSDB_SQL_DROP_USER] = tscBuildDropUserMsg;
H
hzcheng 已提交
2527 2528 2529
  tscBuildMsg[TSDB_SQL_DROP_ACCT] = tscBuildDropAcctMsg;
  tscBuildMsg[TSDB_SQL_DROP_DB] = tscBuildDropDbMsg;
  tscBuildMsg[TSDB_SQL_DROP_TABLE] = tscBuildDropTableMsg;
2530
  tscBuildMsg[TSDB_SQL_ALTER_USER] = tscBuildUserMsg;
S
slguan 已提交
2531 2532 2533
  tscBuildMsg[TSDB_SQL_CREATE_DNODE] = tscBuildCreateDnodeMsg;
  tscBuildMsg[TSDB_SQL_DROP_DNODE] = tscBuildDropDnodeMsg;
  tscBuildMsg[TSDB_SQL_CFG_DNODE] = tscBuildCfgDnodeMsg;
H
hzcheng 已提交
2534
  tscBuildMsg[TSDB_SQL_ALTER_TABLE] = tscBuildAlterTableMsg;
2535
  tscBuildMsg[TSDB_SQL_UPDATE_TAGS_VAL] = tscBuildUpdateTagMsg;
H
hzcheng 已提交
2536 2537 2538 2539
  tscBuildMsg[TSDB_SQL_ALTER_DB] = tscAlterDbMsg;

  tscBuildMsg[TSDB_SQL_CONNECT] = tscBuildConnectMsg;
  tscBuildMsg[TSDB_SQL_USE_DB] = tscBuildUseDbMsg;
H
hjxilinx 已提交
2540
  tscBuildMsg[TSDB_SQL_META] = tscBuildTableMetaMsg;
H
hjxilinx 已提交
2541
  tscBuildMsg[TSDB_SQL_STABLEVGROUP] = tscBuildSTableVgroupMsg;
S
slguan 已提交
2542
  tscBuildMsg[TSDB_SQL_MULTI_META] = tscBuildMultiMeterMetaMsg;
H
hzcheng 已提交
2543 2544 2545 2546

  tscBuildMsg[TSDB_SQL_HB] = tscBuildHeartBeatMsg;
  tscBuildMsg[TSDB_SQL_SHOW] = tscBuildShowMsg;
  tscBuildMsg[TSDB_SQL_RETRIEVE] = tscBuildRetrieveFromMgmtMsg;
2547 2548 2549
  tscBuildMsg[TSDB_SQL_KILL_QUERY] = tscBuildKillMsg;
  tscBuildMsg[TSDB_SQL_KILL_STREAM] = tscBuildKillMsg;
  tscBuildMsg[TSDB_SQL_KILL_CONNECTION] = tscBuildKillMsg;
H
hzcheng 已提交
2550 2551

  tscProcessMsgRsp[TSDB_SQL_SELECT] = tscProcessQueryRsp;
H
hjxilinx 已提交
2552
  tscProcessMsgRsp[TSDB_SQL_FETCH] = tscProcessRetrieveRspFromNode;
H
hzcheng 已提交
2553 2554 2555 2556 2557

  tscProcessMsgRsp[TSDB_SQL_DROP_DB] = tscProcessDropDbRsp;
  tscProcessMsgRsp[TSDB_SQL_DROP_TABLE] = tscProcessDropTableRsp;
  tscProcessMsgRsp[TSDB_SQL_CONNECT] = tscProcessConnectRsp;
  tscProcessMsgRsp[TSDB_SQL_USE_DB] = tscProcessUseDbRsp;
2558
  tscProcessMsgRsp[TSDB_SQL_META] = tscProcessTableMetaRsp;
H
hjxilinx 已提交
2559
  tscProcessMsgRsp[TSDB_SQL_STABLEVGROUP] = tscProcessSTableVgroupRsp;
S
slguan 已提交
2560
  tscProcessMsgRsp[TSDB_SQL_MULTI_META] = tscProcessMultiMeterMetaRsp;
H
hzcheng 已提交
2561 2562

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

H
hjxilinx 已提交
2566 2567 2568 2569 2570
  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;
2571

H
hzcheng 已提交
2572 2573
  tscProcessMsgRsp[TSDB_SQL_RETRIEVE_EMPTY_RESULT] = tscProcessEmptyResultRsp;

H
hjxilinx 已提交
2574
  tscProcessMsgRsp[TSDB_SQL_RETRIEVE_LOCALMERGE] = tscProcessRetrieveLocalMergeRsp;
H
hzcheng 已提交
2575 2576 2577 2578 2579 2580 2581 2582 2583 2584

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