parInsertUtil.c 47.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * 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/>.
 */
X
Xiaoyu Wang 已提交
15

X
Xiaoyu Wang 已提交
16
#include "parInsertUtil.h"
17 18

#include "catalog.h"
X
Xiaoyu Wang 已提交
19
#include "parInt.h"
X
Xiaoyu Wang 已提交
20
#include "parUtil.h"
X
Xiaoyu Wang 已提交
21
#include "querynodes.h"
C
Cary Xu 已提交
22
#include "tRealloc.h"
wmmhello's avatar
wmmhello 已提交
23
#include "tdatablock.h"
24

25
typedef struct SBlockKeyTuple {
X
Xiaoyu Wang 已提交
26 27
  TSKEY   skey;
  void*   payloadAddr;
wafwerar's avatar
wafwerar 已提交
28
  int16_t index;
29 30 31 32 33 34 35
} SBlockKeyTuple;

typedef struct SBlockKeyInfo {
  int32_t         maxBytesAlloc;
  SBlockKeyTuple* pKeyTuple;
} SBlockKeyInfo;

C
Cary Xu 已提交
36 37
typedef struct {
  int32_t   index;
C
Cary Xu 已提交
38
  SArray*   rowArray;  // array of merged rows(mem allocated by tRealloc/free by tFree)
C
Cary Xu 已提交
39
  STSchema* pSchema;
C
Cary Xu 已提交
40
  int64_t   tbUid;  // suid for child table, uid for normal table
C
Cary Xu 已提交
41 42
} SBlockRowMerger;

C
Cary Xu 已提交
43
static FORCE_INLINE void tdResetSBlockRowMerger(SBlockRowMerger* pMerger) {
C
Cary Xu 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57
  if (pMerger) {
    pMerger->index = -1;
  }
}

static void tdFreeSBlockRowMerger(SBlockRowMerger* pMerger) {
  if (pMerger) {
    int32_t size = taosArrayGetSize(pMerger->rowArray);
    for (int32_t i = 0; i < size; ++i) {
      tFree(*(void**)taosArrayGet(pMerger->rowArray, i));
    }
    taosArrayDestroy(pMerger->rowArray);

    taosMemoryFreeClear(pMerger->pSchema);
C
Cary Xu 已提交
58
    taosMemoryFree(pMerger);
C
Cary Xu 已提交
59 60 61
  }
}

X
Xiaoyu Wang 已提交
62 63 64
static int32_t rowDataCompar(const void* lhs, const void* rhs) {
  TSKEY left = *(TSKEY*)lhs;
  TSKEY right = *(TSKEY*)rhs;
65 66 67 68 69 70 71
  if (left == right) {
    return 0;
  } else {
    return left > right ? 1 : -1;
  }
}

wafwerar's avatar
wafwerar 已提交
72 73 74 75 76 77 78 79 80 81
static int32_t rowDataComparStable(const void* lhs, const void* rhs) {
  TSKEY left = *(TSKEY*)lhs;
  TSKEY right = *(TSKEY*)rhs;
  if (left == right) {
    return ((SBlockKeyTuple*)lhs)->index - ((SBlockKeyTuple*)rhs)->index;
  } else {
    return left > right ? 1 : -1;
  }
}

X
Xiaoyu Wang 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
int32_t insGetExtendedRowSize(STableDataBlocks* pBlock) {
  STableComInfo* pTableInfo = &pBlock->pTableMeta->tableInfo;
  ASSERT(pBlock->rowSize == pTableInfo->rowSize);
  return pBlock->rowSize + TD_ROW_HEAD_LEN - sizeof(TSKEY) + pBlock->boundColumnInfo.extendedVarLen +
         (int32_t)TD_BITMAP_BYTES(pTableInfo->numOfColumns - 1);
}

void insGetSTSRowAppendInfo(uint8_t rowType, SParsedDataColInfo* spd, col_id_t idx, int32_t* toffset,
                            col_id_t* colIdx) {
  col_id_t schemaIdx = 0;
  if (IS_DATA_COL_ORDERED(spd)) {
    schemaIdx = spd->boundColumns[idx];
    if (TD_IS_TP_ROW_T(rowType)) {
      *toffset = (spd->cols + schemaIdx)->toffset;  // the offset of firstPart
      *colIdx = schemaIdx;
    } else {
      *toffset = idx * sizeof(SKvRowIdx);  // the offset of SKvRowIdx
      *colIdx = idx;
    }
  } else {
    ASSERT(idx == (spd->colIdxInfo + idx)->boundIdx);
    schemaIdx = (spd->colIdxInfo + idx)->schemaColIdx;
    if (TD_IS_TP_ROW_T(rowType)) {
      *toffset = (spd->cols + schemaIdx)->toffset;
      *colIdx = schemaIdx;
    } else {
      *toffset = ((spd->colIdxInfo + idx)->finalIdx) * sizeof(SKvRowIdx);
      *colIdx = (spd->colIdxInfo + idx)->finalIdx;
    }
  }
}

X
Xiaoyu Wang 已提交
114
int32_t insSetBlockInfo(SSubmitBlk* pBlocks, STableDataBlocks* dataBuf, int32_t numOfRows, SMsgBuf* pMsg) {
X
Xiaoyu Wang 已提交
115 116 117 118 119 120
  pBlocks->suid = (TSDB_NORMAL_TABLE == dataBuf->pTableMeta->tableType ? 0 : dataBuf->pTableMeta->suid);
  pBlocks->uid = dataBuf->pTableMeta->uid;
  pBlocks->sversion = dataBuf->pTableMeta->sversion;
  pBlocks->schemaLen = dataBuf->createTbReqLen;

  if (pBlocks->numOfRows + numOfRows >= INT32_MAX) {
X
Xiaoyu Wang 已提交
121
    return buildInvalidOperationMsg(pMsg, "too many rows in sql, total number of rows should be less than INT32_MAX");
X
Xiaoyu Wang 已提交
122
  }
X
Xiaoyu Wang 已提交
123 124
  pBlocks->numOfRows += numOfRows;
  return TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
125 126 127
}

void insSetBoundColumnInfo(SParsedDataColInfo* pColList, SSchema* pSchema, col_id_t numOfCols) {
128 129 130
  pColList->numOfCols = numOfCols;
  pColList->numOfBound = numOfCols;
  pColList->orderStatus = ORDER_STATUS_ORDERED;  // default is ORDERED for non-bound mode
131
  pColList->boundColumns = taosMemoryCalloc(pColList->numOfCols, sizeof(col_id_t));
wafwerar's avatar
wafwerar 已提交
132
  pColList->cols = taosMemoryCalloc(pColList->numOfCols, sizeof(SBoundColumn));
133 134 135 136 137 138 139 140 141 142
  pColList->colIdxInfo = NULL;
  pColList->flen = 0;
  pColList->allNullLen = 0;

  int32_t nVar = 0;
  for (int32_t i = 0; i < pColList->numOfCols; ++i) {
    uint8_t type = pSchema[i].type;
    if (i > 0) {
      pColList->cols[i].offset = pColList->cols[i - 1].offset + pSchema[i - 1].bytes;
      pColList->cols[i].toffset = pColList->flen;
K
kailixu 已提交
143
      pColList->flen += TYPE_BYTES[type];
144 145 146 147 148 149 150 151 152 153 154 155 156
    }
    switch (type) {
      case TSDB_DATA_TYPE_BINARY:
        pColList->allNullLen += (VARSTR_HEADER_SIZE + CHAR_BYTES);
        ++nVar;
        break;
      case TSDB_DATA_TYPE_NCHAR:
        pColList->allNullLen += (VARSTR_HEADER_SIZE + TSDB_NCHAR_SIZE);
        ++nVar;
        break;
      default:
        break;
    }
X
Xiaoyu Wang 已提交
157
    pColList->boundColumns[i] = i;
158 159
  }
  pColList->allNullLen += pColList->flen;
C
Cary Xu 已提交
160
  pColList->boundNullLen = pColList->allNullLen;  // default set allNullLen
161 162 163
  pColList->extendedVarLen = (uint16_t)(nVar * sizeof(VarDataOffsetT));
}

X
Xiaoyu Wang 已提交
164
int32_t insSchemaIdxCompar(const void* lhs, const void* rhs) {
X
Xiaoyu Wang 已提交
165 166
  uint16_t left = *(uint16_t*)lhs;
  uint16_t right = *(uint16_t*)rhs;
167 168 169 170 171 172 173 174

  if (left == right) {
    return 0;
  } else {
    return left > right ? 1 : -1;
  }
}

X
Xiaoyu Wang 已提交
175
int32_t insBoundIdxCompar(const void* lhs, const void* rhs) {
X
Xiaoyu Wang 已提交
176 177
  uint16_t left = *(uint16_t*)POINTER_SHIFT(lhs, sizeof(uint16_t));
  uint16_t right = *(uint16_t*)POINTER_SHIFT(rhs, sizeof(uint16_t));
178 179 180 181 182 183 184 185

  if (left == right) {
    return 0;
  } else {
    return left > right ? 1 : -1;
  }
}

D
stmt  
dapan1121 已提交
186 187
void destroyBoundColumnInfo(void* pBoundInfo) {
  if (NULL == pBoundInfo) {
D
stmt  
dapan1121 已提交
188 189
    return;
  }
D
stmt  
dapan1121 已提交
190 191

  SParsedDataColInfo* pColList = (SParsedDataColInfo*)pBoundInfo;
X
Xiaoyu Wang 已提交
192

193
  taosMemoryFreeClear(pColList->boundColumns);
wafwerar's avatar
wafwerar 已提交
194 195
  taosMemoryFreeClear(pColList->cols);
  taosMemoryFreeClear(pColList->colIdxInfo);
196 197
}

198 199 200 201 202 203 204 205 206 207
void qDestroyBoundColInfo(void* pInfo) {
  if (NULL == pInfo) {
    return;
  }

  SBoundColInfo* pBoundInfo = (SBoundColInfo*)pInfo;

  taosMemoryFreeClear(pBoundInfo->pColIndex);
}

wmmhello's avatar
wmmhello 已提交
208
static int32_t createTableDataBlock(size_t defaultSize, int32_t rowSize, int32_t startOffset, STableMeta* pTableMeta,
X
Xiaoyu Wang 已提交
209
                               STableDataBlocks** dataBlocks) {
wafwerar's avatar
wafwerar 已提交
210
  STableDataBlocks* dataBuf = (STableDataBlocks*)taosMemoryCalloc(1, sizeof(STableDataBlocks));
211
  if (dataBuf == NULL) {
S
Shengliang Guan 已提交
212
    return TSDB_CODE_OUT_OF_MEMORY;
213 214 215 216 217 218 219 220 221 222
  }

  dataBuf->nAllocSize = (uint32_t)defaultSize;
  dataBuf->headerSize = startOffset;

  // the header size will always be the startOffset value, reserved for the subumit block header
  if (dataBuf->nAllocSize <= dataBuf->headerSize) {
    dataBuf->nAllocSize = dataBuf->headerSize * 2;
  }

wafwerar's avatar
wafwerar 已提交
223
  dataBuf->pData = taosMemoryMalloc(dataBuf->nAllocSize);
224
  if (dataBuf->pData == NULL) {
wafwerar's avatar
wafwerar 已提交
225
    taosMemoryFreeClear(dataBuf);
S
Shengliang Guan 已提交
226
    return TSDB_CODE_OUT_OF_MEMORY;
227 228 229
  }
  memset(dataBuf->pData, 0, sizeof(SSubmitBlk));

X
Xiaoyu Wang 已提交
230
  dataBuf->pTableMeta = tableMetaDup(pTableMeta);
231 232

  SParsedDataColInfo* pColInfo = &dataBuf->boundColumnInfo;
X
Xiaoyu Wang 已提交
233
  SSchema*            pSchema = getTableColumnSchema(dataBuf->pTableMeta);
X
Xiaoyu Wang 已提交
234
  insSetBoundColumnInfo(pColInfo, pSchema, dataBuf->pTableMeta->tableInfo.numOfColumns);
235

X
Xiaoyu Wang 已提交
236 237 238 239 240
  dataBuf->ordered = true;
  dataBuf->prevTS = INT64_MIN;
  dataBuf->rowSize = rowSize;
  dataBuf->size = startOffset;
  dataBuf->vgId = dataBuf->pTableMeta->vgId;
241 242 243 244 245 246 247

  assert(defaultSize > 0 && pTableMeta != NULL && dataBuf->pTableMeta != NULL);

  *dataBlocks = dataBuf;
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
248
int32_t insBuildCreateTbMsg(STableDataBlocks* pBlocks, SVCreateTbReq* pCreateTbReq) {
H
Hongze Cheng 已提交
249
  SEncoder coder = {0};
X
Xiaoyu Wang 已提交
250 251
  char*    pBuf;
  int32_t  len;
H
Hongze Cheng 已提交
252

wafwerar's avatar
wafwerar 已提交
253 254
  int32_t ret = 0;
  tEncodeSize(tEncodeSVCreateTbReq, pCreateTbReq, len, ret);
X
Xiaoyu Wang 已提交
255 256 257 258 259 260 261 262
  if (pBlocks->nAllocSize - pBlocks->size < len) {
    pBlocks->nAllocSize += len + pBlocks->rowSize;
    char* pTmp = taosMemoryRealloc(pBlocks->pData, pBlocks->nAllocSize);
    if (pTmp != NULL) {
      pBlocks->pData = pTmp;
      memset(pBlocks->pData + pBlocks->size, 0, pBlocks->nAllocSize - pBlocks->size);
    } else {
      pBlocks->nAllocSize -= len + pBlocks->rowSize;
S
Shengliang Guan 已提交
263
      return TSDB_CODE_OUT_OF_MEMORY;
X
Xiaoyu Wang 已提交
264 265
    }
  }
H
Hongze Cheng 已提交
266

X
Xiaoyu Wang 已提交
267
  pBuf = pBlocks->pData + pBlocks->size;
H
Hongze Cheng 已提交
268

H
Hongze Cheng 已提交
269
  tEncoderInit(&coder, pBuf, len);
X
Xiaoyu Wang 已提交
270
  int32_t code = tEncodeSVCreateTbReq(&coder, pCreateTbReq);
H
Hongze Cheng 已提交
271
  tEncoderClear(&coder);
X
Xiaoyu Wang 已提交
272 273
  pBlocks->size += len;
  pBlocks->createTbReqLen = len;
X
Xiaoyu Wang 已提交
274 275

  return code;
X
Xiaoyu Wang 已提交
276 277
}

X
Xiaoyu Wang 已提交
278
void insDestroyDataBlock(STableDataBlocks* pDataBlock) {
X
Xiaoyu Wang 已提交
279 280 281 282 283 284 285 286 287 288
  if (pDataBlock == NULL) {
    return;
  }

  taosMemoryFreeClear(pDataBlock->pData);
  taosMemoryFreeClear(pDataBlock->pTableMeta);
  destroyBoundColumnInfo(&pDataBlock->boundColumnInfo);
  taosMemoryFreeClear(pDataBlock);
}

X
Xiaoyu Wang 已提交
289 290 291
int32_t insGetDataBlockFromList(SHashObj* pHashList, void* id, int32_t idLen, int32_t size, int32_t startOffset,
                                int32_t rowSize, STableMeta* pTableMeta, STableDataBlocks** dataBlocks,
                                SArray* pBlockList, SVCreateTbReq* pCreateTbReq) {
292
  *dataBlocks = NULL;
D
dapan 已提交
293
  STableDataBlocks** t1 = (STableDataBlocks**)taosHashGet(pHashList, (const char*)id, idLen);
294 295 296 297 298
  if (t1 != NULL) {
    *dataBlocks = *t1;
  }

  if (*dataBlocks == NULL) {
wmmhello's avatar
wmmhello 已提交
299
    int32_t ret = createTableDataBlock((size_t)size, rowSize, startOffset, pTableMeta, dataBlocks);
300 301 302 303
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }

H
Hongze Cheng 已提交
304
    if (NULL != pCreateTbReq && NULL != pCreateTbReq->ctb.pTag) {
X
Xiaoyu Wang 已提交
305
      ret = insBuildCreateTbMsg(*dataBlocks, pCreateTbReq);
X
Xiaoyu Wang 已提交
306
      if (ret != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
307
        insDestroyDataBlock(*dataBlocks);
X
Xiaoyu Wang 已提交
308 309 310 311
        return ret;
      }
    }

X
Xiaoyu Wang 已提交
312 313
    // converting to 'const char*' is to handle coverity scan errors
    taosHashPut(pHashList, (const char*)id, idLen, (const char*)dataBlocks, POINTER_BYTES);
314 315 316 317 318 319 320 321
    if (pBlockList) {
      taosArrayPush(pBlockList, dataBlocks);
    }
  }

  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
322
void insDestroyBlockArrayList(SArray* pDataBlockList) {
323
  if (pDataBlockList == NULL) {
324
    return;
325 326 327 328
  }

  size_t size = taosArrayGetSize(pDataBlockList);
  for (int32_t i = 0; i < size; i++) {
329
    void* p = taosArrayGetP(pDataBlockList, i);
X
Xiaoyu Wang 已提交
330
    insDestroyDataBlock(p);
331 332 333 334 335
  }

  taosArrayDestroy(pDataBlockList);
}

X
Xiaoyu Wang 已提交
336
void insDestroyBlockHashmap(SHashObj* pDataBlockHash) {
337 338 339 340 341 342
  if (pDataBlockHash == NULL) {
    return;
  }

  void** p1 = taosHashIterate(pDataBlockHash, NULL);
  while (p1) {
wmmhello's avatar
wmmhello 已提交
343 344
    SBoundColInfo* pBlocks = *p1;
    destroyBoundColInfo(pBlocks);
345 346 347 348 349 350 351

    p1 = taosHashIterate(pDataBlockHash, p1);
  }

  taosHashCleanup(pDataBlockHash);
}

352
// data block is disordered, sort it in ascending order
C
Cary Xu 已提交
353
static int sortRemoveDataBlockDupRows(STableDataBlocks* dataBuf, SBlockKeyInfo* pBlkKeyInfo) {
X
Xiaoyu Wang 已提交
354
  SSubmitBlk* pBlocks = (SSubmitBlk*)dataBuf->pData;
355 356 357 358 359 360 361
  int16_t     nRows = pBlocks->numOfRows;

  // size is less than the total size, since duplicated rows may be removed yet.

  // allocate memory
  size_t nAlloc = nRows * sizeof(SBlockKeyTuple);
  if (pBlkKeyInfo->pKeyTuple == NULL || pBlkKeyInfo->maxBytesAlloc < nAlloc) {
X
Xiaoyu Wang 已提交
362
    char* tmp = taosMemoryRealloc(pBlkKeyInfo->pKeyTuple, nAlloc);
363
    if (tmp == NULL) {
S
Shengliang Guan 已提交
364
      return TSDB_CODE_OUT_OF_MEMORY;
365
    }
X
Xiaoyu Wang 已提交
366
    pBlkKeyInfo->pKeyTuple = (SBlockKeyTuple*)tmp;
367 368 369 370
    pBlkKeyInfo->maxBytesAlloc = (int32_t)nAlloc;
  }
  memset(pBlkKeyInfo->pKeyTuple, 0, nAlloc);

X
Xiaoyu Wang 已提交
371
  int32_t         extendedRowSize = insGetExtendedRowSize(dataBuf);
X
Xiaoyu Wang 已提交
372 373
  SBlockKeyTuple* pBlkKeyTuple = pBlkKeyInfo->pKeyTuple;
  char*           pBlockData = pBlocks->data + pBlocks->schemaLen;
374 375
  int             n = 0;
  while (n < nRows) {
X
Xiaoyu Wang 已提交
376
    pBlkKeyTuple->skey = TD_ROW_KEY((STSRow*)pBlockData);
377
    pBlkKeyTuple->payloadAddr = pBlockData;
wafwerar's avatar
wafwerar 已提交
378
    pBlkKeyTuple->index = n;
379 380 381 382 383 384 385 386 387

    // next loop
    pBlockData += extendedRowSize;
    ++pBlkKeyTuple;
    ++n;
  }

  if (!dataBuf->ordered) {
    pBlkKeyTuple = pBlkKeyInfo->pKeyTuple;
388 389

    // todo. qsort is unstable, if timestamp is same, should get the last one
wafwerar's avatar
wafwerar 已提交
390
    taosSort(pBlkKeyTuple, nRows, sizeof(SBlockKeyTuple), rowDataComparStable);
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420

    pBlkKeyTuple = pBlkKeyInfo->pKeyTuple;
    int32_t i = 0;
    int32_t j = 1;
    while (j < nRows) {
      TSKEY ti = (pBlkKeyTuple + i)->skey;
      TSKEY tj = (pBlkKeyTuple + j)->skey;

      if (ti == tj) {
        ++j;
        continue;
      }

      int32_t nextPos = (++i);
      if (nextPos != j) {
        memmove(pBlkKeyTuple + nextPos, pBlkKeyTuple + j, sizeof(SBlockKeyTuple));
      }
      ++j;
    }

    dataBuf->ordered = true;
    pBlocks->numOfRows = i + 1;
  }

  dataBuf->size = sizeof(SSubmitBlk) + pBlocks->numOfRows * extendedRowSize;
  dataBuf->prevTS = INT64_MIN;

  return 0;
}

C
Cary Xu 已提交
421 422 423 424 425 426 427 428
static void* tdGetCurRowFromBlockMerger(SBlockRowMerger* pBlkRowMerger) {
  if (pBlkRowMerger && (pBlkRowMerger->index >= 0)) {
    ASSERT(pBlkRowMerger->index < taosArrayGetSize(pBlkRowMerger->rowArray));
    return *(void**)taosArrayGet(pBlkRowMerger->rowArray, pBlkRowMerger->index);
  }
  return NULL;
}

C
Cary Xu 已提交
429
static int32_t tdBlockRowMerge(STableMeta* pTableMeta, SBlockKeyTuple* pEndKeyTp, int32_t nDupRows,
C
Cary Xu 已提交
430 431 432 433 434 435 436
                               SBlockRowMerger** pBlkRowMerger, int32_t rowSize) {
  ASSERT(nDupRows > 1);
  SBlockKeyTuple* pStartKeyTp = pEndKeyTp - (nDupRows - 1);
  ASSERT(pStartKeyTp->skey == pEndKeyTp->skey);

  // TODO: optimization if end row is all normal
#if 0
C
Cary Xu 已提交
437
  STSRow* pEndRow = (STSRow*)pEndKeyTp->payloadAddr;
C
Cary Xu 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
  if(isNormal(pEndRow)) { // set the end row if it is normal and return directly
    pStartKeyTp->payloadAddr = pEndKeyTp->payloadAddr;
    return TSDB_CODE_SUCCESS;
  }
#endif

  if (!(*pBlkRowMerger)) {
    (*pBlkRowMerger) = taosMemoryCalloc(1, sizeof(**pBlkRowMerger));
    if (!(*pBlkRowMerger)) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      return TSDB_CODE_FAILED;
    }
    (*pBlkRowMerger)->index = -1;
    if (!(*pBlkRowMerger)->rowArray) {
      (*pBlkRowMerger)->rowArray = taosArrayInit(1, sizeof(void*));
      if (!(*pBlkRowMerger)->rowArray) {
        terrno = TSDB_CODE_OUT_OF_MEMORY;
        return TSDB_CODE_FAILED;
      }
    }
  }

C
Cary Xu 已提交
460 461 462 463 464 465 466 467 468 469
  if ((*pBlkRowMerger)->pSchema) {
    if ((*pBlkRowMerger)->pSchema->version != pTableMeta->sversion) {
      taosMemoryFreeClear((*pBlkRowMerger)->pSchema);
    } else {
      if ((*pBlkRowMerger)->tbUid != (pTableMeta->suid > 0 ? pTableMeta->suid : pTableMeta->uid)) {
        taosMemoryFreeClear((*pBlkRowMerger)->pSchema);
      }
    }
  }

C
Cary Xu 已提交
470
  if (!(*pBlkRowMerger)->pSchema) {
C
Cary Xu 已提交
471
    (*pBlkRowMerger)->pSchema =
H
Hongze Cheng 已提交
472
        tBuildTSchema(pTableMeta->schema, pTableMeta->tableInfo.numOfColumns, pTableMeta->sversion);
C
Cary Xu 已提交
473 474 475 476 477

    if (!(*pBlkRowMerger)->pSchema) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      return TSDB_CODE_FAILED;
    }
C
Cary Xu 已提交
478
    (*pBlkRowMerger)->tbUid = pTableMeta->suid > 0 ? pTableMeta->suid : pTableMeta->uid;
C
Cary Xu 已提交
479 480 481 482 483
  }

  void* pDestRow = NULL;
  ++((*pBlkRowMerger)->index);
  if ((*pBlkRowMerger)->index < taosArrayGetSize((*pBlkRowMerger)->rowArray)) {
484 485
    void** pAlloc = (void**)taosArrayGet((*pBlkRowMerger)->rowArray, (*pBlkRowMerger)->index);
    if (tRealloc((uint8_t**)pAlloc, rowSize) != 0) {
C
Cary Xu 已提交
486 487
      return TSDB_CODE_FAILED;
    }
488
    pDestRow = *pAlloc;
C
Cary Xu 已提交
489 490 491 492 493 494 495 496 497 498 499 500
  } else {
    if (tRealloc((uint8_t**)&pDestRow, rowSize) != 0) {
      return TSDB_CODE_FAILED;
    }
    taosArrayPush((*pBlkRowMerger)->rowArray, &pDestRow);
  }

  // merge rows to pDestRow
  STSchema* pSchema = (*pBlkRowMerger)->pSchema;
  SArray*   pArray = taosArrayInit(pSchema->numOfCols, sizeof(SColVal));
  for (int32_t i = 0; i < pSchema->numOfCols; ++i) {
    SColVal colVal = {0};
C
Cary Xu 已提交
501
    for (int32_t j = 0; j < nDupRows; ++j) {
C
Cary Xu 已提交
502
      tTSRowGetVal((pEndKeyTp - j)->payloadAddr, pSchema, i, &colVal);
H
Hongze Cheng 已提交
503
      if (!COL_VAL_IS_NONE(&colVal)) {
C
Cary Xu 已提交
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
        break;
      }
    }
    taosArrayPush(pArray, &colVal);
  }
  if (tdSTSRowNew(pArray, pSchema, (STSRow**)&pDestRow) < 0) {
    taosArrayDestroy(pArray);
    return TSDB_CODE_FAILED;
  }

  taosArrayDestroy(pArray);
  return TSDB_CODE_SUCCESS;
}

// data block is disordered, sort it in ascending order, and merge dup rows if exists
static int sortMergeDataBlockDupRows(STableDataBlocks* dataBuf, SBlockKeyInfo* pBlkKeyInfo,
                                     SBlockRowMerger** ppBlkRowMerger) {
  SSubmitBlk* pBlocks = (SSubmitBlk*)dataBuf->pData;
C
Cary Xu 已提交
522
  STableMeta* pTableMeta = dataBuf->pTableMeta;
523
  int32_t     nRows = pBlocks->numOfRows;
C
Cary Xu 已提交
524 525 526 527 528 529 530 531

  // size is less than the total size, since duplicated rows may be removed.

  // allocate memory
  size_t nAlloc = nRows * sizeof(SBlockKeyTuple);
  if (pBlkKeyInfo->pKeyTuple == NULL || pBlkKeyInfo->maxBytesAlloc < nAlloc) {
    char* tmp = taosMemoryRealloc(pBlkKeyInfo->pKeyTuple, nAlloc);
    if (tmp == NULL) {
S
Shengliang Guan 已提交
532
      return TSDB_CODE_OUT_OF_MEMORY;
C
Cary Xu 已提交
533 534 535 536 537 538 539 540
    }
    pBlkKeyInfo->pKeyTuple = (SBlockKeyTuple*)tmp;
    pBlkKeyInfo->maxBytesAlloc = (int32_t)nAlloc;
  }
  memset(pBlkKeyInfo->pKeyTuple, 0, nAlloc);

  tdResetSBlockRowMerger(*ppBlkRowMerger);

X
Xiaoyu Wang 已提交
541
  int32_t         extendedRowSize = insGetExtendedRowSize(dataBuf);
C
Cary Xu 已提交
542 543
  SBlockKeyTuple* pBlkKeyTuple = pBlkKeyInfo->pKeyTuple;
  char*           pBlockData = pBlocks->data + pBlocks->schemaLen;
544
  int32_t         n = 0;
C
Cary Xu 已提交
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
  while (n < nRows) {
    pBlkKeyTuple->skey = TD_ROW_KEY((STSRow*)pBlockData);
    pBlkKeyTuple->payloadAddr = pBlockData;
    pBlkKeyTuple->index = n;

    // next loop
    pBlockData += extendedRowSize;
    ++pBlkKeyTuple;
    ++n;
  }

  if (!dataBuf->ordered) {
    pBlkKeyTuple = pBlkKeyInfo->pKeyTuple;

    taosSort(pBlkKeyTuple, nRows, sizeof(SBlockKeyTuple), rowDataComparStable);

    pBlkKeyTuple = pBlkKeyInfo->pKeyTuple;
    bool    hasDup = false;
    int32_t nextPos = 0;
    int32_t i = 0;
    int32_t j = 1;

    while (j < nRows) {
      TSKEY ti = (pBlkKeyTuple + i)->skey;
      TSKEY tj = (pBlkKeyTuple + j)->skey;

      if (ti == tj) {
        ++j;
        continue;
      }

      if ((j - i) > 1) {
C
Cary Xu 已提交
577
        if (tdBlockRowMerge(pTableMeta, (pBlkKeyTuple + j - 1), j - i, ppBlkRowMerger, extendedRowSize) < 0) {
C
Cary Xu 已提交
578 579 580
          return TSDB_CODE_FAILED;
        }
        (pBlkKeyTuple + nextPos)->payloadAddr = tdGetCurRowFromBlockMerger(*ppBlkRowMerger);
C
Cary Xu 已提交
581 582 583
        if (!hasDup) {
          hasDup = true;
        }
C
Cary Xu 已提交
584 585 586 587 588 589 590 591 592 593 594 595 596 597
        i = j;
      } else {
        if (hasDup) {
          memmove(pBlkKeyTuple + nextPos, pBlkKeyTuple + i, sizeof(SBlockKeyTuple));
        }
        ++i;
      }

      ++nextPos;
      ++j;
    }

    if ((j - i) > 1) {
      ASSERT((pBlkKeyTuple + i)->skey == (pBlkKeyTuple + j - 1)->skey);
C
Cary Xu 已提交
598
      if (tdBlockRowMerge(pTableMeta, (pBlkKeyTuple + j - 1), j - i, ppBlkRowMerger, extendedRowSize) < 0) {
C
Cary Xu 已提交
599 600 601 602 603 604 605 606
        return TSDB_CODE_FAILED;
      }
      (pBlkKeyTuple + nextPos)->payloadAddr = tdGetCurRowFromBlockMerger(*ppBlkRowMerger);
    } else if (hasDup) {
      memmove(pBlkKeyTuple + nextPos, pBlkKeyTuple + i, sizeof(SBlockKeyTuple));
    }

    dataBuf->ordered = true;
C
Cary Xu 已提交
607
    pBlocks->numOfRows = nextPos + 1;
C
Cary Xu 已提交
608 609 610 611 612 613 614 615
  }

  dataBuf->size = sizeof(SSubmitBlk) + pBlocks->numOfRows * extendedRowSize;
  dataBuf->prevTS = INT64_MIN;

  return TSDB_CODE_SUCCESS;
}

616
// Erase the empty space reserved for binary data
617
static int trimDataBlock(void* pDataBlock, STableDataBlocks* pTableDataBlock, SBlockKeyTuple* blkKeyTuple) {
618
  // TODO: optimize this function, handle the case while binary is not presented
X
Xiaoyu Wang 已提交
619
  int32_t     nonDataLen = sizeof(SSubmitBlk) + pTableDataBlock->createTbReqLen;
620
  SSubmitBlk* pBlock = pDataBlock;
X
Xiaoyu Wang 已提交
621 622
  memcpy(pDataBlock, pTableDataBlock->pData, nonDataLen);
  pDataBlock = (char*)pDataBlock + nonDataLen;
623

X
Xiaoyu Wang 已提交
624
  pBlock->schemaLen = pTableDataBlock->createTbReqLen;
625 626
  pBlock->dataLen = 0;

627 628 629 630 631 632 633
  int32_t numOfRows = pBlock->numOfRows;
  for (int32_t i = 0; i < numOfRows; ++i) {
    void*     payload = (blkKeyTuple + i)->payloadAddr;
    TDRowLenT rowTLen = TD_ROW_LEN((STSRow*)payload);
    memcpy(pDataBlock, payload, rowTLen);
    pDataBlock = POINTER_SHIFT(pDataBlock, rowTLen);
    pBlock->dataLen += rowTLen;
634 635
  }

636
  return pBlock->dataLen + pBlock->schemaLen;
637 638
}

639
int32_t insMergeTableDataBlocks(SHashObj* pHashObj, SArray** pVgDataBlocks) {
S
Shengliang Guan 已提交
640
  const int INSERT_HEAD_SIZE = sizeof(SSubmitReq);
641
  int       code = 0;
D
dapan 已提交
642
  SHashObj* pVnodeDataBlockHashList = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, false);
643 644 645
  SArray*   pVnodeDataBlockList = taosArrayInit(8, POINTER_BYTES);

  STableDataBlocks** p = taosHashIterate(pHashObj, NULL);
X
Xiaoyu Wang 已提交
646 647
  STableDataBlocks*  pOneTableBlock = *p;
  SBlockKeyInfo      blkKeyInfo = {0};  // share by pOneTableBlock
X
Xiaoyu Wang 已提交
648
  SBlockRowMerger*   pBlkRowMerger = NULL;
C
Cary Xu 已提交
649

650
  while (pOneTableBlock) {
X
Xiaoyu Wang 已提交
651
    SSubmitBlk* pBlocks = (SSubmitBlk*)pOneTableBlock->pData;
652 653
    if (pBlocks->numOfRows > 0) {
      STableDataBlocks* dataBuf = NULL;
X
Xiaoyu Wang 已提交
654
      pOneTableBlock->pTableMeta->vgId = pOneTableBlock->vgId;  // for schemaless, restore origin vgId
X
Xiaoyu Wang 已提交
655 656 657
      int32_t ret = insGetDataBlockFromList(pVnodeDataBlockHashList, &pOneTableBlock->vgId,
                                            sizeof(pOneTableBlock->vgId), TSDB_PAYLOAD_SIZE, INSERT_HEAD_SIZE, 0,
                                            pOneTableBlock->pTableMeta, &dataBuf, pVnodeDataBlockList, NULL);
658
      if (ret != TSDB_CODE_SUCCESS) {
C
Cary Xu 已提交
659
        tdFreeSBlockRowMerger(pBlkRowMerger);
660
        taosHashCleanup(pVnodeDataBlockHashList);
X
Xiaoyu Wang 已提交
661
        insDestroyBlockArrayList(pVnodeDataBlockList);
wafwerar's avatar
wafwerar 已提交
662
        taosMemoryFreeClear(blkKeyInfo.pKeyTuple);
663 664
        return ret;
      }
X
Xiaoyu Wang 已提交
665
      ASSERT(pOneTableBlock->pTableMeta->tableInfo.rowSize > 0);
666
      // the maximum expanded size in byte when a row-wise data is converted to SDataRow format
667
      int64_t destSize = dataBuf->size + pOneTableBlock->size +
X
Xiaoyu Wang 已提交
668 669
                         sizeof(STColumn) * getNumOfColumns(pOneTableBlock->pTableMeta) +
                         pOneTableBlock->createTbReqLen;
670 671 672

      if (dataBuf->nAllocSize < destSize) {
        dataBuf->nAllocSize = (uint32_t)(destSize * 1.5);
wafwerar's avatar
wafwerar 已提交
673
        char* tmp = taosMemoryRealloc(dataBuf->pData, dataBuf->nAllocSize);
674 675 676
        if (tmp != NULL) {
          dataBuf->pData = tmp;
        } else {  // failed to allocate memory, free already allocated memory and return error code
C
Cary Xu 已提交
677
          tdFreeSBlockRowMerger(pBlkRowMerger);
678
          taosHashCleanup(pVnodeDataBlockHashList);
X
Xiaoyu Wang 已提交
679
          insDestroyBlockArrayList(pVnodeDataBlockList);
wafwerar's avatar
wafwerar 已提交
680 681
          taosMemoryFreeClear(dataBuf->pData);
          taosMemoryFreeClear(blkKeyInfo.pKeyTuple);
S
Shengliang Guan 已提交
682
          return TSDB_CODE_OUT_OF_MEMORY;
683 684 685
        }
      }

686 687 688 689 690 691 692
      if ((code = sortMergeDataBlockDupRows(pOneTableBlock, &blkKeyInfo, &pBlkRowMerger)) != 0) {
        tdFreeSBlockRowMerger(pBlkRowMerger);
        taosHashCleanup(pVnodeDataBlockHashList);
        insDestroyBlockArrayList(pVnodeDataBlockList);
        taosMemoryFreeClear(dataBuf->pData);
        taosMemoryFreeClear(blkKeyInfo.pKeyTuple);
        return code;
693
      }
694
      ASSERT(blkKeyInfo.pKeyTuple != NULL && pBlocks->numOfRows > 0);
695 696

      // erase the empty space reserved for binary data
697
      int32_t finalLen = trimDataBlock(dataBuf->pData + dataBuf->size, pOneTableBlock, blkKeyInfo.pKeyTuple);
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712

      dataBuf->size += (finalLen + sizeof(SSubmitBlk));
      assert(dataBuf->size <= dataBuf->nAllocSize);
      dataBuf->numOfTables += 1;
    }

    p = taosHashIterate(pHashObj, p);
    if (p == NULL) {
      break;
    }

    pOneTableBlock = *p;
  }

  // free the table data blocks;
C
Cary Xu 已提交
713
  tdFreeSBlockRowMerger(pBlkRowMerger);
714
  taosHashCleanup(pVnodeDataBlockHashList);
wafwerar's avatar
wafwerar 已提交
715
  taosMemoryFreeClear(blkKeyInfo.pKeyTuple);
716
  *pVgDataBlocks = pVnodeDataBlockList;
717 718 719
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
720
int32_t insAllocateMemForSize(STableDataBlocks* pDataBlock, int32_t allSize) {
X
Xiaoyu Wang 已提交
721
  size_t   remain = pDataBlock->nAllocSize - pDataBlock->size;
D
stmt  
dapan1121 已提交
722
  uint32_t nAllocSizeOld = pDataBlock->nAllocSize;
X
Xiaoyu Wang 已提交
723

D
stmt  
dapan1121 已提交
724 725 726 727
  // expand the allocated size
  if (remain < allSize) {
    pDataBlock->nAllocSize = (pDataBlock->size + allSize) * 1.5;

X
Xiaoyu Wang 已提交
728
    char* tmp = taosMemoryRealloc(pDataBlock->pData, (size_t)pDataBlock->nAllocSize);
D
stmt  
dapan1121 已提交
729 730 731 732 733 734
    if (tmp != NULL) {
      pDataBlock->pData = tmp;
      memset(pDataBlock->pData + pDataBlock->size, 0, pDataBlock->nAllocSize - pDataBlock->size);
    } else {
      // do nothing, if allocate more memory failed
      pDataBlock->nAllocSize = nAllocSizeOld;
S
Shengliang Guan 已提交
735
      return TSDB_CODE_OUT_OF_MEMORY;
D
stmt  
dapan1121 已提交
736 737 738 739 740 741
    }
  }

  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
742 743 744 745 746 747 748
int32_t insInitRowBuilder(SRowBuilder* pBuilder, int16_t schemaVer, SParsedDataColInfo* pColInfo) {
  ASSERT(pColInfo->numOfCols > 0 && (pColInfo->numOfBound <= pColInfo->numOfCols));
  tdSRowInit(pBuilder, schemaVer);
  tdSRowSetExtendedInfo(pBuilder, pColInfo->numOfCols, pColInfo->numOfBound, pColInfo->flen, pColInfo->allNullLen,
                        pColInfo->boundNullLen);
  return TSDB_CODE_SUCCESS;
}
X
Xiaoyu Wang 已提交
749

X
Xiaoyu Wang 已提交
750 751 752 753 754 755 756 757
static char* tableNameGetPosition(SToken* pToken, char target) {
  bool inEscape = false;
  bool inQuote = false;
  char quotaStr = 0;

  for (uint32_t i = 0; i < pToken->n; ++i) {
    if (*(pToken->z + i) == target && (!inEscape) && (!inQuote)) {
      return pToken->z + i;
758 759
    }

X
Xiaoyu Wang 已提交
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
    if (*(pToken->z + i) == TS_ESCAPE_CHAR) {
      if (!inQuote) {
        inEscape = !inEscape;
      }
    }

    if (*(pToken->z + i) == '\'' || *(pToken->z + i) == '"') {
      if (!inEscape) {
        if (!inQuote) {
          quotaStr = *(pToken->z + i);
          inQuote = !inQuote;
        } else if (quotaStr == *(pToken->z + i)) {
          inQuote = !inQuote;
        }
      }
775 776 777
    }
  }

X
Xiaoyu Wang 已提交
778
  return NULL;
779 780
}

X
Xiaoyu Wang 已提交
781 782 783 784 785 786 787 788
int32_t insCreateSName(SName* pName, SToken* pTableName, int32_t acctId, const char* dbName, SMsgBuf* pMsgBuf) {
  const char* msg1 = "name too long";
  const char* msg2 = "invalid database name";
  const char* msg3 = "db is not specified";
  const char* msg4 = "invalid table name";

  int32_t code = TSDB_CODE_SUCCESS;
  char*   p = tableNameGetPosition(pTableName, TS_PATH_DELIMITER[0]);
D
stmt  
dapan1121 已提交
789

X
Xiaoyu Wang 已提交
790 791
  if (p != NULL) {  // db has been specified in sql string so we ignore current db path
    assert(*p == TS_PATH_DELIMITER[0]);
D
stmt  
dapan1121 已提交
792

X
Xiaoyu Wang 已提交
793 794 795
    int32_t dbLen = p - pTableName->z;
    if (dbLen <= 0) {
      return buildInvalidOperationMsg(pMsgBuf, msg2);
D
stmt  
dapan1121 已提交
796
    }
X
Xiaoyu Wang 已提交
797 798 799
    char name[TSDB_DB_FNAME_LEN] = {0};
    strncpy(name, pTableName->z, dbLen);
    int32_t actualDbLen = strdequote(name);
X
Xiaoyu Wang 已提交
800

X
Xiaoyu Wang 已提交
801 802 803 804
    code = tNameSetDbName(pName, acctId, name, actualDbLen);
    if (code != TSDB_CODE_SUCCESS) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }
X
Xiaoyu Wang 已提交
805

X
Xiaoyu Wang 已提交
806 807 808 809
    int32_t tbLen = pTableName->n - dbLen - 1;
    if (tbLen <= 0) {
      return buildInvalidOperationMsg(pMsgBuf, msg4);
    }
D
stmt  
dapan1121 已提交
810

X
Xiaoyu Wang 已提交
811 812 813
    char tbname[TSDB_TABLE_FNAME_LEN] = {0};
    strncpy(tbname, p + 1, tbLen);
    /*tbLen = */ strdequote(tbname);
D
stmt  
dapan1121 已提交
814

X
Xiaoyu Wang 已提交
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
    code = tNameFromString(pName, tbname, T_NAME_TABLE);
    if (code != 0) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }
  } else {  // get current DB name first, and then set it into path
    if (pTableName->n >= TSDB_TABLE_NAME_LEN) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }

    assert(pTableName->n < TSDB_TABLE_FNAME_LEN);

    char name[TSDB_TABLE_FNAME_LEN] = {0};
    strncpy(name, pTableName->z, pTableName->n);
    strdequote(name);

    if (dbName == NULL) {
      return buildInvalidOperationMsg(pMsgBuf, msg3);
    }
X
Xiaoyu Wang 已提交
833

X
Xiaoyu Wang 已提交
834 835 836 837 838
    code = tNameSetDbName(pName, acctId, dbName, strlen(dbName));
    if (code != TSDB_CODE_SUCCESS) {
      code = buildInvalidOperationMsg(pMsgBuf, msg2);
      return code;
    }
X
Xiaoyu Wang 已提交
839

X
Xiaoyu Wang 已提交
840 841 842
    code = tNameFromString(pName, name, T_NAME_TABLE);
    if (code != 0) {
      code = buildInvalidOperationMsg(pMsgBuf, msg1);
D
dapan1121 已提交
843 844 845
    }
  }

X
Xiaoyu Wang 已提交
846 847 848 849
  if (NULL != strchr(pName->tname, '.')) {
    code = generateSyntaxErrMsgExt(pMsgBuf, TSDB_CODE_PAR_INVALID_IDENTIFIER_NAME, "The table name cannot contain '.'");
  }

X
Xiaoyu Wang 已提交
850
  return code;
D
stmt  
dapan1121 已提交
851 852
}

D
dapan1121 已提交
853
int16_t insFindCol(SToken* pColname, int16_t start, int16_t end, SSchema* pSchema) {
X
Xiaoyu Wang 已提交
854 855 856 857 858
  while (start < end) {
    if (strlen(pSchema[start].name) == pColname->n && strncmp(pColname->z, pSchema[start].name, pColname->n) == 0) {
      return start;
    }
    ++start;
D
stmt  
dapan1121 已提交
859
  }
X
Xiaoyu Wang 已提交
860 861
  return -1;
}
D
stmt  
dapan1121 已提交
862

X
Xiaoyu Wang 已提交
863
void insBuildCreateTbReq(SVCreateTbReq* pTbReq, const char* tname, STag* pTag, int64_t suid, const char* sname,
864
                         SArray* tagName, uint8_t tagNum, int32_t ttl) {
X
Xiaoyu Wang 已提交
865 866 867 868 869 870
  pTbReq->type = TD_CHILD_TABLE;
  pTbReq->name = strdup(tname);
  pTbReq->ctb.suid = suid;
  pTbReq->ctb.tagNum = tagNum;
  if (sname) pTbReq->ctb.stbName = strdup(sname);
  pTbReq->ctb.pTag = (uint8_t*)pTag;
H
Haojun Liao 已提交
871
  pTbReq->ctb.tagName = taosArrayDup(tagName, NULL);
872
  pTbReq->ttl = ttl;
X
Xiaoyu Wang 已提交
873 874 875 876
  pTbReq->commentLen = -1;

  return;
}
D
stmt  
dapan1121 已提交
877

X
Xiaoyu Wang 已提交
878 879 880
int32_t insMemRowAppend(SMsgBuf* pMsgBuf, const void* value, int32_t len, void* param) {
  SMemParam*   pa = (SMemParam*)param;
  SRowBuilder* rb = pa->rb;
X
Xiaoyu Wang 已提交
881

X
Xiaoyu Wang 已提交
882 883 884
  if (value == NULL) {  // it is a null data
    tdAppendColValToRow(rb, pa->schema->colId, pa->schema->type, TD_VTYPE_NULL, value, false, pa->toffset, pa->colIdx);
    return TSDB_CODE_SUCCESS;
D
dapan 已提交
885
  }
X
Xiaoyu Wang 已提交
886

X
Xiaoyu Wang 已提交
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
  if (TSDB_DATA_TYPE_BINARY == pa->schema->type) {
    const char* rowEnd = tdRowEnd(rb->pBuf);
    STR_WITH_SIZE_TO_VARSTR(rowEnd, value, len);
    tdAppendColValToRow(rb, pa->schema->colId, pa->schema->type, TD_VTYPE_NORM, rowEnd, false, pa->toffset, pa->colIdx);
  } else if (TSDB_DATA_TYPE_NCHAR == pa->schema->type) {
    // if the converted output len is over than pColumnModel->bytes, return error: 'Argument list too long'
    int32_t     output = 0;
    const char* rowEnd = tdRowEnd(rb->pBuf);
    if (!taosMbsToUcs4(value, len, (TdUcs4*)varDataVal(rowEnd), pa->schema->bytes - VARSTR_HEADER_SIZE, &output)) {
      if (errno == E2BIG) {
        return generateSyntaxErrMsg(pMsgBuf, TSDB_CODE_PAR_VALUE_TOO_LONG, pa->schema->name);
      }
      char buf[512] = {0};
      snprintf(buf, tListLen(buf), "%s", strerror(errno));
      return buildSyntaxErrMsg(pMsgBuf, buf, value);
    }
    varDataSetLen(rowEnd, output);
    tdAppendColValToRow(rb, pa->schema->colId, pa->schema->type, TD_VTYPE_NORM, rowEnd, false, pa->toffset, pa->colIdx);
  } else {
    tdAppendColValToRow(rb, pa->schema->colId, pa->schema->type, TD_VTYPE_NORM, value, false, pa->toffset, pa->colIdx);
  }
D
stmt  
dapan1121 已提交
908

D
stmt  
dapan1121 已提交
909 910 911
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
912 913 914 915 916
int32_t insCheckTimestamp(STableDataBlocks* pDataBlocks, const char* start) {
  // once the data block is disordered, we do NOT keep previous timestamp any more
  if (!pDataBlocks->ordered) {
    return TSDB_CODE_SUCCESS;
  }
D
dapan 已提交
917

X
Xiaoyu Wang 已提交
918 919 920
  TSKEY k = *(TSKEY*)start;
  if (k <= pDataBlocks->prevTS) {
    pDataBlocks->ordered = false;
D
stmt  
dapan1121 已提交
921 922
  }

X
Xiaoyu Wang 已提交
923 924
  pDataBlocks->prevTS = k;
  return TSDB_CODE_SUCCESS;
D
stmt  
dapan1121 已提交
925 926
}

X
Xiaoyu Wang 已提交
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
static void buildMsgHeader(STableDataBlocks* src, SVgDataBlocks* blocks) {
  SSubmitReq* submit = (SSubmitReq*)blocks->pData;
  submit->header.vgId = htonl(blocks->vg.vgId);
  submit->header.contLen = htonl(blocks->size);
  submit->length = submit->header.contLen;
  submit->numOfBlocks = htonl(blocks->numOfTables);
  SSubmitBlk* blk = (SSubmitBlk*)(submit + 1);
  int32_t     numOfBlocks = blocks->numOfTables;
  while (numOfBlocks--) {
    int32_t dataLen = blk->dataLen;
    int32_t schemaLen = blk->schemaLen;
    blk->uid = htobe64(blk->uid);
    blk->suid = htobe64(blk->suid);
    blk->sversion = htonl(blk->sversion);
    blk->dataLen = htonl(blk->dataLen);
    blk->schemaLen = htonl(blk->schemaLen);
    blk->numOfRows = htonl(blk->numOfRows);
    blk = (SSubmitBlk*)(blk->data + schemaLen + dataLen);
D
stmt  
dapan1121 已提交
945
  }
X
Xiaoyu Wang 已提交
946
}
D
stmt  
dapan1121 已提交
947

X
Xiaoyu Wang 已提交
948 949 950 951
int32_t insBuildOutput(SHashObj* pVgroupsHashObj, SArray* pVgDataBlocks, SArray** pDataBlocks) {
  size_t numOfVg = taosArrayGetSize(pVgDataBlocks);
  *pDataBlocks = taosArrayInit(numOfVg, POINTER_BYTES);
  if (NULL == *pDataBlocks) {
S
Shengliang Guan 已提交
952
    return TSDB_CODE_OUT_OF_MEMORY;
X
Xiaoyu Wang 已提交
953 954
  }
  for (size_t i = 0; i < numOfVg; ++i) {
X
Xiaoyu Wang 已提交
955
    STableDataBlocks* src = taosArrayGetP(pVgDataBlocks, i);
X
Xiaoyu Wang 已提交
956 957
    SVgDataBlocks*    dst = taosMemoryCalloc(1, sizeof(SVgDataBlocks));
    if (NULL == dst) {
S
Shengliang Guan 已提交
958
      return TSDB_CODE_OUT_OF_MEMORY;
X
Xiaoyu Wang 已提交
959
    }
X
Xiaoyu Wang 已提交
960
    taosHashGetDup(pVgroupsHashObj, (const char*)&src->vgId, sizeof(src->vgId), &dst->vg);
X
Xiaoyu Wang 已提交
961 962 963 964
    dst->numOfTables = src->numOfTables;
    dst->size = src->size;
    TSWAP(dst->pData, src->pData);
    buildMsgHeader(src, dst);
X
Xiaoyu Wang 已提交
965
    taosArrayPush(*pDataBlocks, &dst);
X
Xiaoyu Wang 已提交
966 967
  }
  return TSDB_CODE_SUCCESS;
D
stmt  
dapan1121 已提交
968
}
X
Xiaoyu Wang 已提交
969

D
dapan1121 已提交
970
static void initBoundCols(int32_t ncols, int16_t* pBoundCols) {
X
Xiaoyu Wang 已提交
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
  for (int32_t i = 0; i < ncols; ++i) {
    pBoundCols[i] = i;
  }
}

static void initColValues(STableMeta* pTableMeta, SArray* pValues) {
  SSchema* pSchemas = getTableColumnSchema(pTableMeta);
  for (int32_t i = 0; i < pTableMeta->tableInfo.numOfColumns; ++i) {
    SColVal val = COL_VAL_NONE(pSchemas[i].colId, pSchemas[i].type);
    taosArrayPush(pValues, &val);
  }
}

int32_t insInitBoundColsInfo(int32_t numOfBound, SBoundColInfo* pInfo) {
  pInfo->numOfCols = numOfBound;
  pInfo->numOfBound = numOfBound;
D
dapan1121 已提交
987
  pInfo->pColIndex = taosMemoryCalloc(numOfBound, sizeof(int16_t));
X
Xiaoyu Wang 已提交
988 989 990 991 992 993 994
  if (NULL == pInfo->pColIndex) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  initBoundCols(numOfBound, pInfo->pColIndex);
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
995
void insCheckTableDataOrder(STableDataCxt* pTableCxt, TSKEY tsKey) {
X
Xiaoyu Wang 已提交
996
  // once the data block is disordered, we do NOT keep last timestamp any more
X
Xiaoyu Wang 已提交
997 998 999 1000
  if (!pTableCxt->ordered) {
    return;
  }

X
Xiaoyu Wang 已提交
1001
  if (tsKey < pTableCxt->lastTs) {
X
Xiaoyu Wang 已提交
1002 1003 1004
    pTableCxt->ordered = false;
  }

X
Xiaoyu Wang 已提交
1005 1006 1007 1008
  if (tsKey == pTableCxt->lastTs) {
    pTableCxt->duplicateTs = true;
  }

X
Xiaoyu Wang 已提交
1009 1010 1011 1012
  pTableCxt->lastTs = tsKey;
  return;
}

1013
void destroyBoundColInfo(SBoundColInfo* pInfo) { taosMemoryFreeClear(pInfo->pColIndex); }
X
Xiaoyu Wang 已提交
1014

H
Hongze Cheng 已提交
1015 1016
static int32_t createTableDataCxt(STableMeta* pTableMeta, SVCreateTbReq** pCreateTbReq, STableDataCxt** pOutput,
                                  bool colMode) {
X
Xiaoyu Wang 已提交
1017 1018 1019 1020 1021 1022 1023
  STableDataCxt* pTableCxt = taosMemoryCalloc(1, sizeof(STableDataCxt));
  if (NULL == pTableCxt) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  int32_t code = TSDB_CODE_SUCCESS;

X
Xiaoyu Wang 已提交
1024
  pTableCxt->lastTs = 0;
X
Xiaoyu Wang 已提交
1025 1026
  pTableCxt->ordered = true;
  pTableCxt->duplicateTs = false;
X
Xiaoyu Wang 已提交
1027

X
Xiaoyu Wang 已提交
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
  pTableCxt->pMeta = tableMetaDup(pTableMeta);
  if (NULL == pTableCxt->pMeta) {
    code = TSDB_CODE_OUT_OF_MEMORY;
  }
  if (TSDB_CODE_SUCCESS == code) {
    pTableCxt->pSchema =
        tBuildTSchema(getTableColumnSchema(pTableMeta), pTableMeta->tableInfo.numOfColumns, pTableMeta->sversion);
    if (NULL == pTableCxt->pSchema) {
      code = TSDB_CODE_OUT_OF_MEMORY;
    }
  }
  if (TSDB_CODE_SUCCESS == code) {
    code = insInitBoundColsInfo(pTableMeta->tableInfo.numOfColumns, &pTableCxt->boundColsInfo);
  }
  if (TSDB_CODE_SUCCESS == code) {
    pTableCxt->pValues = taosArrayInit(pTableMeta->tableInfo.numOfColumns, sizeof(SColVal));
    if (NULL == pTableCxt->pValues) {
      code = TSDB_CODE_OUT_OF_MEMORY;
    } else {
      initColValues(pTableMeta, pTableCxt->pValues);
    }
  }
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
1051 1052
    pTableCxt->pData = taosMemoryCalloc(1, sizeof(SSubmitTbData));
    if (NULL == pTableCxt->pData) {
X
Xiaoyu Wang 已提交
1053
      code = TSDB_CODE_OUT_OF_MEMORY;
X
Xiaoyu Wang 已提交
1054
    } else {
X
Xiaoyu Wang 已提交
1055
      pTableCxt->pData->flags = NULL != *pCreateTbReq ? SUBMIT_REQ_AUTO_CREATE_TABLE : 0;
D
dapan1121 已提交
1056
      pTableCxt->pData->flags |= colMode ? SUBMIT_REQ_COLUMN_DATA_FORMAT : 0;
X
Xiaoyu Wang 已提交
1057 1058 1059
      pTableCxt->pData->suid = pTableMeta->suid;
      pTableCxt->pData->uid = pTableMeta->uid;
      pTableCxt->pData->sver = pTableMeta->sversion;
X
Xiaoyu Wang 已提交
1060 1061
      pTableCxt->pData->pCreateTbReq = *pCreateTbReq;
      *pCreateTbReq = NULL;
D
dapan1121 已提交
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
      if (pTableCxt->pData->flags & SUBMIT_REQ_COLUMN_DATA_FORMAT) {
        pTableCxt->pData->aCol = taosArrayInit(128, sizeof(SColData));
        if (NULL == pTableCxt->pData->aCol) {
          code = TSDB_CODE_OUT_OF_MEMORY;
        }
      } else {
        pTableCxt->pData->aRowP = taosArrayInit(128, POINTER_BYTES);
        if (NULL == pTableCxt->pData->aRowP) {
          code = TSDB_CODE_OUT_OF_MEMORY;
        }
X
Xiaoyu Wang 已提交
1072
      }
X
Xiaoyu Wang 已提交
1073 1074 1075 1076 1077
    }
  }

  if (TSDB_CODE_SUCCESS == code) {
    *pOutput = pTableCxt;
D
dapan1121 已提交
1078
    qDebug("tableDataCxt created, uid:%" PRId64 ", vgId:%d", pTableMeta->uid, pTableMeta->vgId);
X
Xiaoyu Wang 已提交
1079 1080 1081 1082 1083 1084 1085
  } else {
    taosMemoryFree(pTableCxt);
  }

  return code;
}

X
Xiaoyu Wang 已提交
1086 1087 1088 1089 1090 1091 1092 1093
static void resetColValues(SArray* pValues) {
  int32_t num = taosArrayGetSize(pValues);
  for (int32_t i = 0; i < num; ++i) {
    SColVal* pVal = taosArrayGet(pValues, i);
    pVal->flag = CV_FLAG_NONE;
  }
}

X
Xiaoyu Wang 已提交
1094
int32_t insGetTableDataCxt(SHashObj* pHash, void* id, int32_t idLen, STableMeta* pTableMeta,
D
dapan1121 已提交
1095
                           SVCreateTbReq** pCreateTbReq, STableDataCxt** pTableCxt, bool colMode) {
wmmhello's avatar
wmmhello 已提交
1096 1097 1098
  STableDataCxt** tmp = (STableDataCxt**)taosHashGet(pHash, id, idLen);
  if (NULL != tmp) {
    *pTableCxt = *tmp;
X
Xiaoyu Wang 已提交
1099
    resetColValues((*pTableCxt)->pValues);
X
Xiaoyu Wang 已提交
1100 1101
    return TSDB_CODE_SUCCESS;
  }
D
dapan1121 已提交
1102
  int32_t code = createTableDataCxt(pTableMeta, pCreateTbReq, pTableCxt, colMode);
X
Xiaoyu Wang 已提交
1103 1104 1105 1106 1107 1108
  if (TSDB_CODE_SUCCESS == code) {
    code = taosHashPut(pHash, id, idLen, pTableCxt, POINTER_BYTES);
  }
  return code;
}

X
Xiaoyu Wang 已提交
1109 1110 1111 1112 1113 1114 1115
static void destroyColVal(void* p) {
  SColVal* pVal = p;
  if (TSDB_DATA_TYPE_NCHAR == pVal->type) {
    taosMemoryFree(pVal->value.pData);
  }
}

X
Xiaoyu Wang 已提交
1116 1117 1118 1119 1120 1121 1122 1123
void insDestroyTableDataCxt(STableDataCxt* pTableCxt) {
  if (NULL == pTableCxt) {
    return;
  }

  taosMemoryFreeClear(pTableCxt->pMeta);
  tDestroyTSchema(pTableCxt->pSchema);
  destroyBoundColInfo(&pTableCxt->boundColsInfo);
X
Xiaoyu Wang 已提交
1124
  taosArrayDestroyEx(pTableCxt->pValues, destroyColVal);
H
Hongze Cheng 已提交
1125
  if (pTableCxt->pData) {
H
Hongze Cheng 已提交
1126
    tDestroySSubmitTbData(pTableCxt->pData, TSDB_MSG_FLG_ENCODE);
H
Hongze Cheng 已提交
1127 1128
    taosMemoryFree(pTableCxt->pData);
  }
X
Xiaoyu Wang 已提交
1129
  taosMemoryFree(pTableCxt);
X
Xiaoyu Wang 已提交
1130 1131 1132 1133 1134 1135 1136
}

void insDestroyVgroupDataCxt(SVgroupDataCxt* pVgCxt) {
  if (NULL == pVgCxt) {
    return;
  }

H
Hongze Cheng 已提交
1137
  tDestroySSubmitReq2(pVgCxt->pData, TSDB_MSG_FLG_ENCODE);
D
dapan1121 已提交
1138
  taosMemoryFree(pVgCxt->pData);
X
Xiaoyu Wang 已提交
1139
  taosMemoryFree(pVgCxt);
X
Xiaoyu Wang 已提交
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
}

void insDestroyVgroupDataCxtList(SArray* pVgCxtList) {
  if (NULL == pVgCxtList) {
    return;
  }

  size_t size = taosArrayGetSize(pVgCxtList);
  for (int32_t i = 0; i < size; i++) {
    void* p = taosArrayGetP(pVgCxtList, i);
    insDestroyVgroupDataCxt(p);
  }

  taosArrayDestroy(pVgCxtList);
}

void insDestroyVgroupDataCxtHashMap(SHashObj* pVgCxtHash) {
  if (NULL == pVgCxtHash) {
    return;
  }

  void** p = taosHashIterate(pVgCxtHash, NULL);
  while (p) {
    insDestroyVgroupDataCxt(*(SVgroupDataCxt**)p);

    p = taosHashIterate(pVgCxtHash, p);
  }

  taosHashCleanup(pVgCxtHash);
}

void insDestroyTableDataCxtHashMap(SHashObj* pTableCxtHash) {
  if (NULL == pTableCxtHash) {
    return;
  }

  void** p = taosHashIterate(pTableCxtHash, NULL);
  while (p) {
    insDestroyTableDataCxt(*(STableDataCxt**)p);

    p = taosHashIterate(pTableCxtHash, p);
  }

  taosHashCleanup(pTableCxtHash);
}

static int32_t fillVgroupDataCxt(STableDataCxt* pTableCxt, SVgroupDataCxt* pVgCxt) {
X
Xiaoyu Wang 已提交
1187 1188 1189
  if (NULL == pVgCxt->pData->aSubmitTbData) {
    pVgCxt->pData->aSubmitTbData = taosArrayInit(128, sizeof(SSubmitTbData));
    if (NULL == pVgCxt->pData->aSubmitTbData) {
X
Xiaoyu Wang 已提交
1190 1191 1192
      return TSDB_CODE_OUT_OF_MEMORY;
    }
  }
X
Xiaoyu Wang 已提交
1193
  taosArrayPush(pVgCxt->pData->aSubmitTbData, pTableCxt->pData);
X
Xiaoyu Wang 已提交
1194
  taosMemoryFreeClear(pTableCxt->pData);
X
Xiaoyu Wang 已提交
1195

D
dapan1121 已提交
1196 1197
  qDebug("add tableDataCxt uid:%" PRId64 " to vgId:%d", pTableCxt->pMeta->uid, pVgCxt->vgId);

X
Xiaoyu Wang 已提交
1198 1199 1200
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
static int32_t createVgroupDataCxt(STableDataCxt* pTableCxt, SHashObj* pVgroupHash, SArray* pVgroupList,
                                   SVgroupDataCxt** pOutput) {
  SVgroupDataCxt* pVgCxt = taosMemoryCalloc(1, sizeof(SVgroupDataCxt));
  if (NULL == pVgCxt) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  pVgCxt->pData = taosMemoryCalloc(1, sizeof(SSubmitReq2));
  if (NULL == pVgCxt->pData) {
    insDestroyVgroupDataCxt(pVgCxt);
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  pVgCxt->vgId = pTableCxt->pMeta->vgId;
  int32_t code = taosHashPut(pVgroupHash, &pVgCxt->vgId, sizeof(pVgCxt->vgId), &pVgCxt, POINTER_BYTES);
  if (TSDB_CODE_SUCCESS == code) {
    taosArrayPush(pVgroupList, &pVgCxt);
    *pOutput = pVgCxt;
  } else {
    insDestroyVgroupDataCxt(pVgCxt);
  }
  return code;
}

D
dapan1121 已提交
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235
int insColDataComp(const void* lp, const void* rp) {
  SColData* pLeft = (SColData*)lp;
  SColData* pRight = (SColData*)rp;
  if (pLeft->cid < pRight->cid) {
    return -1;
  } else if (pLeft->cid > pRight->cid) {
    return 1;
  }

  return 0;
}

X
Xiaoyu Wang 已提交
1236 1237 1238 1239 1240 1241
int32_t insMergeTableDataCxt(SHashObj* pTableHash, SArray** pVgDataBlocks) {
  SHashObj* pVgroupHash = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, false);
  SArray*   pVgroupList = taosArrayInit(8, POINTER_BYTES);
  if (NULL == pVgroupHash || NULL == pVgroupList) {
    taosHashCleanup(pVgroupHash);
    taosArrayDestroy(pVgroupList);
H
Hongze Cheng 已提交
1242
    return TSDB_CODE_OUT_OF_MEMORY;
X
Xiaoyu Wang 已提交
1243 1244 1245
  }

  int32_t code = TSDB_CODE_SUCCESS;
H
Hongze Cheng 已提交
1246 1247
  bool    colFormat = false;

X
Xiaoyu Wang 已提交
1248
  void* p = taosHashIterate(pTableHash, NULL);
D
dapan1121 已提交
1249 1250 1251 1252
  if (p) {
    STableDataCxt* pTableCxt = *(STableDataCxt**)p;
    colFormat = (0 != (pTableCxt->pData->flags & SUBMIT_REQ_COLUMN_DATA_FORMAT));
  }
H
Hongze Cheng 已提交
1253

X
Xiaoyu Wang 已提交
1254 1255
  while (TSDB_CODE_SUCCESS == code && NULL != p) {
    STableDataCxt* pTableCxt = *(STableDataCxt**)p;
D
dapan1121 已提交
1256
    if (colFormat) {
H
Hongze Cheng 已提交
1257
      SColData* pCol = taosArrayGet(pTableCxt->pData->aCol, 0);
D
dapan1121 已提交
1258 1259 1260 1261
      if (pCol->nVal <= 0) {
        p = taosHashIterate(pTableHash, p);
        continue;
      }
H
Hongze Cheng 已提交
1262

D
dapan1121 已提交
1263 1264 1265
      if (pTableCxt->pData->pCreateTbReq) {
        pTableCxt->pData->flags |= SUBMIT_REQ_AUTO_CREATE_TABLE;
      }
H
Hongze Cheng 已提交
1266

D
dapan1121 已提交
1267
      taosArraySort(pTableCxt->pData->aCol, insColDataComp);
H
Hongze Cheng 已提交
1268

D
dapan1121 已提交
1269
      tColDataSortMerge(pTableCxt->pData->aCol);
D
dapan1121 已提交
1270
    } else {
1271 1272 1273 1274 1275 1276
      if (!pTableCxt->ordered) {
        tRowSort(pTableCxt->pData->aRowP);
      }
      if (!pTableCxt->ordered || pTableCxt->duplicateTs) {
        code = tRowMerge(pTableCxt->pData->aRowP, pTableCxt->pSchema, 0);
      }
D
dapan1121 已提交
1277
    }
H
Hongze Cheng 已提交
1278

X
Xiaoyu Wang 已提交
1279
    if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
1280
      SVgroupDataCxt* pVgCxt = NULL;
X
Xiaoyu Wang 已提交
1281
      int32_t         vgId = pTableCxt->pMeta->vgId;
X
Xiaoyu Wang 已提交
1282 1283
      void**          p = taosHashGet(pVgroupHash, &vgId, sizeof(vgId));
      if (NULL == p) {
X
Xiaoyu Wang 已提交
1284
        code = createVgroupDataCxt(pTableCxt, pVgroupHash, pVgroupList, &pVgCxt);
X
Xiaoyu Wang 已提交
1285 1286
      } else {
        pVgCxt = *(SVgroupDataCxt**)p;
X
Xiaoyu Wang 已提交
1287 1288
      }
      if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
        code = fillVgroupDataCxt(pTableCxt, pVgCxt);
      }
    }
    if (TSDB_CODE_SUCCESS == code) {
      p = taosHashIterate(pTableHash, p);
    }
  }

  taosHashCleanup(pVgroupHash);
  if (TSDB_CODE_SUCCESS == code) {
    *pVgDataBlocks = pVgroupList;
  } else {
D
dapan1121 已提交
1301
    insDestroyVgroupDataCxtList(pVgroupList);
X
Xiaoyu Wang 已提交
1302 1303 1304 1305 1306
  }

  return code;
}

X
Xiaoyu Wang 已提交
1307 1308 1309 1310 1311
static int32_t buildSubmitReq(int32_t vgId, SSubmitReq2* pReq, void** pData, uint32_t* pLen) {
  int32_t  code = TSDB_CODE_SUCCESS;
  uint32_t len = 0;
  void*    pBuf = NULL;
  tEncodeSize(tEncodeSSubmitReq2, pReq, len, code);
X
Xiaoyu Wang 已提交
1312 1313
  if (TSDB_CODE_SUCCESS == code) {
    SEncoder encoder;
X
Xiaoyu Wang 已提交
1314 1315 1316
    len += sizeof(SMsgHead);
    pBuf = taosMemoryMalloc(len);
    if (NULL == pBuf) {
H
Hongze Cheng 已提交
1317
      return TSDB_CODE_OUT_OF_MEMORY;
X
Xiaoyu Wang 已提交
1318
    }
X
Xiaoyu Wang 已提交
1319 1320 1321
    ((SMsgHead*)pBuf)->vgId = htonl(vgId);
    ((SMsgHead*)pBuf)->contLen = htonl(len);
    tEncoderInit(&encoder, POINTER_SHIFT(pBuf, sizeof(SMsgHead)), len - sizeof(SMsgHead));
X
Xiaoyu Wang 已提交
1322 1323 1324
    code = tEncodeSSubmitReq2(&encoder, pReq);
    tEncoderClear(&encoder);
  }
X
Xiaoyu Wang 已提交
1325 1326 1327 1328 1329 1330

  if (TSDB_CODE_SUCCESS == code) {
    *pData = pBuf;
    *pLen = len;
  } else {
    taosMemoryFree(pBuf);
X
Xiaoyu Wang 已提交
1331 1332 1333 1334
  }
  return code;
}

X
Xiaoyu Wang 已提交
1335 1336 1337 1338 1339 1340
static void destroyVgDataBlocks(void* p) {
  SVgDataBlocks* pVg = p;
  taosMemoryFree(pVg->pData);
  taosMemoryFree(pVg);
}

X
Xiaoyu Wang 已提交
1341 1342 1343 1344
int32_t insBuildVgDataBlocks(SHashObj* pVgroupsHashObj, SArray* pVgDataCxtList, SArray** pVgDataBlocks) {
  size_t  numOfVg = taosArrayGetSize(pVgDataCxtList);
  SArray* pDataBlocks = taosArrayInit(numOfVg, POINTER_BYTES);
  if (NULL == pDataBlocks) {
H
Hongze Cheng 已提交
1345
    return TSDB_CODE_OUT_OF_MEMORY;
X
Xiaoyu Wang 已提交
1346 1347 1348 1349 1350 1351 1352
  }

  int32_t code = TSDB_CODE_SUCCESS;
  for (size_t i = 0; TSDB_CODE_SUCCESS == code && i < numOfVg; ++i) {
    SVgroupDataCxt* src = taosArrayGetP(pVgDataCxtList, i);
    SVgDataBlocks*  dst = taosMemoryCalloc(1, sizeof(SVgDataBlocks));
    if (NULL == dst) {
H
Hongze Cheng 已提交
1353
      code = TSDB_CODE_OUT_OF_MEMORY;
X
Xiaoyu Wang 已提交
1354 1355
    }
    if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
1356
      dst->numOfTables = taosArrayGetSize(src->pData->aSubmitTbData);
X
Xiaoyu Wang 已提交
1357 1358 1359
      code = taosHashGetDup(pVgroupsHashObj, (const char*)&src->vgId, sizeof(src->vgId), &dst->vg);
    }
    if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
1360
      code = buildSubmitReq(src->vgId, src->pData, &dst->pData, &dst->size);
X
Xiaoyu Wang 已提交
1361 1362
    }
    if (TSDB_CODE_SUCCESS == code) {
H
Hongze Cheng 已提交
1363
      code = (NULL == taosArrayPush(pDataBlocks, &dst) ? TSDB_CODE_OUT_OF_MEMORY : TSDB_CODE_SUCCESS);
X
Xiaoyu Wang 已提交
1364 1365 1366 1367 1368 1369
    }
  }

  if (TSDB_CODE_SUCCESS == code) {
    *pVgDataBlocks = pDataBlocks;
  } else {
X
Xiaoyu Wang 已提交
1370
    taosArrayDestroyP(pDataBlocks, destroyVgDataBlocks);
X
Xiaoyu Wang 已提交
1371 1372 1373 1374
  }

  return code;
}
wmmhello's avatar
wmmhello 已提交
1375

wmmhello's avatar
wmmhello 已提交
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
static int bindFileds(SBoundColInfo* pBoundInfo, SSchema* pSchema, TAOS_FIELD *fields, int numFields){
  bool* pUseCols = taosMemoryCalloc(pBoundInfo->numOfCols, sizeof(bool));
  if (NULL == pUseCols) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  pBoundInfo->numOfBound = 0;

  int16_t lastColIdx = -1;  // last column found
  int32_t code = TSDB_CODE_SUCCESS;
  for(int i = 0; i < numFields; i++) {
    SToken token;
    token.z = fields[i].name;
    token.n = strlen(fields[i].name);

    int16_t t = lastColIdx + 1;
    int16_t index = insFindCol(&token, t, pBoundInfo->numOfCols, pSchema);
    if (index < 0 && t > 0) {
      index = insFindCol(&token, 0, t, pSchema);
    }
    if (index < 0) {
      uError("can not find column name:%s", token.z);
      code = TSDB_CODE_PAR_INVALID_COLUMN;
      break;
    } else if (pUseCols[index]) {
      code = TSDB_CODE_PAR_INVALID_COLUMN;
      uError("duplicated column name:%s", token.z);
      break;
    } else {
      lastColIdx = index;
      pUseCols[index] = true;
      pBoundInfo->pColIndex[pBoundInfo->numOfBound] = index;
      ++pBoundInfo->numOfBound;
    }
  }

  if (TSDB_CODE_SUCCESS == code && !pUseCols[0]) {
    uError("primary timestamp column can not be null:");
    code = TSDB_CODE_PAR_INVALID_COLUMN;
  }

  taosMemoryFree(pUseCols);
  return code;
}

int rawBlockBindData(SQuery *query, STableMeta* pTableMeta, void* data, SVCreateTbReq *pCreateTb, TAOS_FIELD *tFields, int numFields){
wmmhello's avatar
wmmhello 已提交
1422 1423 1424 1425 1426 1427 1428
  STableDataCxt* pTableCxt = NULL;
  int ret = insGetTableDataCxt(((SVnodeModifOpStmt *)(query->pRoot))->pTableBlockHashObj, &pTableMeta->uid, sizeof(pTableMeta->uid),
                           pTableMeta, &pCreateTb, &pTableCxt, true);
  if (ret != TSDB_CODE_SUCCESS) {
    uError("insGetTableDataCxt error");
    goto end;
  }
wmmhello's avatar
wmmhello 已提交
1429 1430 1431 1432 1433 1434 1435
  if (tFields != NULL){
    ret = bindFileds(&pTableCxt->boundColsInfo, getTableColumnSchema(pTableMeta), tFields, numFields);
    if (ret != TSDB_CODE_SUCCESS) {
      uError("bindFileds error");
      goto end;
    }
  }
wmmhello's avatar
wmmhello 已提交
1436 1437 1438 1439 1440 1441 1442
  // no need to bind, because select * get all fields
  ret = initTableColSubmitData(pTableCxt);
  if (ret != TSDB_CODE_SUCCESS) {
    uError( "initTableColSubmitData error");
    goto end;
  }

wmmhello's avatar
wmmhello 已提交
1443
  char* p = (char*)data;
wmmhello's avatar
wmmhello 已提交
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
  // | version | total length | total rows | total columns | flag seg| block group id | column schema | each column length |
  p += sizeof(int32_t);
  p += sizeof(int32_t);

  int32_t numOfRows = *(int32_t*)p;
  p += sizeof(int32_t);

  int32_t numOfCols = *(int32_t*)p;
  p += sizeof(int32_t);

  p += sizeof(int32_t);
  p += sizeof(uint64_t);

  int8_t *fields = p;
  p += numOfCols * (sizeof(int8_t) + sizeof(int32_t));

  int32_t* colLength = (int32_t*)p;
  p += sizeof(int32_t) * numOfCols;

  char* pStart = p;

  SSchema*            pSchema = getTableColumnSchema(pTableCxt->pMeta);
  SBoundColInfo*      boundInfo = &pTableCxt->boundColsInfo;

  if(boundInfo->numOfBound != numOfCols){
    uError("boundInfo->numOfBound:%d != numOfCols:%d", boundInfo->numOfBound, numOfCols);
    ret = TSDB_CODE_INVALID_PARA;
    goto end;
  }
  for (int c = 0; c < boundInfo->numOfBound; ++c) {
    SSchema* pColSchema = &pSchema[boundInfo->pColIndex[c]];
    SColData* pCol = taosArrayGet(pTableCxt->pData->aCol, c);

    if (*fields != pColSchema->type && *(int32_t*)(fields + sizeof(int8_t)) != pColSchema->bytes) {
      uError( "type or bytes not equal");
      ret = TSDB_CODE_INVALID_PARA;
      goto end;
    }

    colLength[c] = htonl(colLength[c]);
    int8_t* offset = pStart;
    if (IS_VAR_DATA_TYPE(pColSchema->type)) {
      pStart += numOfRows * sizeof(int32_t);
    } else {
      pStart += BitmapLen(numOfRows);
    }
    char *pData = pStart;

    tColDataAddValueByDataBlock(pCol, pColSchema->type, pColSchema->bytes, numOfRows, offset, pData);
    fields += sizeof(int8_t) + sizeof(int32_t);
    pStart += colLength[c];
  }

end:
  return ret;
}