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

#define _DEFAULT_SOURCE
H
Haojun Liao 已提交
17
#include "tdatablock.h"
S
compare  
Shengliang Guan 已提交
18
#include "tcompare.h"
19
#include "tglobal.h"
20
#include "tlog.h"
21
#include "tname.h"
22

L
Liu Jicong 已提交
23
int32_t taosGetFqdnPortFromEp(const char* ep, SEp* pEp) {
H
Haojun Liao 已提交
24 25
  pEp->port = 0;
  strcpy(pEp->fqdn, ep);
26

L
Liu Jicong 已提交
27
  char* temp = strchr(pEp->fqdn, ':');
28 29
  if (temp) {
    *temp = 0;
L
Liu Jicong 已提交
30
    pEp->port = atoi(temp + 1);
31 32
  }

H
Haojun Liao 已提交
33
  if (pEp->port == 0) {
S
Shengliang Guan 已提交
34
    pEp->port = tsServerPort;
35 36 37 38 39
  }

  return 0;
}

L
Liu Jicong 已提交
40
void addEpIntoEpSet(SEpSet* pEpSet, const char* fqdn, uint16_t port) {
H
Haojun Liao 已提交
41 42 43 44 45 46 47 48 49 50
  if (pEpSet == NULL || fqdn == NULL || strlen(fqdn) == 0) {
    return;
  }

  int32_t index = pEpSet->numOfEps;
  tstrncpy(pEpSet->eps[index].fqdn, fqdn, tListLen(pEpSet->eps[index].fqdn));
  pEpSet->eps[index].port = port;
  pEpSet->numOfEps += 1;
}

L
Liu Jicong 已提交
51
bool isEpsetEqual(const SEpSet* s1, const SEpSet* s2) {
52 53 54 55 56
  if (s1->numOfEps != s2->numOfEps || s1->inUse != s2->inUse) {
    return false;
  }

  for (int32_t i = 0; i < s1->numOfEps; i++) {
L
Liu Jicong 已提交
57
    if (s1->eps[i].port != s2->eps[i].port || strncmp(s1->eps[i].fqdn, s2->eps[i].fqdn, TSDB_FQDN_LEN) != 0)
58 59 60 61 62
      return false;
  }
  return true;
}

L
Liu Jicong 已提交
63
void updateEpSet_s(SCorEpSet* pEpSet, SEpSet* pNewEpSet) {
64 65 66 67 68
  taosCorBeginWrite(&pEpSet->version);
  pEpSet->epSet = *pNewEpSet;
  taosCorEndWrite(&pEpSet->version);
}

L
Liu Jicong 已提交
69
SEpSet getEpSet_s(SCorEpSet* pEpSet) {
70 71 72 73 74 75 76 77
  SEpSet ep = {0};
  taosCorBeginRead(&pEpSet->version);
  ep = pEpSet->epSet;
  taosCorEndRead(&pEpSet->version);

  return ep;
}

78
int32_t colDataGetLength(const SColumnInfoData* pColumnInfoData, int32_t numOfRows) {
H
Haojun Liao 已提交
79 80 81 82
  ASSERT(pColumnInfoData != NULL);
  if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
    return pColumnInfoData->varmeta.length;
  } else {
83 84 85 86 87
    if (pColumnInfoData->info.type == TSDB_DATA_TYPE_NULL) {
      return 0;
    } else {
      return pColumnInfoData->info.bytes * numOfRows;
    }
H
Haojun Liao 已提交
88 89 90
  }
}

H
Haojun Liao 已提交
91 92 93 94 95 96 97 98
int32_t colDataGetFullLength(const SColumnInfoData* pColumnInfoData, int32_t numOfRows) {
  if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
    return pColumnInfoData->varmeta.length + sizeof(int32_t) * numOfRows;
  } else {
    return pColumnInfoData->info.bytes * numOfRows + BitmapLen(numOfRows);
  }
}

H
Haojun Liao 已提交
99 100 101 102
void colDataTrim(SColumnInfoData* pColumnInfoData) {
  // TODO
}

103
int32_t getJsonValueLen(const char* data) {
wmmhello's avatar
wmmhello 已提交
104 105 106 107 108 109 110 111 112
  int32_t dataLen = 0;
  if (*data == TSDB_DATA_TYPE_NULL) {
    dataLen = CHAR_BYTES;
  } else if (*data == TSDB_DATA_TYPE_NCHAR) {
    dataLen = varDataTLen(data + CHAR_BYTES) + CHAR_BYTES;
  } else if (*data == TSDB_DATA_TYPE_DOUBLE) {
    dataLen = DOUBLE_BYTES + CHAR_BYTES;
  } else if (*data == TSDB_DATA_TYPE_BOOL) {
    dataLen = CHAR_BYTES + CHAR_BYTES;
wmmhello's avatar
wmmhello 已提交
113
  } else if (tTagIsJson(data)) {  // json string
wmmhello's avatar
wmmhello 已提交
114 115 116 117 118 119 120
    dataLen = ((STag*)(data))->len;
  } else {
    ASSERT(0);
  }
  return dataLen;
}

121 122 123 124
int32_t colDataAppend(SColumnInfoData* pColumnInfoData, uint32_t currentRow, const char* pData, bool isNull) {
  ASSERT(pColumnInfoData != NULL);

  if (isNull) {
H
Haojun Liao 已提交
125 126
    // There is a placehold for each NULL value of binary or nchar type.
    if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
L
Liu Jicong 已提交
127
      pColumnInfoData->varmeta.offset[currentRow] = -1;  // it is a null value of VAR type.
H
Haojun Liao 已提交
128 129 130 131
    } else {
      colDataSetNull_f(pColumnInfoData->nullbitmap, currentRow);
    }

H
Haojun Liao 已提交
132
    pColumnInfoData->hasNull = true;
133 134 135 136 137
    return 0;
  }

  int32_t type = pColumnInfoData->info.type;
  if (IS_VAR_DATA_TYPE(type)) {
wmmhello's avatar
wmmhello 已提交
138
    int32_t dataLen = 0;
139
    if (type == TSDB_DATA_TYPE_JSON) {
wmmhello's avatar
wmmhello 已提交
140
      dataLen = getJsonValueLen(pData);
141
    } else {
wmmhello's avatar
wmmhello 已提交
142
      dataLen = varDataTLen(pData);
143
    }
144

H
Haojun Liao 已提交
145
    SVarColAttr* pAttr = &pColumnInfoData->varmeta;
146
    if (pAttr->allocLen < pAttr->length + dataLen) {
H
Haojun Liao 已提交
147
      uint32_t newSize = pAttr->allocLen;
148
      if (newSize <= 1) {
H
Haojun Liao 已提交
149 150 151
        newSize = 8;
      }

152
      while (newSize < pAttr->length + dataLen) {
H
Haojun Liao 已提交
153 154 155
        newSize = newSize * 1.5;
      }

wafwerar's avatar
wafwerar 已提交
156
      char* buf = taosMemoryRealloc(pColumnInfoData->pData, newSize);
H
Haojun Liao 已提交
157
      if (buf == NULL) {
H
Haojun Liao 已提交
158
        return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
159 160 161 162 163 164 165 166 167
      }

      pColumnInfoData->pData = buf;
      pAttr->allocLen = newSize;
    }

    uint32_t len = pColumnInfoData->varmeta.length;
    pColumnInfoData->varmeta.offset[currentRow] = len;

168 169
    memcpy(pColumnInfoData->pData + len, pData, dataLen);
    pColumnInfoData->varmeta.length += dataLen;
170
  } else {
wmmhello's avatar
wmmhello 已提交
171
    memcpy(pColumnInfoData->pData + pColumnInfoData->info.bytes * currentRow, pData, pColumnInfoData->info.bytes);
172 173 174 175 176
  }

  return 0;
}

L
Liu Jicong 已提交
177 178
static void doBitmapMerge(SColumnInfoData* pColumnInfoData, int32_t numOfRow1, const SColumnInfoData* pSource,
                          int32_t numOfRow2) {
wmmhello's avatar
wmmhello 已提交
179 180
  if (numOfRow2 <= 0) return;

H
Haojun Liao 已提交
181 182 183 184 185 186 187
  uint32_t total = numOfRow1 + numOfRow2;

  uint32_t remindBits = BitPos(numOfRow1);
  uint32_t shiftBits = 8 - remindBits;

  if (remindBits == 0) {  // no need to shift bits of bitmap
    memcpy(pColumnInfoData->nullbitmap + BitmapLen(numOfRow1), pSource->nullbitmap, BitmapLen(numOfRow2));
wmmhello's avatar
wmmhello 已提交
188 189
    return;
  }
H
Haojun Liao 已提交
190

wmmhello's avatar
wmmhello 已提交
191 192
  uint8_t* p = (uint8_t*)pSource->nullbitmap;
  pColumnInfoData->nullbitmap[BitmapLen(numOfRow1) - 1] |= (p[0] >> remindBits);  // copy remind bits
H
Haojun Liao 已提交
193

wmmhello's avatar
wmmhello 已提交
194 195 196
  if (BitmapLen(numOfRow1) == BitmapLen(total)) {
    return;
  }
H
Haojun Liao 已提交
197

wmmhello's avatar
wmmhello 已提交
198 199
  int32_t len = BitmapLen(numOfRow2);
  int32_t i = 0;
H
Haojun Liao 已提交
200

wmmhello's avatar
wmmhello 已提交
201
  uint8_t* start = (uint8_t*)&pColumnInfoData->nullbitmap[BitmapLen(numOfRow1)];
C
Cary Xu 已提交
202 203
  int32_t  overCount = BitmapLen(total) - BitmapLen(numOfRow1);
  while (i < len) {  // size limit of pSource->nullbitmap
wmmhello's avatar
wmmhello 已提交
204
    if (i >= 1) {
C
Cary Xu 已提交
205
      start[i - 1] |= (p[i] >> remindBits);  // copy remind bits
H
Haojun Liao 已提交
206
    }
wmmhello's avatar
wmmhello 已提交
207

C
Cary Xu 已提交
208
    if (i >= overCount) {  // size limit of pColumnInfoData->nullbitmap
wmmhello's avatar
wmmhello 已提交
209 210 211
      return;
    }

C
Cary Xu 已提交
212
    start[i] |= (p[i] << shiftBits);  // copy shift bits
wmmhello's avatar
wmmhello 已提交
213
    i += 1;
H
Haojun Liao 已提交
214 215 216
  }
}

217
int32_t colDataMergeCol(SColumnInfoData* pColumnInfoData, uint32_t numOfRow1, uint32_t* capacity,
218
                        const SColumnInfoData* pSource, uint32_t numOfRow2) {
H
Haojun Liao 已提交
219 220 221 222 223
  ASSERT(pColumnInfoData != NULL && pSource != NULL && pColumnInfoData->info.type == pSource->info.type);
  if (numOfRow2 == 0) {
    return numOfRow1;
  }

wmmhello's avatar
wmmhello 已提交
224 225 226
  if (pSource->hasNull) {
    pColumnInfoData->hasNull = pSource->hasNull;
  }
227

228
  uint32_t finalNumOfRows = numOfRow1 + numOfRow2;
H
Haojun Liao 已提交
229 230
  if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
    // Handle the bitmap
231
    if (finalNumOfRows > *capacity || numOfRow1 == 0) {
232 233 234 235 236 237 238
      char* p = taosMemoryRealloc(pColumnInfoData->varmeta.offset, sizeof(int32_t) * (numOfRow1 + numOfRow2));
      if (p == NULL) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }

      *capacity = finalNumOfRows;
      pColumnInfoData->varmeta.offset = (int32_t*)p;
H
Haojun Liao 已提交
239 240
    }

L
Liu Jicong 已提交
241
    for (int32_t i = 0; i < numOfRow2; ++i) {
242 243 244 245 246
      if (pSource->varmeta.offset[i] == -1) {
        pColumnInfoData->varmeta.offset[i + numOfRow1] = -1;
      } else {
        pColumnInfoData->varmeta.offset[i + numOfRow1] = pSource->varmeta.offset[i] + pColumnInfoData->varmeta.length;
      }
247
    }
H
Haojun Liao 已提交
248

249
    // copy data
H
Haojun Liao 已提交
250 251 252
    uint32_t len = pSource->varmeta.length;
    uint32_t oldLen = pColumnInfoData->varmeta.length;
    if (pColumnInfoData->varmeta.allocLen < len + oldLen) {
wafwerar's avatar
wafwerar 已提交
253
      char* tmp = taosMemoryRealloc(pColumnInfoData->pData, len + oldLen);
H
Haojun Liao 已提交
254
      if (tmp == NULL) {
255
        return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
256 257 258 259 260 261
      }

      pColumnInfoData->pData = tmp;
      pColumnInfoData->varmeta.allocLen = len + oldLen;
    }

262 263
    memcpy(pColumnInfoData->pData + oldLen, pSource->pData, len);
    pColumnInfoData->varmeta.length = len + oldLen;
H
Haojun Liao 已提交
264
  } else {
265
    if (finalNumOfRows > *capacity || numOfRow1 == 0) {
L
Liu Jicong 已提交
266
      ASSERT(finalNumOfRows * pColumnInfoData->info.bytes);
267
      char* tmp = taosMemoryRealloc(pColumnInfoData->pData, finalNumOfRows * pColumnInfoData->info.bytes);
268 269 270
      if (tmp == NULL) {
        return TSDB_CODE_VND_OUT_OF_MEMORY;
      }
H
Haojun Liao 已提交
271

272 273 274 275 276 277 278 279 280 281 282
      pColumnInfoData->pData = tmp;

      if (BitmapLen(numOfRow1) < BitmapLen(finalNumOfRows)) {
        char*    btmp = taosMemoryRealloc(pColumnInfoData->nullbitmap, BitmapLen(finalNumOfRows));
        uint32_t extend = BitmapLen(finalNumOfRows) - BitmapLen(numOfRow1);
        memset(btmp + BitmapLen(numOfRow1), 0, extend);

        pColumnInfoData->nullbitmap = btmp;
      }

      *capacity = finalNumOfRows;
H
Haojun Liao 已提交
283 284
    }

285 286
    doBitmapMerge(pColumnInfoData, numOfRow1, pSource, numOfRow2);

X
Xiaoyu Wang 已提交
287 288 289 290
    if (pSource->pData) {
      int32_t offset = pColumnInfoData->info.bytes * numOfRow1;
      memcpy(pColumnInfoData->pData + offset, pSource->pData, pSource->info.bytes * numOfRow2);
    }
H
Haojun Liao 已提交
291 292 293 294 295
  }

  return numOfRow1 + numOfRow2;
}

L
Liu Jicong 已提交
296 297
int32_t colDataAssign(SColumnInfoData* pColumnInfoData, const SColumnInfoData* pSource, int32_t numOfRows,
                      const SDataBlockInfo* pBlockInfo) {
298
  ASSERT(pColumnInfoData != NULL && pSource != NULL && pColumnInfoData->info.type == pSource->info.type);
299
  if (numOfRows <= 0) {
300 301 302
    return numOfRows;
  }

303 304 305
  if (pBlockInfo != NULL) {
    ASSERT(pBlockInfo->capacity >= numOfRows);
  }
306

307 308
  if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
    memcpy(pColumnInfoData->varmeta.offset, pSource->varmeta.offset, sizeof(int32_t) * numOfRows);
309 310 311 312 313 314 315 316 317
    if (pColumnInfoData->varmeta.allocLen < pSource->varmeta.length) {
      char* tmp = taosMemoryRealloc(pColumnInfoData->pData, pSource->varmeta.length);
      if (tmp == NULL) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }

      pColumnInfoData->pData = tmp;
      pColumnInfoData->varmeta.allocLen = pSource->varmeta.length;
    }
318 319

    pColumnInfoData->varmeta.length = pSource->varmeta.length;
320
    memcpy(pColumnInfoData->pData, pSource->pData, pSource->varmeta.length);
321 322
  } else {
    memcpy(pColumnInfoData->nullbitmap, pSource->nullbitmap, BitmapLen(numOfRows));
D
dapan1121 已提交
323 324 325
    if (pSource->pData) {
      memcpy(pColumnInfoData->pData, pSource->pData, pSource->info.bytes * numOfRows);
    }
326 327
  }

328 329
  pColumnInfoData->hasNull = pSource->hasNull;
  pColumnInfoData->info = pSource->info;
330 331 332
  return 0;
}

L
Liu Jicong 已提交
333
size_t blockDataGetNumOfCols(const SSDataBlock* pBlock) { return taosArrayGetSize(pBlock->pDataBlock); }
334

L
Liu Jicong 已提交
335
size_t blockDataGetNumOfRows(const SSDataBlock* pBlock) { return pBlock->info.rows; }
336

337
int32_t blockDataUpdateTsWindow(SSDataBlock* pDataBlock, int32_t tsColumnIndex) {
338 339 340 341
  if (pDataBlock == NULL || pDataBlock->info.rows <= 0) {
    return 0;
  }

342 343
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  if (numOfCols <= 0) {
344 345 346
    return -1;
  }

347 348
  int32_t index = (tsColumnIndex == -1) ? 0 : tsColumnIndex;

349
  SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, index);
350 351 352 353
  if (pColInfoData->info.type != TSDB_DATA_TYPE_TIMESTAMP) {
    return 0;
  }

354 355 356 357 358 359
  TSKEY skey = *(TSKEY*)colDataGetData(pColInfoData, 0);
  TSKEY ekey = *(TSKEY*)colDataGetData(pColInfoData, (pDataBlock->info.rows - 1));

  pDataBlock->info.window.skey = TMIN(skey, ekey);
  pDataBlock->info.window.ekey = TMAX(skey, ekey);

360 361 362
  return 0;
}

363
int32_t blockDataMerge(SSDataBlock* pDest, const SSDataBlock* pSrc) {
wmmhello's avatar
wmmhello 已提交
364
  assert(pSrc != NULL && pDest != NULL);
365 366
  int32_t capacity = pDest->info.capacity;

367 368
  size_t numOfCols = taosArrayGetSize(pDest->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
369
    SColumnInfoData* pCol2 = taosArrayGet(pDest->pDataBlock, i);
370
    SColumnInfoData* pCol1 = taosArrayGet(pSrc->pDataBlock, i);
H
Haojun Liao 已提交
371

372 373
    capacity = pDest->info.capacity;
    colDataMergeCol(pCol2, pDest->info.rows, &capacity, pCol1, pSrc->info.rows);
H
Haojun Liao 已提交
374 375
  }

376
  pDest->info.capacity = capacity;
H
Haojun Liao 已提交
377 378 379 380 381 382 383
  pDest->info.rows += pSrc->info.rows;
  return TSDB_CODE_SUCCESS;
}

size_t blockDataGetSize(const SSDataBlock* pBlock) {
  assert(pBlock != NULL);

384 385
  size_t total = 0;
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
L
Liu Jicong 已提交
386
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
387
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
H
Haojun Liao 已提交
388
    total += colDataGetFullLength(pColInfoData, pBlock->info.rows);
H
Haojun Liao 已提交
389 390 391 392 393 394 395
  }

  return total;
}

// the number of tuples can be fit in one page.
// Actual data rows pluses the corresponding meta data must fit in one memory buffer of the given page size.
L
Liu Jicong 已提交
396 397
int32_t blockDataSplitRows(SSDataBlock* pBlock, bool hasVarCol, int32_t startIndex, int32_t* stopIndex,
                           int32_t pageSize) {
H
Haojun Liao 已提交
398 399
  ASSERT(pBlock != NULL && stopIndex != NULL);

L
Liu Jicong 已提交
400
  size_t  numOfCols = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
401 402
  int32_t numOfRows = pBlock->info.rows;

H
Haojun Liao 已提交
403 404
  int32_t bitmapChar = 1;

L
Liu Jicong 已提交
405
  size_t headerSize = sizeof(int32_t);
406
  size_t colHeaderSize = sizeof(int32_t) * numOfCols;
L
Liu Jicong 已提交
407
  size_t payloadSize = pageSize - (headerSize + colHeaderSize);
408

H
Haojun Liao 已提交
409
  // TODO speedup by checking if the whole page can fit in firstly.
H
Haojun Liao 已提交
410
  if (!hasVarCol) {
L
Liu Jicong 已提交
411
    size_t  rowSize = blockDataGetRowSize(pBlock);
412 413
    int32_t capacity = payloadSize / (rowSize + numOfCols * bitmapChar / 8.0);
    ASSERT(capacity > 0);
414

415
    *stopIndex = startIndex + capacity - 1;
H
Haojun Liao 已提交
416 417 418
    if (*stopIndex >= numOfRows) {
      *stopIndex = numOfRows - 1;
    }
419

H
Haojun Liao 已提交
420
    return TSDB_CODE_SUCCESS;
421
  }
wmmhello's avatar
wmmhello 已提交
422 423 424 425 426 427
  // iterate the rows that can be fit in this buffer page
  int32_t size = (headerSize + colHeaderSize);
  for (int32_t j = startIndex; j < numOfRows; ++j) {
    for (int32_t i = 0; i < numOfCols; ++i) {
      SColumnInfoData* pColInfoData = TARRAY_GET_ELEM(pBlock->pDataBlock, i);
      if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
428
        if (pColInfoData->varmeta.offset[j] != -1) {
wmmhello's avatar
wmmhello 已提交
429 430
          char* p = colDataGetData(pColInfoData, j);
          size += varDataTLen(p);
H
Haojun Liao 已提交
431 432
        }

wmmhello's avatar
wmmhello 已提交
433
        size += sizeof(pColInfoData->varmeta.offset[0]);
434
      } else {
wmmhello's avatar
wmmhello 已提交
435
        size += pColInfoData->info.bytes;
H
Haojun Liao 已提交
436

wmmhello's avatar
wmmhello 已提交
437 438 439
        if (((j - startIndex) & 0x07) == 0) {
          size += 1;  // the space for null bitmap
        }
H
Haojun Liao 已提交
440 441 442
      }
    }

wmmhello's avatar
wmmhello 已提交
443
    if (size > pageSize) {  // pageSize must be able to hold one row
wmmhello's avatar
wmmhello 已提交
444
      *stopIndex = j - 1;
wmmhello's avatar
wmmhello 已提交
445
      ASSERT(*stopIndex >= startIndex);
wmmhello's avatar
wmmhello 已提交
446 447 448

      return TSDB_CODE_SUCCESS;
    }
H
Haojun Liao 已提交
449
  }
wmmhello's avatar
wmmhello 已提交
450 451 452 453

  // all fit in
  *stopIndex = numOfRows - 1;
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
454 455
}

456 457 458 459 460
SSDataBlock* blockDataExtractBlock(SSDataBlock* pBlock, int32_t startIndex, int32_t rowCount) {
  if (pBlock == NULL || startIndex < 0 || rowCount > pBlock->info.rows || rowCount + startIndex > pBlock->info.rows) {
    return NULL;
  }

461
  SSDataBlock* pDst = createDataBlock();
462 463 464 465
  if (pDst == NULL) {
    return NULL;
  }

466
  pDst->info = pBlock->info;
467
  pDst->info.rows = 0;
468
  pDst->info.capacity = 0;
469 470
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
L
Liu Jicong 已提交
471
    SColumnInfoData  colInfo = {0};
472 473
    SColumnInfoData* pSrcCol = taosArrayGet(pBlock->pDataBlock, i);
    colInfo.info = pSrcCol->info;
474
    blockDataAppendColInfo(pDst, &colInfo);
475 476
  }

477 478 479
  blockDataEnsureCapacity(pDst, rowCount);

  for (int32_t i = 0; i < numOfCols; ++i) {
480 481 482 483
    SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, i);
    SColumnInfoData* pDstCol = taosArrayGet(pDst->pDataBlock, i);

    for (int32_t j = startIndex; j < (startIndex + rowCount); ++j) {
484 485
      bool isNull = false;
      if (pBlock->pBlockAgg == NULL) {
486
        isNull = colDataIsNull_s(pColData, j);
487 488 489
      } else {
        isNull = colDataIsNull(pColData, pBlock->info.rows, j, pBlock->pBlockAgg[i]);
      }
490

491
      char* p = colDataGetData(pColData, j);
492 493 494 495 496 497 498 499
      colDataAppend(pDstCol, j - startIndex, p, isNull);
    }
  }

  pDst->info.rows = rowCount;
  return pDst;
}

H
Haojun Liao 已提交
500 501
/**
 *
502 503 504 505 506
 * +------------------+---------------------------------------------+
 * |the number of rows|                    column #1                |
 * |    (4 bytes)     |------------+-----------------------+--------+
 * |                  | null bitmap| column length(4bytes) | values |
 * +------------------+------------+-----------------------+--------+
H
Haojun Liao 已提交
507 508 509 510
 * @param buf
 * @param pBlock
 * @return
 */
511
int32_t blockDataToBuf(char* buf, const SSDataBlock* pBlock) {
H
Haojun Liao 已提交
512 513 514
  ASSERT(pBlock != NULL);

  // write the number of rows
L
Liu Jicong 已提交
515
  *(uint32_t*)buf = pBlock->info.rows;
H
Haojun Liao 已提交
516

L
Liu Jicong 已提交
517
  size_t  numOfCols = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
518 519 520 521
  int32_t numOfRows = pBlock->info.rows;

  char* pStart = buf + sizeof(uint32_t);

L
Liu Jicong 已提交
522
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
523 524 525 526 527 528 529 530 531
    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, i);
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
      memcpy(pStart, pCol->varmeta.offset, numOfRows * sizeof(int32_t));
      pStart += numOfRows * sizeof(int32_t);
    } else {
      memcpy(pStart, pCol->nullbitmap, BitmapLen(numOfRows));
      pStart += BitmapLen(pBlock->info.rows);
    }

532
    uint32_t dataSize = colDataGetLength(pCol, numOfRows);
533

L
Liu Jicong 已提交
534
    *(int32_t*)pStart = dataSize;
535 536
    pStart += sizeof(int32_t);

H
Haojun Liao 已提交
537 538 539 540 541 542 543
    memcpy(pStart, pCol->pData, dataSize);
    pStart += dataSize;
  }

  return 0;
}

544
int32_t blockDataFromBuf(SSDataBlock* pBlock, const char* buf) {
545 546
  int32_t numOfRows = *(int32_t*) buf;
  blockDataEnsureCapacity(pBlock, numOfRows);
547

548
  pBlock->info.rows = numOfRows;
L
Liu Jicong 已提交
549
  size_t      numOfCols = taosArrayGetSize(pBlock->pDataBlock);
550 551
  const char* pStart = buf + sizeof(uint32_t);

L
Liu Jicong 已提交
552
  for (int32_t i = 0; i < numOfCols; ++i) {
553 554 555
    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, i);

    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
H
Haojun Liao 已提交
556
      size_t metaSize = pBlock->info.rows * sizeof(int32_t);
C
Cary Xu 已提交
557
      char*  tmp = taosMemoryRealloc(pCol->varmeta.offset, metaSize);  // preview calloc is too small
wmmhello's avatar
wmmhello 已提交
558 559 560 561
      if (tmp == NULL) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      pCol->varmeta.offset = (int32_t*)tmp;
562 563 564 565 566 567 568
      memcpy(pCol->varmeta.offset, pStart, metaSize);
      pStart += metaSize;
    } else {
      memcpy(pCol->nullbitmap, pStart, BitmapLen(pBlock->info.rows));
      pStart += BitmapLen(pBlock->info.rows);
    }

L
Liu Jicong 已提交
569
    int32_t colLength = *(int32_t*)pStart;
570 571
    pStart += sizeof(int32_t);

572 573
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
      if (pCol->varmeta.allocLen < colLength) {
wafwerar's avatar
wafwerar 已提交
574
        char* tmp = taosMemoryRealloc(pCol->pData, colLength);
575 576 577 578 579 580 581 582 583 584
        if (tmp == NULL) {
          return TSDB_CODE_OUT_OF_MEMORY;
        }

        pCol->pData = tmp;
        pCol->varmeta.allocLen = colLength;
      }

      pCol->varmeta.length = colLength;
      ASSERT(pCol->varmeta.length <= pCol->varmeta.allocLen);
585 586 587 588 589
    }

    memcpy(pCol->pData, pStart, colLength);
    pStart += colLength;
  }
590 591

  return TSDB_CODE_SUCCESS;
592 593
}

594
// todo remove this
H
Haojun Liao 已提交
595
int32_t blockDataFromBuf1(SSDataBlock* pBlock, const char* buf, size_t capacity) {
X
Xiaoyu Wang 已提交
596 597
  pBlock->info.rows = *(int32_t*)buf;
  pBlock->info.groupId = *(uint64_t*)(buf + sizeof(int32_t));
H
Haojun Liao 已提交
598

599 600
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);

601
  const char* pStart = buf + sizeof(uint32_t) + sizeof(uint64_t);
H
Haojun Liao 已提交
602 603 604

  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, i);
605
    pCol->hasNull = true;
H
Haojun Liao 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634

    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
      size_t metaSize = capacity * sizeof(int32_t);
      memcpy(pCol->varmeta.offset, pStart, metaSize);
      pStart += metaSize;
    } else {
      memcpy(pCol->nullbitmap, pStart, BitmapLen(capacity));
      pStart += BitmapLen(capacity);
    }

    int32_t colLength = *(int32_t*)pStart;
    pStart += sizeof(int32_t);

    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
      if (pCol->varmeta.allocLen < colLength) {
        char* tmp = taosMemoryRealloc(pCol->pData, colLength);
        if (tmp == NULL) {
          return TSDB_CODE_OUT_OF_MEMORY;
        }

        pCol->pData = tmp;
        pCol->varmeta.allocLen = colLength;
      }

      pCol->varmeta.length = colLength;
      ASSERT(pCol->varmeta.length <= pCol->varmeta.allocLen);
    }

    memcpy(pCol->pData, pStart, colLength);
635
    pStart += pCol->info.bytes * capacity;
H
Haojun Liao 已提交
636 637 638 639 640
  }

  return TSDB_CODE_SUCCESS;
}

641
size_t blockDataGetRowSize(SSDataBlock* pBlock) {
H
Haojun Liao 已提交
642
  ASSERT(pBlock != NULL);
643 644
  if (pBlock->info.rowSize == 0) {
    size_t rowSize = 0;
H
Haojun Liao 已提交
645

646
    size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
L
Liu Jicong 已提交
647 648 649 650
    for (int32_t i = 0; i < numOfCols; ++i) {
      SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, i);
      rowSize += pColInfo->info.bytes;
    }
651 652

    pBlock->info.rowSize = rowSize;
H
Haojun Liao 已提交
653 654
  }

655
  return pBlock->info.rowSize;
H
Haojun Liao 已提交
656 657
}

H
Haojun Liao 已提交
658 659 660 661 662
/**
 * @refitem blockDataToBuf for the meta size
 * @param pBlock
 * @return
 */
663 664
size_t blockDataGetSerialMetaSize(uint32_t numOfCols) {
  // | total rows/total length | block group id | column schema | each column length |
L
Liu Jicong 已提交
665 666
  return sizeof(int32_t) + sizeof(uint64_t) + numOfCols * (sizeof(int16_t) + sizeof(int32_t)) +
         numOfCols * sizeof(int32_t);
H
Haojun Liao 已提交
667 668
}

X
Xiaoyu Wang 已提交
669
double blockDataGetSerialRowSize(const SSDataBlock* pBlock) {
H
Haojun Liao 已提交
670 671 672
  ASSERT(pBlock != NULL);
  double rowSize = 0;

673
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
L
Liu Jicong 已提交
674
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
675 676 677 678 679 680
    SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, i);
    rowSize += pColInfo->info.bytes;

    if (IS_VAR_DATA_TYPE(pColInfo->info.type)) {
      rowSize += sizeof(int32_t);
    } else {
L
Liu Jicong 已提交
681
      rowSize += 1 / 8.0;  // one bit for each record
H
Haojun Liao 已提交
682 683 684 685 686 687
    }
  }

  return rowSize;
}

H
Haojun Liao 已提交
688
typedef struct SSDataBlockSortHelper {
L
Liu Jicong 已提交
689 690
  SArray*      orderInfo;  // SArray<SBlockOrderInfo>
  SSDataBlock* pDataBlock;
H
Haojun Liao 已提交
691 692 693
} SSDataBlockSortHelper;

int32_t dataBlockCompar(const void* p1, const void* p2, const void* param) {
L
Liu Jicong 已提交
694
  const SSDataBlockSortHelper* pHelper = (const SSDataBlockSortHelper*)param;
H
Haojun Liao 已提交
695 696 697

  SSDataBlock* pDataBlock = pHelper->pDataBlock;

L
Liu Jicong 已提交
698 699
  int32_t left = *(int32_t*)p1;
  int32_t right = *(int32_t*)p2;
H
Haojun Liao 已提交
700 701

  SArray* pInfo = pHelper->orderInfo;
702

L
Liu Jicong 已提交
703
  for (int32_t i = 0; i < pInfo->size; ++i) {
H
Haojun Liao 已提交
704
    SBlockOrderInfo* pOrder = TARRAY_GET_ELEM(pInfo, i);
L
Liu Jicong 已提交
705
    SColumnInfoData* pColInfoData = pOrder->pColData;  // TARRAY_GET_ELEM(pDataBlock->pDataBlock, pOrder->colIndex);
H
Haojun Liao 已提交
706

707
    if (pColInfoData->hasNull) {
708 709
      bool leftNull = colDataIsNull(pColInfoData, pDataBlock->info.rows, left, NULL);
      bool rightNull = colDataIsNull(pColInfoData, pDataBlock->info.rows, right, NULL);
710
      if (leftNull && rightNull) {
L
Liu Jicong 已提交
711
        continue;  // continue to next slot
712
      }
H
Haojun Liao 已提交
713

714
      if (rightNull) {
H
Haojun Liao 已提交
715
        return pOrder->nullFirst ? 1 : -1;
716
      }
H
Haojun Liao 已提交
717

718
      if (leftNull) {
H
Haojun Liao 已提交
719
        return pOrder->nullFirst ? -1 : 1;
720
      }
H
Haojun Liao 已提交
721 722
    }

L
Liu Jicong 已提交
723
    void* left1 = colDataGetData(pColInfoData, left);
724
    void* right1 = colDataGetData(pColInfoData, right);
wmmhello's avatar
wmmhello 已提交
725 726 727 728 729 730
    if (pColInfoData->info.type == TSDB_DATA_TYPE_JSON) {
      if (tTagIsJson(left1) || tTagIsJson(right1)) {
        terrno = TSDB_CODE_QRY_JSON_NOT_SUPPORT_ERROR;
        return 0;
      }
    }
731
    __compar_fn_t fn = getKeyComparFunc(pColInfoData->info.type, pOrder->order);
732

733 734 735 736 737
    int ret = fn(left1, right1);
    if (ret == 0) {
      continue;
    } else {
      return ret;
H
Haojun Liao 已提交
738 739 740 741 742 743
    }
  }

  return 0;
}

L
Liu Jicong 已提交
744 745
static int32_t doAssignOneTuple(SColumnInfoData* pDstCols, int32_t numOfRows, const SSDataBlock* pSrcBlock,
                                int32_t tupleIndex) {
H
Haojun Liao 已提交
746
  int32_t code = 0;
L
Liu Jicong 已提交
747
  size_t  numOfCols = taosArrayGetSize(pSrcBlock->pDataBlock);
H
Haojun Liao 已提交
748 749 750 751 752

  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* pDst = &pDstCols[i];
    SColumnInfoData* pSrc = taosArrayGet(pSrcBlock->pDataBlock, i);

753
    if (pSrc->hasNull && colDataIsNull(pSrc, pSrcBlock->info.rows, tupleIndex, pSrcBlock->pBlockAgg[i])) {
H
Haojun Liao 已提交
754 755 756 757
      code = colDataAppend(pDst, numOfRows, NULL, true);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
H
Haojun Liao 已提交
758
    } else {
759
      char* p = colDataGetData(pSrc, tupleIndex);
H
Haojun Liao 已提交
760 761 762 763
      code = colDataAppend(pDst, numOfRows, p, false);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
H
Haojun Liao 已提交
764 765
    }
  }
766 767

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
768 769
}

770
static int32_t blockDataAssign(SColumnInfoData* pCols, const SSDataBlock* pDataBlock, const int32_t* index) {
H
Haojun Liao 已提交
771
#if 0
H
Haojun Liao 已提交
772
  for (int32_t i = 0; i < pDataBlock->info.rows; ++i) {
H
Haojun Liao 已提交
773 774 775 776
    int32_t code = doAssignOneTuple(pCols, i, pDataBlock, index[i]);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
H
Haojun Liao 已提交
777
  }
H
Haojun Liao 已提交
778
#else
779 780
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
781 782 783 784
    SColumnInfoData* pDst = &pCols[i];
    SColumnInfoData* pSrc = taosArrayGet(pDataBlock->pDataBlock, i);

    if (IS_VAR_DATA_TYPE(pSrc->info.type)) {
L
Liu Jicong 已提交
785 786
      memcpy(pDst->pData, pSrc->pData, pSrc->varmeta.length);
      pDst->varmeta.length = pSrc->varmeta.length;
H
Haojun Liao 已提交
787

L
Liu Jicong 已提交
788 789 790
      for (int32_t j = 0; j < pDataBlock->info.rows; ++j) {
        pDst->varmeta.offset[j] = pSrc->varmeta.offset[index[j]];
      }
H
Haojun Liao 已提交
791
    } else {
wmmhello's avatar
wmmhello 已提交
792 793 794 795
      for (int32_t j = 0; j < pDataBlock->info.rows; ++j) {
        if (colDataIsNull_f(pSrc->nullbitmap, index[j])) {
          colDataSetNull_f(pDst->nullbitmap, j);
          continue;
H
Haojun Liao 已提交
796
        }
wmmhello's avatar
wmmhello 已提交
797
        memcpy(pDst->pData + j * pDst->info.bytes, pSrc->pData + index[j] * pDst->info.bytes, pDst->info.bytes);
H
Haojun Liao 已提交
798 799 800 801
      }
    }
  }
#endif
H
Haojun Liao 已提交
802
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
803 804 805 806
}

static SColumnInfoData* createHelpColInfoData(const SSDataBlock* pDataBlock) {
  int32_t rows = pDataBlock->info.rows;
L
Liu Jicong 已提交
807
  size_t  numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
H
Haojun Liao 已提交
808

wafwerar's avatar
wafwerar 已提交
809
  SColumnInfoData* pCols = taosMemoryCalloc(numOfCols, sizeof(SColumnInfoData));
H
Haojun Liao 已提交
810 811 812 813
  if (pCols == NULL) {
    return NULL;
  }

L
Liu Jicong 已提交
814
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
815 816 817 818
    SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, i);
    pCols[i].info = pColInfoData->info;

    if (IS_VAR_DATA_TYPE(pCols[i].info.type)) {
wafwerar's avatar
wafwerar 已提交
819 820
      pCols[i].varmeta.offset = taosMemoryCalloc(rows, sizeof(int32_t));
      pCols[i].pData = taosMemoryCalloc(1, pColInfoData->varmeta.length);
H
Haojun Liao 已提交
821 822 823

      pCols[i].varmeta.length = pColInfoData->varmeta.length;
      pCols[i].varmeta.allocLen = pCols[i].varmeta.length;
H
Haojun Liao 已提交
824
    } else {
wafwerar's avatar
wafwerar 已提交
825 826
      pCols[i].nullbitmap = taosMemoryCalloc(1, BitmapLen(rows));
      pCols[i].pData = taosMemoryCalloc(rows, pCols[i].info.bytes);
H
Haojun Liao 已提交
827 828 829 830 831 832
    }
  }

  return pCols;
}

H
Haojun Liao 已提交
833
static void copyBackToBlock(SSDataBlock* pDataBlock, SColumnInfoData* pCols) {
834
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
H
Haojun Liao 已提交
835

L
Liu Jicong 已提交
836
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
837 838 839 840
    SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, i);
    pColInfoData->info = pCols[i].info;

    if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
wafwerar's avatar
wafwerar 已提交
841
      taosMemoryFreeClear(pColInfoData->varmeta.offset);
H
Haojun Liao 已提交
842 843
      pColInfoData->varmeta = pCols[i].varmeta;
    } else {
wafwerar's avatar
wafwerar 已提交
844
      taosMemoryFreeClear(pColInfoData->nullbitmap);
H
Haojun Liao 已提交
845 846 847
      pColInfoData->nullbitmap = pCols[i].nullbitmap;
    }

wafwerar's avatar
wafwerar 已提交
848
    taosMemoryFreeClear(pColInfoData->pData);
H
Haojun Liao 已提交
849 850 851
    pColInfoData->pData = pCols[i].pData;
  }

wafwerar's avatar
wafwerar 已提交
852
  taosMemoryFreeClear(pCols);
H
Haojun Liao 已提交
853 854 855
}

static int32_t* createTupleIndex(size_t rows) {
wafwerar's avatar
wafwerar 已提交
856
  int32_t* index = taosMemoryCalloc(rows, sizeof(int32_t));
H
Haojun Liao 已提交
857 858 859 860
  if (index == NULL) {
    return NULL;
  }

L
Liu Jicong 已提交
861
  for (int32_t i = 0; i < rows; ++i) {
H
Haojun Liao 已提交
862 863 864 865 866 867
    index[i] = i;
  }

  return index;
}

wafwerar's avatar
wafwerar 已提交
868
static void destroyTupleIndex(int32_t* index) { taosMemoryFreeClear(index); }
H
Haojun Liao 已提交
869

H
Haojun Liao 已提交
870
int32_t blockDataSort(SSDataBlock* pDataBlock, SArray* pOrderInfo) {
H
Haojun Liao 已提交
871 872 873 874 875 876 877
  ASSERT(pDataBlock != NULL && pOrderInfo != NULL);
  if (pDataBlock->info.rows <= 1) {
    return TSDB_CODE_SUCCESS;
  }

  // Allocate the additional buffer.
  uint32_t rows = pDataBlock->info.rows;
H
Haojun Liao 已提交
878 879 880 881 882 883 884

  bool sortColumnHasNull = false;
  bool varTypeSort = false;

  for (int32_t i = 0; i < taosArrayGetSize(pOrderInfo); ++i) {
    SBlockOrderInfo* pInfo = taosArrayGet(pOrderInfo, i);

H
Haojun Liao 已提交
885
    SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, pInfo->slotId);
H
Haojun Liao 已提交
886 887 888 889 890 891 892 893 894
    if (pColInfoData->hasNull) {
      sortColumnHasNull = true;
    }

    if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
      varTypeSort = true;
    }
  }

895 896
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);

H
Haojun Liao 已提交
897
  if (taosArrayGetSize(pOrderInfo) == 1 && (!sortColumnHasNull)) {
898
    if (numOfCols == 1) {
H
Haojun Liao 已提交
899 900 901 902 903
      if (!varTypeSort) {
        SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, 0);
        SBlockOrderInfo* pOrder = taosArrayGet(pOrderInfo, 0);

        int64_t p0 = taosGetTimestampUs();
X
Xiaoyu Wang 已提交
904

905
        __compar_fn_t fn = getKeyComparFunc(pColInfoData->info.type, pOrder->order);
wafwerar's avatar
wafwerar 已提交
906
        taosSort(pColInfoData->pData, pDataBlock->info.rows, pColInfoData->info.bytes, fn);
H
Haojun Liao 已提交
907 908

        int64_t p1 = taosGetTimestampUs();
909
        uDebug("blockDataSort easy cost:%" PRId64 ", rows:%d\n", p1 - p0, pDataBlock->info.rows);
H
Haojun Liao 已提交
910 911 912 913

        return TSDB_CODE_SUCCESS;
      } else {  // var data type
      }
914
    } else if (numOfCols == 2) {
H
Haojun Liao 已提交
915 916 917
    }
  }

H
Haojun Liao 已提交
918 919 920 921 922 923
  int32_t* index = createTupleIndex(rows);
  if (index == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

924 925
  int64_t p0 = taosGetTimestampUs();

H
Haojun Liao 已提交
926
  SSDataBlockSortHelper helper = {.pDataBlock = pDataBlock, .orderInfo = pOrderInfo};
L
Liu Jicong 已提交
927
  for (int32_t i = 0; i < taosArrayGetSize(helper.orderInfo); ++i) {
H
Haojun Liao 已提交
928
    struct SBlockOrderInfo* pInfo = taosArrayGet(helper.orderInfo, i);
H
Haojun Liao 已提交
929
    pInfo->pColData = taosArrayGet(pDataBlock->pDataBlock, pInfo->slotId);
H
Haojun Liao 已提交
930 931
  }

X
Xiaoyu Wang 已提交
932
  terrno = 0;
H
Haojun Liao 已提交
933
  taosqsort(index, rows, sizeof(int32_t), &helper, dataBlockCompar);
X
Xiaoyu Wang 已提交
934
  if (terrno) return terrno;
H
Haojun Liao 已提交
935

936 937
  int64_t p1 = taosGetTimestampUs();

H
Haojun Liao 已提交
938 939
  SColumnInfoData* pCols = createHelpColInfoData(pDataBlock);
  if (pCols == NULL) {
940
    destroyTupleIndex(index);
H
Haojun Liao 已提交
941 942 943 944
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

945 946
  int64_t p2 = taosGetTimestampUs();

wmmhello's avatar
wmmhello 已提交
947
  blockDataAssign(pCols, pDataBlock, index);
H
Haojun Liao 已提交
948

949
  int64_t p3 = taosGetTimestampUs();
H
Haojun Liao 已提交
950 951

  copyBackToBlock(pDataBlock, pCols);
952 953
  int64_t p4 = taosGetTimestampUs();

C
Cary Xu 已提交
954 955 956
  uDebug("blockDataSort complex sort:%" PRId64 ", create:%" PRId64 ", assign:%" PRId64 ", copyback:%" PRId64
         ", rows:%d\n",
         p1 - p0, p2 - p1, p3 - p2, p4 - p3, rows);
H
Haojun Liao 已提交
957
  destroyTupleIndex(index);
H
Haojun Liao 已提交
958 959

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
960
}
961

H
Haojun Liao 已提交
962 963
typedef struct SHelper {
  int32_t index;
L
Liu Jicong 已提交
964 965 966 967 968
  union {
    char*   pData;
    int64_t i64;
    double  d64;
  };
H
Haojun Liao 已提交
969 970 971 972 973 974
} SHelper;

SHelper* createTupleIndex_rv(int32_t numOfRows, SArray* pOrderInfo, SSDataBlock* pBlock) {
  int32_t sortValLengthPerRow = 0;
  int32_t numOfCols = taosArrayGetSize(pOrderInfo);

L
Liu Jicong 已提交
975
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
976
    SBlockOrderInfo* pInfo = taosArrayGet(pOrderInfo, i);
H
Haojun Liao 已提交
977
    SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, pInfo->slotId);
H
Haojun Liao 已提交
978 979 980 981 982 983
    pInfo->pColData = pColInfo;
    sortValLengthPerRow += pColInfo->info.bytes;
  }

  size_t len = sortValLengthPerRow * pBlock->info.rows;

wafwerar's avatar
wafwerar 已提交
984 985
  char*    buf = taosMemoryCalloc(1, len);
  SHelper* phelper = taosMemoryCalloc(numOfRows, sizeof(SHelper));
L
Liu Jicong 已提交
986
  for (int32_t i = 0; i < numOfRows; ++i) {
H
Haojun Liao 已提交
987 988 989 990 991
    phelper[i].index = i;
    phelper[i].pData = buf + sortValLengthPerRow * i;
  }

  int32_t offset = 0;
L
Liu Jicong 已提交
992
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
993
    SBlockOrderInfo* pInfo = taosArrayGet(pOrderInfo, i);
L
Liu Jicong 已提交
994 995 996 997
    for (int32_t j = 0; j < numOfRows; ++j) {
      phelper[j].i64 = *(int32_t*)pInfo->pColData->pData + pInfo->pColData->info.bytes * j;
      //      memcpy(phelper[j].pData + offset, pInfo->pColData->pData + pInfo->pColData->info.bytes * j,
      //      pInfo->pColData->info.bytes);
H
Haojun Liao 已提交
998 999 1000 1001 1002 1003 1004 1005 1006
    }

    offset += pInfo->pColData->info.bytes;
  }

  return phelper;
}

int32_t dataBlockCompar_rv(const void* p1, const void* p2, const void* param) {
L
Liu Jicong 已提交
1007
  const SSDataBlockSortHelper* pHelper = (const SSDataBlockSortHelper*)param;
H
Haojun Liao 已提交
1008

L
Liu Jicong 已提交
1009
  //  SSDataBlock* pDataBlock = pHelper->pDataBlock;
H
Haojun Liao 已提交
1010

L
Liu Jicong 已提交
1011 1012
  SHelper* left = (SHelper*)p1;
  SHelper* right = (SHelper*)p2;
H
Haojun Liao 已提交
1013 1014 1015 1016

  SArray* pInfo = pHelper->orderInfo;

  int32_t offset = 0;
L
Liu Jicong 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
  //  for(int32_t i = 0; i < pInfo->size; ++i) {
  //    SBlockOrderInfo* pOrder = TARRAY_GET_ELEM(pInfo, 0);
  //    SColumnInfoData* pColInfoData = pOrder->pColData;//TARRAY_GET_ELEM(pDataBlock->pDataBlock, pOrder->colIndex);

  //    if (pColInfoData->hasNull) {
  //      bool leftNull  = colDataIsNull(pColInfoData, pDataBlock->info.rows, left, pDataBlock->pBlockAgg);
  //      bool rightNull = colDataIsNull(pColInfoData, pDataBlock->info.rows, right, pDataBlock->pBlockAgg);
  //      if (leftNull && rightNull) {
  //        continue; // continue to next slot
  //      }
  //
  //      if (rightNull) {
  //        return pHelper->nullFirst? 1:-1;
  //      }
  //
  //      if (leftNull) {
  //        return pHelper->nullFirst? -1:1;
  //      }
  //    }

  //    void* left1  = colDataGetData(pColInfoData, left);
  //    void* right1 = colDataGetData(pColInfoData, right);

  //    switch(pColInfoData->info.type) {
  //      case TSDB_DATA_TYPE_INT: {
  int32_t leftx = *(int32_t*)left->pData;    //*(int32_t*)(left->pData + offset);
  int32_t rightx = *(int32_t*)right->pData;  //*(int32_t*)(right->pData + offset);

  //        offset += pColInfoData->info.bytes;
  if (leftx == rightx) {
    //          break;
    return 0;
  } else {
    //          if (pOrder->order == TSDB_ORDER_ASC) {
    return (leftx < rightx) ? -1 : 1;
    //          } else {
    //            return (leftx < rightx)? 1:-1;
    //          }
  }
  //      }
  //      default:
  //        assert(0);
  //    }
  //  }
H
Haojun Liao 已提交
1061 1062 1063 1064

  return 0;
}

L
Liu Jicong 已提交
1065
int32_t varColSort(SColumnInfoData* pColumnInfoData, SBlockOrderInfo* pOrder) { return 0; }
H
Haojun Liao 已提交
1066 1067

int32_t blockDataSort_rv(SSDataBlock* pDataBlock, SArray* pOrderInfo, bool nullFirst) {
L
Liu Jicong 已提交
1068
  // Allocate the additional buffer.
H
Haojun Liao 已提交
1069 1070
  int64_t p0 = taosGetTimestampUs();

H
Haojun Liao 已提交
1071
  SSDataBlockSortHelper helper = {.pDataBlock = pDataBlock, .orderInfo = pOrderInfo};
H
Haojun Liao 已提交
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081

  uint32_t rows = pDataBlock->info.rows;
  SHelper* index = createTupleIndex_rv(rows, helper.orderInfo, pDataBlock);
  if (index == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

  taosqsort(index, rows, sizeof(SHelper), &helper, dataBlockCompar_rv);

L
Liu Jicong 已提交
1082
  int64_t          p1 = taosGetTimestampUs();
H
Haojun Liao 已提交
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
  SColumnInfoData* pCols = createHelpColInfoData(pDataBlock);
  if (pCols == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

  int64_t p2 = taosGetTimestampUs();

  //  int32_t code = blockDataAssign(pCols, pDataBlock, index);
  //  if (code != TSDB_CODE_SUCCESS) {
  //    terrno = code;
  //    return code;
  //  }

  int64_t p3 = taosGetTimestampUs();

  copyBackToBlock(pDataBlock, pCols);
  int64_t p4 = taosGetTimestampUs();

L
Liu Jicong 已提交
1102 1103
  printf("sort:%" PRId64 ", create:%" PRId64 ", assign:%" PRId64 ", copyback:%" PRId64 ", rows:%d\n", p1 - p0, p2 - p1,
         p3 - p2, p4 - p3, rows);
H
Haojun Liao 已提交
1104
  //  destroyTupleIndex(index);
1105
  return 0;
H
Haojun Liao 已提交
1106 1107
}

1108
void blockDataCleanup(SSDataBlock* pDataBlock) {
1109
  pDataBlock->info.rows = 0;
1110 1111
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
1112 1113
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
    colInfoDataCleanup(p, pDataBlock->info.capacity);
1114 1115 1116
  }
}

L
Liu Jicong 已提交
1117
static int32_t doEnsureCapacity(SColumnInfoData* pColumn, const SDataBlockInfo* pBlockInfo, uint32_t numOfRows) {
1118 1119
  ASSERT(numOfRows > 0 && pBlockInfo->capacity >= pBlockInfo->rows);
  if (numOfRows < pBlockInfo->capacity) {
X
Xiaoyu Wang 已提交
1120 1121 1122
    return TSDB_CODE_SUCCESS;
  }

H
Haojun Liao 已提交
1123
  // todo temp disable it
L
Liu Jicong 已提交
1124
  //  ASSERT(pColumn->info.bytes != 0);
H
Haojun Liao 已提交
1125

1126 1127
  int32_t existedRows = pBlockInfo->rows;

D
dapan1121 已提交
1128
  if (IS_VAR_DATA_TYPE(pColumn->info.type)) {
wafwerar's avatar
wafwerar 已提交
1129
    char* tmp = taosMemoryRealloc(pColumn->varmeta.offset, sizeof(int32_t) * numOfRows);
D
dapan1121 已提交
1130 1131 1132
    if (tmp == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
1133

D
dapan1121 已提交
1134
    pColumn->varmeta.offset = (int32_t*)tmp;
1135
    memset(&pColumn->varmeta.offset[existedRows], 0, sizeof(int32_t) * (numOfRows - existedRows));
D
dapan1121 已提交
1136
  } else {
wafwerar's avatar
wafwerar 已提交
1137
    char* tmp = taosMemoryRealloc(pColumn->nullbitmap, BitmapLen(numOfRows));
D
dapan1121 已提交
1138 1139 1140
    if (tmp == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
1141

1142
    int32_t oldLen = BitmapLen(existedRows);
D
dapan1121 已提交
1143
    pColumn->nullbitmap = tmp;
1144
    memset(&pColumn->nullbitmap[oldLen], 0, BitmapLen(numOfRows) - oldLen);
1145 1146 1147 1148 1149

    if (pColumn->info.type == TSDB_DATA_TYPE_NULL) {
      return TSDB_CODE_SUCCESS;
    }

X
Xiaoyu Wang 已提交
1150
    assert(pColumn->info.bytes);
wafwerar's avatar
wafwerar 已提交
1151
    tmp = taosMemoryRealloc(pColumn->pData, numOfRows * pColumn->info.bytes);
D
dapan1121 已提交
1152 1153 1154
    if (tmp == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
L
Liu Jicong 已提交
1155

1156
    memset(tmp + pColumn->info.bytes * existedRows, 0, pColumn->info.bytes * (numOfRows - existedRows));
D
dapan1121 已提交
1157 1158 1159 1160 1161 1162
    pColumn->pData = tmp;
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1163
void colInfoDataCleanup(SColumnInfoData* pColumn, uint32_t numOfRows) {
1164 1165 1166
  if (IS_VAR_DATA_TYPE(pColumn->info.type)) {
    pColumn->varmeta.length = 0;
  } else {
dengyihao's avatar
dengyihao 已提交
1167 1168 1169
    if (pColumn->nullbitmap != NULL) {
      memset(pColumn->nullbitmap, 0, BitmapLen(numOfRows));
    }
1170 1171 1172
  }
}

1173 1174 1175 1176 1177
int32_t colInfoDataEnsureCapacity(SColumnInfoData* pColumn, uint32_t numOfRows) {
  SDataBlockInfo info = {0};
  return doEnsureCapacity(pColumn, &info, numOfRows);
}

D
dapan1121 已提交
1178 1179
int32_t blockDataEnsureCapacity(SSDataBlock* pDataBlock, uint32_t numOfRows) {
  int32_t code = 0;
H
Haojun Liao 已提交
1180 1181 1182
  if (numOfRows == 0) {
    return TSDB_CODE_SUCCESS;
  }
L
Liu Jicong 已提交
1183

1184 1185 1186
  if (pDataBlock->info.capacity < numOfRows) {
    pDataBlock->info.capacity = numOfRows;
  }
1187

1188 1189
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
D
dapan1121 已提交
1190
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
1191
    code = doEnsureCapacity(p, &pDataBlock->info, numOfRows);
D
dapan1121 已提交
1192 1193
    if (code) {
      return code;
1194 1195
    }
  }
H
Haojun Liao 已提交
1196 1197 1198 1199

  return TSDB_CODE_SUCCESS;
}

1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
void blockDataFreeRes(SSDataBlock* pBlock) {
  int32_t numOfOutput = taosArrayGetSize(pBlock->pDataBlock);
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SColumnInfoData* pColInfoData = (SColumnInfoData*)taosArrayGet(pBlock->pDataBlock, i);
    colDataDestroy(pColInfoData);
  }

  taosArrayDestroy(pBlock->pDataBlock);
  taosMemoryFreeClear(pBlock->pBlockAgg);
  memset(&pBlock->info, 0, sizeof(SDataBlockInfo));
}

H
Haojun Liao 已提交
1212 1213 1214 1215 1216
void* blockDataDestroy(SSDataBlock* pBlock) {
  if (pBlock == NULL) {
    return NULL;
  }

1217
  blockDataFreeRes(pBlock);
wafwerar's avatar
wafwerar 已提交
1218
  taosMemoryFreeClear(pBlock);
H
Haojun Liao 已提交
1219
  return NULL;
D
dapan1121 已提交
1220
}
1221

L
Liu Jicong 已提交
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
int32_t assignOneDataBlock(SSDataBlock* dst, const SSDataBlock* src) {
  ASSERT(src != NULL);

  dst->info = src->info;
  dst->info.rows = 0;
  dst->info.capacity = 0;

  size_t numOfCols = taosArrayGetSize(src->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* p = taosArrayGet(src->pDataBlock, i);
    SColumnInfoData  colInfo = {.hasNull = true, .info = p->info};
    blockDataAppendColInfo(dst, &colInfo);
  }

  int32_t code = blockDataEnsureCapacity(dst, src->info.rows);
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    return -1;
  }

  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* pDst = taosArrayGet(dst->pDataBlock, i);
    SColumnInfoData* pSrc = taosArrayGet(src->pDataBlock, i);
D
dapan1121 已提交
1245
    if (pSrc->pData == NULL && (!IS_VAR_DATA_TYPE(pSrc->info.type))) {
L
Liu Jicong 已提交
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
      continue;
    }

    colDataAssign(pDst, pSrc, src->info.rows, &src->info);
  }

  dst->info.rows = src->info.rows;
  dst->info.capacity = src->info.rows;
  return 0;
}
1256

5
54liuyao 已提交
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
int32_t copyDataBlock(SSDataBlock* dst, const SSDataBlock* src) {
  ASSERT(src != NULL && dst != NULL);

  blockDataCleanup(dst);
  int32_t code = blockDataEnsureCapacity(dst, src->info.rows);
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    return code;
  }

  size_t numOfCols = taosArrayGetSize(src->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* pDst = taosArrayGet(dst->pDataBlock, i);
    SColumnInfoData* pSrc = taosArrayGet(src->pDataBlock, i);
    if (pSrc->pData == NULL) {
      continue;
    }

    colDataAssign(pDst, pSrc, src->info.rows, &src->info);
  }

  dst->info.rows = src->info.rows;
  dst->info.window = src->info.window;
1280
  dst->info.type = src->info.type;
5
54liuyao 已提交
1281 1282 1283
  return TSDB_CODE_SUCCESS;
}

1284
SSDataBlock* createOneDataBlock(const SSDataBlock* pDataBlock, bool copyData) {
C
Cary Xu 已提交
1285
  if (pDataBlock == NULL) {
1286 1287
    return NULL;
  }
1288

1289 1290 1291 1292
  SSDataBlock* pBlock = createDataBlock();
  pBlock->info = pDataBlock->info;
  pBlock->info.rows = 0;
  pBlock->info.capacity = 0;
1293

1294
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
L
Liu Jicong 已提交
1295
  for (int32_t i = 0; i < numOfCols; ++i) {
1296
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
1297 1298
    SColumnInfoData  colInfo = {.hasNull = true, .info = p->info};
    blockDataAppendColInfo(pBlock, &colInfo);
1299 1300
  }

1301
  if (copyData) {
1302 1303 1304 1305 1306 1307 1308
    int32_t code = blockDataEnsureCapacity(pBlock, pDataBlock->info.rows);
    if (code != TSDB_CODE_SUCCESS) {
      terrno = code;
      blockDataDestroy(pBlock);
      return NULL;
    }

1309 1310 1311
    for (int32_t i = 0; i < numOfCols; ++i) {
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, i);
      SColumnInfoData* pSrc = taosArrayGet(pDataBlock->pDataBlock, i);
1312
      if (pSrc->pData == NULL) {
1313 1314
        continue;
      }
1315 1316

      colDataAssign(pDst, pSrc, pDataBlock->info.rows, &pDataBlock->info);
1317 1318 1319 1320 1321 1322
    }

    pBlock->info.rows = pDataBlock->info.rows;
    pBlock->info.capacity = pDataBlock->info.rows;
  }

1323 1324 1325
  return pBlock;
}

1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
SSDataBlock* createDataBlock() {
  SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
  if (pBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
  }

  pBlock->pDataBlock = taosArrayInit(4, sizeof(SColumnInfoData));
  if (pBlock->pDataBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    taosMemoryFree(pBlock);
  }

  return pBlock;
}

int32_t blockDataAppendColInfo(SSDataBlock* pBlock, SColumnInfoData* pColInfoData) {
  ASSERT(pBlock != NULL && pColInfoData != NULL);
  if (pBlock->pDataBlock == NULL) {
    pBlock->pDataBlock = taosArrayInit(4, sizeof(SColumnInfoData));
    if (pBlock->pDataBlock == NULL) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      return terrno;
    }
  }

  void* p = taosArrayPush(pBlock->pDataBlock, pColInfoData);
  if (p == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

H
Haojun Liao 已提交
1357
  // todo disable it temporarily
L
Liu Jicong 已提交
1358
  //  ASSERT(pColInfoData->info.type != 0);
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
  if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
    pBlock->info.hasVarCol = true;
  }

  pBlock->info.rowSize += pColInfoData->info.bytes;
  return TSDB_CODE_SUCCESS;
}

SColumnInfoData createColumnInfoData(int16_t type, int32_t bytes, int16_t colId) {
  SColumnInfoData col = {.hasNull = true};
  col.info.colId = colId;
L
Liu Jicong 已提交
1370
  col.info.type = type;
1371 1372 1373 1374 1375
  col.info.bytes = bytes;

  return col;
}

L
Liu Jicong 已提交
1376
SColumnInfoData* bdGetColumnInfoData(const SSDataBlock* pBlock, int32_t index) {
1377 1378 1379 1380 1381 1382 1383 1384
  ASSERT(pBlock != NULL);
  if (index >= taosArrayGetSize(pBlock->pDataBlock)) {
    return NULL;
  }

  return taosArrayGet(pBlock->pDataBlock, index);
}

1385
size_t blockDataGetCapacityInRow(const SSDataBlock* pBlock, size_t pageSize) {
1386
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
1387

1388
  int32_t payloadSize = pageSize - blockDataGetSerialMetaSize(numOfCols);
1389 1390 1391 1392 1393
  int32_t rowSize = pBlock->info.rowSize;
  int32_t nRows = payloadSize / rowSize;

  // the true value must be less than the value of nRows
  int32_t additional = 0;
1394
  for (int32_t i = 0; i < numOfCols; ++i) {
1395 1396 1397 1398 1399 1400 1401 1402 1403
    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, i);
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
      additional += nRows * sizeof(int32_t);
    } else {
      additional += BitmapLen(nRows);
    }
  }

  int32_t newRows = (payloadSize - additional) / rowSize;
1404
  ASSERT(newRows <= nRows && newRows >= 1);
1405 1406

  return newRows;
1407
}
H
Haojun Liao 已提交
1408

1409 1410
void colDataDestroy(SColumnInfoData* pColData) {
  if (IS_VAR_DATA_TYPE(pColData->info.type)) {
wmmhello's avatar
wmmhello 已提交
1411
    taosMemoryFreeClear(pColData->varmeta.offset);
1412
  } else {
wmmhello's avatar
wmmhello 已提交
1413
    taosMemoryFreeClear(pColData->nullbitmap);
1414 1415
  }

wmmhello's avatar
wmmhello 已提交
1416
  taosMemoryFreeClear(pColData->pData);
1417 1418
}

H
Haojun Liao 已提交
1419 1420 1421 1422
static void doShiftBitmap(char* nullBitmap, size_t n, size_t total) {
  int32_t len = BitmapLen(total);

  int32_t newLen = BitmapLen(total - n);
C
Cary Xu 已提交
1423 1424
  if (n % 8 == 0) {
    memmove(nullBitmap, nullBitmap + n / 8, newLen);
H
Haojun Liao 已提交
1425
  } else {
1426
    int32_t  tail = n % 8;
1427
    int32_t  i = 0;
C
Cary Xu 已提交
1428
    uint8_t* p = (uint8_t*)nullBitmap;
H
Haojun Liao 已提交
1429

1430 1431 1432 1433 1434 1435 1436 1437 1438
    if (n < 8) {
      while (i < len) {
        uint8_t v = p[i];  // source bitmap value
        p[i] = (v << tail);

        if (i < len - 1) {
          uint8_t next = p[i + 1];
          p[i] |= (next >> (8 - tail));
        }
H
Haojun Liao 已提交
1439

1440
        i += 1;
H
Haojun Liao 已提交
1441
      }
1442 1443
    } else if (n > 8) {
      int32_t gap = len - newLen;
1444
      while (i < newLen) {
1445 1446 1447 1448 1449 1450 1451
        uint8_t v = p[i + gap];
        p[i] = (v << tail);

        if (i < newLen - 1) {
          uint8_t next = p[i + gap + 1];
          p[i] |= (next >> (8 - tail));
        }
H
Haojun Liao 已提交
1452

1453 1454
        i += 1;
      }
H
Haojun Liao 已提交
1455 1456 1457 1458
    }
  }
}

X
Xiaoyu Wang 已提交
1459
static int32_t colDataMoveVarData(SColumnInfoData* pColInfoData, size_t start, size_t end) {
wmmhello's avatar
wmmhello 已提交
1460 1461 1462
  int32_t dataOffset = -1;
  int32_t dataLen = 0;
  int32_t beigin = start;
X
Xiaoyu Wang 已提交
1463
  while (beigin < end) {
wmmhello's avatar
wmmhello 已提交
1464
    int32_t offset = pColInfoData->varmeta.offset[beigin];
X
Xiaoyu Wang 已提交
1465
    if (offset == -1) {
wmmhello's avatar
wmmhello 已提交
1466 1467 1468
      beigin++;
      continue;
    }
X
Xiaoyu Wang 已提交
1469
    if (start != 0) {
wmmhello's avatar
wmmhello 已提交
1470 1471
      pColInfoData->varmeta.offset[beigin] = dataLen;
    }
X
Xiaoyu Wang 已提交
1472 1473
    char* data = pColInfoData->pData + offset;
    if (dataOffset == -1) dataOffset = offset;  // mark the begin of data
wmmhello's avatar
wmmhello 已提交
1474 1475 1476 1477 1478 1479 1480 1481
    int32_t type = pColInfoData->info.type;
    if (type == TSDB_DATA_TYPE_JSON) {
      dataLen += getJsonValueLen(data);
    } else {
      dataLen += varDataTLen(data);
    }
    beigin++;
  }
X
Xiaoyu Wang 已提交
1482
  if (dataOffset > 0) {
wmmhello's avatar
wmmhello 已提交
1483 1484 1485 1486 1487 1488
    memmove(pColInfoData->pData, pColInfoData->pData + dataOffset, dataLen);
    memmove(pColInfoData->varmeta.offset, &pColInfoData->varmeta.offset[start], (end - start) * sizeof(int32_t));
  }
  return dataLen;
}

H
Haojun Liao 已提交
1489 1490
static void colDataTrimFirstNRows(SColumnInfoData* pColInfoData, size_t n, size_t total) {
  if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
wmmhello's avatar
wmmhello 已提交
1491
    pColInfoData->varmeta.length = colDataMoveVarData(pColInfoData, n, total);
1492
    memset(&pColInfoData->varmeta.offset[total - n], 0, n);
H
Haojun Liao 已提交
1493 1494 1495 1496 1497 1498 1499
  } else {
    int32_t bytes = pColInfoData->info.bytes;
    memmove(pColInfoData->pData, ((char*)pColInfoData->pData + n * bytes), (total - n) * bytes);
    doShiftBitmap(pColInfoData->nullbitmap, n, total);
  }
}

C
Cary Xu 已提交
1500
int32_t blockDataTrimFirstNRows(SSDataBlock* pBlock, size_t n) {
H
Haojun Liao 已提交
1501 1502 1503 1504 1505 1506 1507
  if (n == 0) {
    return TSDB_CODE_SUCCESS;
  }

  if (pBlock->info.rows <= n) {
    blockDataCleanup(pBlock);
  } else {
1508 1509
    size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
1510 1511 1512 1513 1514 1515 1516 1517 1518
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
      colDataTrimFirstNRows(pColInfoData, n, pBlock->info.rows);
    }

    pBlock->info.rows -= n;
  }
  return TSDB_CODE_SUCCESS;
}

wmmhello's avatar
wmmhello 已提交
1519 1520
static void colDataKeepFirstNRows(SColumnInfoData* pColInfoData, size_t n, size_t total) {
  if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
wmmhello's avatar
wmmhello 已提交
1521
    pColInfoData->varmeta.length = colDataMoveVarData(pColInfoData, 0, n);
wmmhello's avatar
wmmhello 已提交
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
    memset(&pColInfoData->varmeta.offset[n], 0, total - n);
  }
}

int32_t blockDataKeepFirstNRows(SSDataBlock* pBlock, size_t n) {
  if (n == 0) {
    blockDataCleanup(pBlock);
    return TSDB_CODE_SUCCESS;
  }

  if (pBlock->info.rows <= n) {
    return TSDB_CODE_SUCCESS;
  } else {
    size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
    for (int32_t i = 0; i < numOfCols; ++i) {
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
      colDataKeepFirstNRows(pColInfoData, n, pBlock->info.rows);
    }

    pBlock->info.rows = n;
  }
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1546 1547
int32_t tEncodeDataBlock(void** buf, const SSDataBlock* pBlock) {
  int64_t tbUid = pBlock->info.uid;
1548
  int16_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
  int16_t hasVarCol = pBlock->info.hasVarCol;
  int32_t rows = pBlock->info.rows;
  int32_t sz = taosArrayGetSize(pBlock->pDataBlock);

  int32_t tlen = 0;
  tlen += taosEncodeFixedI64(buf, tbUid);
  tlen += taosEncodeFixedI16(buf, numOfCols);
  tlen += taosEncodeFixedI16(buf, hasVarCol);
  tlen += taosEncodeFixedI32(buf, rows);
  tlen += taosEncodeFixedI32(buf, sz);
  for (int32_t i = 0; i < sz; i++) {
    SColumnInfoData* pColData = (SColumnInfoData*)taosArrayGet(pBlock->pDataBlock, i);
    tlen += taosEncodeFixedI16(buf, pColData->info.colId);
    tlen += taosEncodeFixedI16(buf, pColData->info.type);
    tlen += taosEncodeFixedI32(buf, pColData->info.bytes);
S
slzhou@taodata.com 已提交
1564
    tlen += taosEncodeFixedBool(buf, pColData->hasNull);
H
Haojun Liao 已提交
1565 1566 1567 1568 1569 1570 1571 1572

    if (IS_VAR_DATA_TYPE(pColData->info.type)) {
      tlen += taosEncodeBinary(buf, pColData->varmeta.offset, sizeof(int32_t) * rows);
    } else {
      tlen += taosEncodeBinary(buf, pColData->nullbitmap, BitmapLen(rows));
    }

    int32_t len = colDataGetLength(pColData, rows);
X
Xiaoyu Wang 已提交
1573
    tlen += taosEncodeFixedI32(buf, len);
H
Haojun Liao 已提交
1574 1575 1576 1577 1578 1579 1580 1581 1582

    tlen += taosEncodeBinary(buf, pColData->pData, len);
  }
  return tlen;
}

void* tDecodeDataBlock(const void* buf, SSDataBlock* pBlock) {
  int32_t sz;

1583 1584 1585 1586
  int16_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);

  buf = taosDecodeFixedU64(buf, &pBlock->info.uid);
  buf = taosDecodeFixedI16(buf, &numOfCols);
H
Haojun Liao 已提交
1587 1588 1589 1590 1591 1592 1593 1594 1595
  buf = taosDecodeFixedI16(buf, &pBlock->info.hasVarCol);
  buf = taosDecodeFixedI32(buf, &pBlock->info.rows);
  buf = taosDecodeFixedI32(buf, &sz);
  pBlock->pDataBlock = taosArrayInit(sz, sizeof(SColumnInfoData));
  for (int32_t i = 0; i < sz; i++) {
    SColumnInfoData data = {0};
    buf = taosDecodeFixedI16(buf, &data.info.colId);
    buf = taosDecodeFixedI16(buf, &data.info.type);
    buf = taosDecodeFixedI32(buf, &data.info.bytes);
S
slzhou@taodata.com 已提交
1596
    buf = taosDecodeFixedBool(buf, &data.hasNull);
H
Haojun Liao 已提交
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611

    if (IS_VAR_DATA_TYPE(data.info.type)) {
      buf = taosDecodeBinary(buf, (void**)&data.varmeta.offset, pBlock->info.rows * sizeof(int32_t));
      data.varmeta.length = pBlock->info.rows * sizeof(int32_t);
      data.varmeta.allocLen = data.varmeta.length;
    } else {
      buf = taosDecodeBinary(buf, (void**)&data.nullbitmap, BitmapLen(pBlock->info.rows));
    }

    int32_t len = 0;
    buf = taosDecodeFixedI32(buf, &len);
    buf = taosDecodeBinary(buf, (void**)&data.pData, len);
    taosArrayPush(pBlock->pDataBlock, &data);
  }
  return (void*)buf;
L
Liu Jicong 已提交
1612
}
L
Liu Jicong 已提交
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626

int32_t tEncodeDataBlocks(void** buf, const SArray* blocks) {
  int32_t tlen = 0;
  int32_t sz = taosArrayGetSize(blocks);
  tlen += taosEncodeFixedI32(buf, sz);

  for (int32_t i = 0; i < sz; i++) {
    SSDataBlock* pBlock = taosArrayGet(blocks, i);
    tlen += tEncodeDataBlock(buf, pBlock);
  }

  return tlen;
}

L
Liu Jicong 已提交
1627
void* tDecodeDataBlocks(const void* buf, SArray** blocks) {
L
Liu Jicong 已提交
1628 1629
  int32_t sz;
  buf = taosDecodeFixedI32(buf, &sz);
L
Liu Jicong 已提交
1630 1631

  *blocks = taosArrayInit(sz, sizeof(SSDataBlock));
L
Liu Jicong 已提交
1632 1633 1634
  for (int32_t i = 0; i < sz; i++) {
    SSDataBlock pBlock = {0};
    buf = tDecodeDataBlock(buf, &pBlock);
L
Liu Jicong 已提交
1635
    taosArrayPush(*blocks, &pBlock);
L
Liu Jicong 已提交
1636 1637 1638
  }
  return (void*)buf;
}
L
Liu Jicong 已提交
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675

static char* formatTimestamp(char* buf, int64_t val, int precision) {
  time_t  tt;
  int32_t ms = 0;
  if (precision == TSDB_TIME_PRECISION_NANO) {
    tt = (time_t)(val / 1000000000);
    ms = val % 1000000000;
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
    tt = (time_t)(val / 1000000);
    ms = val % 1000000;
  } else {
    tt = (time_t)(val / 1000);
    ms = val % 1000;
  }

  /* comment out as it make testcases like select_with_tags.sim fail.
    but in windows, this may cause the call to localtime crash if tt < 0,
    need to find a better solution.
    if (tt < 0) {
      tt = 0;
    }
    */

#ifdef WINDOWS
  if (tt < 0) tt = 0;
#endif
  if (tt <= 0 && ms < 0) {
    tt--;
    if (precision == TSDB_TIME_PRECISION_NANO) {
      ms += 1000000000;
    } else if (precision == TSDB_TIME_PRECISION_MICRO) {
      ms += 1000000;
    } else {
      ms += 1000;
    }
  }

1676
  struct tm* ptm = taosLocalTime(&tt, NULL);
L
Liu Jicong 已提交
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
  size_t     pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", ptm);

  if (precision == TSDB_TIME_PRECISION_NANO) {
    sprintf(buf + pos, ".%09d", ms);
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
    sprintf(buf + pos, ".%06d", ms);
  } else {
    sprintf(buf + pos, ".%03d", ms);
  }

  return buf;
}
H
Haojun Liao 已提交
1689

1690 1691 1692 1693 1694 1695 1696
void blockDebugShowDataBlock(SSDataBlock* pBlock, const char* flag) {
  SArray* dataBlocks = taosArrayInit(1, sizeof(SSDataBlock));
  taosArrayPush(dataBlocks, pBlock);
  blockDebugShowDataBlocks(dataBlocks, flag);
  taosArrayDestroy(dataBlocks);
}

S
slzhou 已提交
1697
void blockDebugShowDataBlocks(const SArray* dataBlocks, const char* flag) {
C
Cary Xu 已提交
1698
  char    pBuf[128] = {0};
L
Liu Jicong 已提交
1699 1700 1701
  int32_t sz = taosArrayGetSize(dataBlocks);
  for (int32_t i = 0; i < sz; i++) {
    SSDataBlock* pDataBlock = taosArrayGet(dataBlocks, i);
L
Liu Jicong 已提交
1702
    size_t       numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
1703

L
Liu Jicong 已提交
1704
    int32_t rows = pDataBlock->info.rows;
1705 1706
    printf("%s |block type %d |child id %d|group id %zX\n", flag, (int32_t)pDataBlock->info.type,
           pDataBlock->info.childId, pDataBlock->info.groupId);
L
Liu Jicong 已提交
1707
    for (int32_t j = 0; j < rows; j++) {
C
Cary Xu 已提交
1708
      printf("%s |", flag);
1709
      for (int32_t k = 0; k < numOfCols; k++) {
L
Liu Jicong 已提交
1710 1711
        SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, k);
        void*            var = POINTER_SHIFT(pColInfoData->pData, j * pColInfoData->info.bytes);
5
54liuyao 已提交
1712
        if (colDataIsNull(pColInfoData, rows, j, NULL)) {
5
54liuyao 已提交
1713 1714 1715
          printf(" %15s |", "NULL");
          continue;
        }
L
Liu Jicong 已提交
1716 1717 1718 1719 1720 1721 1722 1723
        switch (pColInfoData->info.type) {
          case TSDB_DATA_TYPE_TIMESTAMP:
            formatTimestamp(pBuf, *(uint64_t*)var, TSDB_TIME_PRECISION_MILLI);
            printf(" %25s |", pBuf);
            break;
          case TSDB_DATA_TYPE_INT:
            printf(" %15d |", *(int32_t*)var);
            break;
L
Liu Jicong 已提交
1724 1725 1726
          case TSDB_DATA_TYPE_UINT:
            printf(" %15u |", *(uint32_t*)var);
            break;
L
Liu Jicong 已提交
1727 1728 1729
          case TSDB_DATA_TYPE_BIGINT:
            printf(" %15ld |", *(int64_t*)var);
            break;
L
Liu Jicong 已提交
1730 1731 1732
          case TSDB_DATA_TYPE_UBIGINT:
            printf(" %15lu |", *(uint64_t*)var);
            break;
C
Cary Xu 已提交
1733 1734 1735
          case TSDB_DATA_TYPE_FLOAT:
            printf(" %15f |", *(float*)var);
            break;
5
54liuyao 已提交
1736
          case TSDB_DATA_TYPE_DOUBLE:
C
Cary Xu 已提交
1737
            printf(" %15lf |", *(double*)var);
5
54liuyao 已提交
1738
            break;
L
Liu Jicong 已提交
1739 1740 1741 1742 1743
        }
      }
      printf("\n");
    }
  }
5
54liuyao 已提交
1744 1745 1746 1747 1748 1749
}

// for debug
char* dumpBlockData(SSDataBlock* pDataBlock, const char* flag, char** pDataBuf) {
  int32_t size = 2048;
  *pDataBuf = taosMemoryCalloc(size, 1);
1750 1751
  char*   dumpBuf = *pDataBuf;
  char    pBuf[128] = {0};
5
54liuyao 已提交
1752 1753 1754
  int32_t colNum = taosArrayGetSize(pDataBlock->pDataBlock);
  int32_t rows = pDataBlock->info.rows;
  int32_t len = 0;
L
Liu Jicong 已提交
1755 1756 1757
  len += snprintf(dumpBuf + len, size - len, "\n%s |block type %d |child id %d|group id:%" PRIu64 "| uid:%ld\n", flag,
                  (int32_t)pDataBlock->info.type, pDataBlock->info.childId, pDataBlock->info.groupId,
                  pDataBlock->info.uid);
S
Shengliang Guan 已提交
1758
  if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1759

5
54liuyao 已提交
1760 1761
  for (int32_t j = 0; j < rows; j++) {
    len += snprintf(dumpBuf + len, size - len, "%s |", flag);
L
Liu Jicong 已提交
1762
    if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1763

5
54liuyao 已提交
1764 1765 1766
    for (int32_t k = 0; k < colNum; k++) {
      SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, k);
      void*            var = POINTER_SHIFT(pColInfoData->pData, j * pColInfoData->info.bytes);
5
54liuyao 已提交
1767
      if (colDataIsNull(pColInfoData, rows, j, NULL) || !pColInfoData->pData) {
5
54liuyao 已提交
1768
        len += snprintf(dumpBuf + len, size - len, " %15s |", "NULL");
L
Liu Jicong 已提交
1769
        if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1770 1771 1772 1773 1774 1775
        continue;
      }
      switch (pColInfoData->info.type) {
        case TSDB_DATA_TYPE_TIMESTAMP:
          formatTimestamp(pBuf, *(uint64_t*)var, TSDB_TIME_PRECISION_MILLI);
          len += snprintf(dumpBuf + len, size - len, " %25s |", pBuf);
L
Liu Jicong 已提交
1776
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1777 1778 1779
          break;
        case TSDB_DATA_TYPE_INT:
          len += snprintf(dumpBuf + len, size - len, " %15d |", *(int32_t*)var);
L
Liu Jicong 已提交
1780
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1781 1782 1783
          break;
        case TSDB_DATA_TYPE_UINT:
          len += snprintf(dumpBuf + len, size - len, " %15u |", *(uint32_t*)var);
L
Liu Jicong 已提交
1784
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1785 1786 1787
          break;
        case TSDB_DATA_TYPE_BIGINT:
          len += snprintf(dumpBuf + len, size - len, " %15ld |", *(int64_t*)var);
L
Liu Jicong 已提交
1788
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1789 1790 1791
          break;
        case TSDB_DATA_TYPE_UBIGINT:
          len += snprintf(dumpBuf + len, size - len, " %15lu |", *(uint64_t*)var);
L
Liu Jicong 已提交
1792
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1793 1794 1795
          break;
        case TSDB_DATA_TYPE_FLOAT:
          len += snprintf(dumpBuf + len, size - len, " %15f |", *(float*)var);
L
Liu Jicong 已提交
1796
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1797 1798 1799
          break;
        case TSDB_DATA_TYPE_DOUBLE:
          len += snprintf(dumpBuf + len, size - len, " %15lf |", *(double*)var);
L
Liu Jicong 已提交
1800
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1801 1802 1803 1804
          break;
      }
    }
    len += snprintf(dumpBuf + len, size - len, "\n");
L
Liu Jicong 已提交
1805
    if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1806 1807 1808
  }
  len += snprintf(dumpBuf + len, size - len, "%s |end\n", flag);
  return dumpBuf;
L
Liu Jicong 已提交
1809 1810
}

C
Cary Xu 已提交
1811 1812 1813 1814 1815 1816 1817
/**
 * @brief TODO: Assume that the final generated result it less than 3M
 *
 * @param pReq
 * @param pDataBlocks
 * @param vgId
 * @param suid  // TODO: check with Liao whether suid response is reasonable
1818
 *
C
Cary Xu 已提交
1819 1820
 * TODO: colId should be set
 */
1821 1822
int32_t buildSubmitReqFromDataBlock(SSubmitReq** pReq, const SArray* pDataBlocks, STSchema* pTSchema, int32_t vgId,
                                    tb_uid_t suid) {
C
Cary Xu 已提交
1823 1824 1825 1826
  int32_t sz = taosArrayGetSize(pDataBlocks);
  int32_t bufSize = sizeof(SSubmitReq);
  for (int32_t i = 0; i < sz; ++i) {
    SDataBlockInfo* pBlkInfo = &((SSDataBlock*)taosArrayGet(pDataBlocks, i))->info;
1827 1828 1829

    int32_t numOfCols = taosArrayGetSize(pDataBlocks);
    bufSize += pBlkInfo->rows * (TD_ROW_HEAD_LEN + pBlkInfo->rowSize + BitmapLen(numOfCols));
C
Cary Xu 已提交
1830 1831 1832 1833
    bufSize += sizeof(SSubmitBlk);
  }

  *pReq = taosMemoryCalloc(1, bufSize);
1834
  if (!(*pReq)) {
C
Cary Xu 已提交
1835 1836 1837
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return TSDB_CODE_FAILED;
  }
C
Cary Xu 已提交
1838 1839
  void* pDataBuf = *pReq;

1840
  int32_t     msgLen = sizeof(SSubmitReq);
C
Cary Xu 已提交
1841 1842
  int32_t     numOfBlks = 0;
  SRowBuilder rb = {0};
C
Cary Xu 已提交
1843
  tdSRowInit(&rb, pTSchema->version);
C
Cary Xu 已提交
1844 1845 1846

  for (int32_t i = 0; i < sz; ++i) {
    SSDataBlock* pDataBlock = taosArrayGet(pDataBlocks, i);
1847
    int32_t      colNum = taosArrayGetSize(pDataBlock->pDataBlock);
C
Cary Xu 已提交
1848
    int32_t      rows = pDataBlock->info.rows;
L
Liu Jicong 已提交
1849 1850
    //    int32_t      rowSize = pDataBlock->info.rowSize;
    //    int64_t      groupId = pDataBlock->info.groupId;
1851

1852 1853 1854 1855 1856
    if (colNum <= 1) {
      // invalid if only with TS col
      continue;
    }

1857
    if (rb.nCols != colNum) {
C
Cary Xu 已提交
1858 1859 1860 1861 1862
      tdSRowSetTpInfo(&rb, colNum, pTSchema->flen);
    }

    SSubmitBlk* pSubmitBlk = POINTER_SHIFT(pDataBuf, msgLen);
    pSubmitBlk->suid = suid;
1863
    pSubmitBlk->uid = pDataBlock->info.groupId;
C
Cary Xu 已提交
1864
    pSubmitBlk->numOfRows = rows;
C
Cary Xu 已提交
1865
    pSubmitBlk->sversion = pTSchema->version;
C
Cary Xu 已提交
1866 1867 1868

    msgLen += sizeof(SSubmitBlk);
    int32_t dataLen = 0;
1869 1870
    for (int32_t j = 0; j < rows; ++j) {                     // iterate by row
      tdSRowResetBuf(&rb, POINTER_SHIFT(pDataBuf, msgLen));  // set row buf
1871
      bool    isStartKey = false;
1872
      int32_t offset = 0;
C
Cary Xu 已提交
1873 1874
      for (int32_t k = 0; k < colNum; ++k) {  // iterate by column
        SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, k);
1875 1876
        STColumn*        pCol = &pTSchema->columns[k];
        void*            var = POINTER_SHIFT(pColInfoData->pData, j * pColInfoData->info.bytes);
C
Cary Xu 已提交
1877 1878 1879 1880
        switch (pColInfoData->info.type) {
          case TSDB_DATA_TYPE_TIMESTAMP:
            if (!isStartKey) {
              isStartKey = true;
1881
              tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID, TSDB_DATA_TYPE_TIMESTAMP, TD_VTYPE_NORM, var, true,
1882 1883
                                  offset, k);

C
Cary Xu 已提交
1884
            } else {
1885 1886
              tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, TSDB_DATA_TYPE_TIMESTAMP, TD_VTYPE_NORM, var,
                                  true, offset, k);
C
Cary Xu 已提交
1887 1888 1889
            }
            break;
          case TSDB_DATA_TYPE_NCHAR: {
1890 1891
            tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, TSDB_DATA_TYPE_NCHAR, TD_VTYPE_NORM, var, true,
                                offset, k);
C
Cary Xu 已提交
1892 1893 1894
            break;
          }
          case TSDB_DATA_TYPE_VARCHAR: {  // TSDB_DATA_TYPE_BINARY
1895 1896
            tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, TSDB_DATA_TYPE_VARCHAR, TD_VTYPE_NORM, var, true,
                                offset, k);
C
Cary Xu 已提交
1897 1898 1899 1900 1901
            break;
          }
          case TSDB_DATA_TYPE_VARBINARY:
          case TSDB_DATA_TYPE_DECIMAL:
          case TSDB_DATA_TYPE_BLOB:
1902
          case TSDB_DATA_TYPE_JSON:
C
Cary Xu 已提交
1903
          case TSDB_DATA_TYPE_MEDIUMBLOB:
C
Cary Xu 已提交
1904
            uError("the column type %" PRIi16 " is defined but not implemented yet", pColInfoData->info.type);
C
Cary Xu 已提交
1905 1906 1907 1908
            TASSERT(0);
            break;
          default:
            if (pColInfoData->info.type < TSDB_DATA_TYPE_MAX && pColInfoData->info.type > TSDB_DATA_TYPE_NULL) {
C
Cary Xu 已提交
1909 1910 1911
              if (pCol->type == pColInfoData->info.type) {
                tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, pCol->type, TD_VTYPE_NORM, var, true, offset,
                                    k);
1912
              } else {
C
Cary Xu 已提交
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
                char tv[8] = {0};
                if (pColInfoData->info.type == TSDB_DATA_TYPE_FLOAT) {
                  float v = 0;
                  GET_TYPED_DATA(v, float, pColInfoData->info.type, var);
                  SET_TYPED_DATA(&tv, pCol->type, v);
                } else if (pColInfoData->info.type == TSDB_DATA_TYPE_DOUBLE) {
                  double v = 0;
                  GET_TYPED_DATA(v, double, pColInfoData->info.type, var);
                  SET_TYPED_DATA(&tv, pCol->type, v);
                } else if (IS_SIGNED_NUMERIC_TYPE(pColInfoData->info.type)) {
                  int64_t v = 0;
                  GET_TYPED_DATA(v, int64_t, pColInfoData->info.type, var);
                  SET_TYPED_DATA(&tv, pCol->type, v);
                } else {
                  uint64_t v = 0;
                  GET_TYPED_DATA(v, uint64_t, pColInfoData->info.type, var);
                  SET_TYPED_DATA(&tv, pCol->type, v);
                }
                tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, pCol->type, TD_VTYPE_NORM, tv, true, offset,
                                    k);
1933
              }
C
Cary Xu 已提交
1934
            } else {
C
Cary Xu 已提交
1935
              uError("the column type %" PRIi16 " is undefined\n", pColInfoData->info.type);
C
Cary Xu 已提交
1936 1937 1938 1939
              TASSERT(0);
            }
            break;
        }
1940
        offset += TYPE_BYTES[pCol->type];  // sum/avg would convert to int64_t/uint64_t/double during aggregation
C
Cary Xu 已提交
1941 1942
      }
      dataLen += TD_ROW_LEN(rb.pBuf);
C
Cary Xu 已提交
1943 1944 1945
#ifdef TD_DEBUG_PRINT_ROW
      tdSRowPrint(rb.pBuf, pTSchema, __func__);
#endif
C
Cary Xu 已提交
1946
    }
C
Cary Xu 已提交
1947 1948 1949

    ++numOfBlks;

C
Cary Xu 已提交
1950 1951 1952 1953
    pSubmitBlk->dataLen = dataLen;
    msgLen += pSubmitBlk->dataLen;
  }

1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
  if (numOfBlks > 0) {
    (*pReq)->length = msgLen;

    (*pReq)->header.vgId = htonl(vgId);
    (*pReq)->header.contLen = htonl(msgLen);
    (*pReq)->length = (*pReq)->header.contLen;
    (*pReq)->numOfBlocks = htonl(numOfBlks);
    SSubmitBlk* blk = (SSubmitBlk*)((*pReq) + 1);
    while (numOfBlks--) {
      int32_t dataLen = blk->dataLen;
      blk->uid = htobe64(blk->uid);
      blk->suid = htobe64(blk->suid);
      blk->padding = htonl(blk->padding);
      blk->sversion = htonl(blk->sversion);
      blk->dataLen = htonl(blk->dataLen);
      blk->schemaLen = htonl(blk->schemaLen);
      blk->numOfRows = htons(blk->numOfRows);
      blk = (SSubmitBlk*)(blk->data + dataLen);
    }
  } else {
    // no valid rows
    taosMemoryFreeClear(*pReq);
C
Cary Xu 已提交
1976
  }
C
Cary Xu 已提交
1977 1978

  return TSDB_CODE_SUCCESS;
C
Cary Xu 已提交
1979
}
L
Liu Jicong 已提交
1980

1981
char* buildCtbNameByGroupId(const char* stbName, uint64_t groupId) {
L
Liu Jicong 已提交
1982
  ASSERT(stbName[0] != 0);
1983 1984 1985 1986 1987 1988
  SArray* tags = taosArrayInit(0, sizeof(void*));
  SSmlKv* pTag = taosMemoryCalloc(1, sizeof(SSmlKv));
  pTag->key = "group_id";
  pTag->keyLen = strlen(pTag->key);
  pTag->type = TSDB_DATA_TYPE_UBIGINT;
  pTag->u = groupId;
L
Liu Jicong 已提交
1989
  pTag->length = sizeof(uint64_t);
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
  taosArrayPush(tags, &pTag);

  void* cname = taosMemoryCalloc(1, TSDB_TABLE_NAME_LEN + 1);

  RandTableName rname = {
      .tags = tags,
      .sTableName = stbName,
      .sTableNameLen = strlen(stbName),
      .childTableName = cname,
  };

  buildChildTableName(&rname);

  taosMemoryFree(pTag);
  taosArrayDestroy(tags);

  ASSERT(rname.childTableName && rname.childTableName[0]);
  return rname.childTableName;
}

2010
void blockEncode(const SSDataBlock* pBlock, char* data, int32_t* dataLen, int32_t numOfCols, int8_t needCompress) {
2011
  // todo extract method
2012 2013 2014 2015 2016 2017
  int32_t* actualLen = (int32_t*)data;
  data += sizeof(int32_t);

  uint64_t* groupId = (uint64_t*)data;
  data += sizeof(uint64_t);

L
Liu Jicong 已提交
2018
  for (int32_t i = 0; i < numOfCols; ++i) {
2019
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
2020

L
Liu Jicong 已提交
2021
    *((int16_t*)data) = pColInfoData->info.type;
2022 2023
    data += sizeof(int16_t);

L
Liu Jicong 已提交
2024
    *((int32_t*)data) = pColInfoData->info.bytes;
2025 2026 2027
    data += sizeof(int32_t);
  }

2028 2029 2030
  int32_t* colSizes = (int32_t*)data;
  data += numOfCols * sizeof(int32_t);

2031
  *dataLen = blockDataGetSerialMetaSize(numOfCols);
2032 2033 2034 2035 2036 2037

  int32_t numOfRows = pBlock->info.rows;
  for (int32_t col = 0; col < numOfCols; ++col) {
    SColumnInfoData* pColRes = (SColumnInfoData*)taosArrayGet(pBlock->pDataBlock, col);

    // copy the null bitmap
2038
    size_t metaSize = 0;
2039
    if (IS_VAR_DATA_TYPE(pColRes->info.type)) {
2040
      metaSize = numOfRows * sizeof(int32_t);
2041 2042
      memcpy(data, pColRes->varmeta.offset, metaSize);
    } else {
2043 2044
      metaSize = BitmapLen(numOfRows);
      memcpy(data, pColRes->nullbitmap, metaSize);
2045 2046
    }

2047 2048 2049
    data += metaSize;
    (*dataLen) += metaSize;

2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
    if (needCompress) {
      colSizes[col] = blockCompressColData(pColRes, numOfRows, data, needCompress);
      data += colSizes[col];
      (*dataLen) += colSizes[col];
    } else {
      colSizes[col] = colDataGetLength(pColRes, numOfRows);
      (*dataLen) += colSizes[col];
      memmove(data, pColRes->pData, colSizes[col]);
      data += colSizes[col];
    }

    colSizes[col] = htonl(colSizes[col]);
  }

  *actualLen = *dataLen;
  *groupId = pBlock->info.groupId;
}

2068
const char* blockDecode(SSDataBlock* pBlock, int32_t numOfCols, int32_t numOfRows, const char* pData) {
2069 2070 2071 2072 2073 2074 2075 2076
  const char* pStart = pData;

  int32_t dataLen = *(int32_t*)pStart;
  pStart += sizeof(int32_t);

  pBlock->info.groupId = *(uint64_t*)pStart;
  pStart += sizeof(uint64_t);

2077 2078 2079 2080 2081
  if (pBlock->pDataBlock == NULL) {
    pBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));
    taosArraySetSize(pBlock->pDataBlock, numOfCols);
  }

L
Liu Jicong 已提交
2082
  for (int32_t i = 0; i < numOfCols; ++i) {
2083 2084 2085 2086 2087 2088
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
    pColInfoData->info.type = *(int16_t*)pStart;
    pStart += sizeof(int16_t);

    pColInfoData->info.bytes = *(int32_t*)pStart;
    pStart += sizeof(int32_t);
2089 2090 2091 2092

    if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
      pBlock->info.hasVarCol = true;
    }
2093 2094 2095 2096
  }

  blockDataEnsureCapacity(pBlock, numOfRows);

2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108
  int32_t* colLen = (int32_t*)pStart;
  pStart += sizeof(int32_t) * numOfCols;

  for (int32_t i = 0; i < numOfCols; ++i) {
    colLen[i] = htonl(colLen[i]);
    ASSERT(colLen[i] >= 0);

    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
    if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
      memcpy(pColInfoData->varmeta.offset, pStart, sizeof(int32_t) * numOfRows);
      pStart += sizeof(int32_t) * numOfRows;

2109 2110 2111 2112 2113 2114 2115 2116
      if (colLen[i] > 0 && pColInfoData->varmeta.allocLen < colLen[i]) {
        char* tmp = taosMemoryRealloc(pColInfoData->pData, colLen[i]);
        if (tmp == NULL) {
          return NULL;
        }

        pColInfoData->pData = tmp;
        pColInfoData->varmeta.allocLen = colLen[i];
2117
      }
2118 2119

      pColInfoData->varmeta.length = colLen[i];
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135
    } else {
      memcpy(pColInfoData->nullbitmap, pStart, BitmapLen(numOfRows));
      pStart += BitmapLen(numOfRows);
    }

    if (colLen[i] > 0) {
      memcpy(pColInfoData->pData, pStart, colLen[i]);
    }

    // TODO
    // setting this flag to true temporarily so aggregate function on stable will
    // examine NULL value for non-primary key column
    pColInfoData->hasNull = true;
    pStart += colLen[i];
  }

2136
  pBlock->info.rows = numOfRows;
2137 2138
  ASSERT(pStart - pData == dataLen);
  return pStart;
L
Liu Jicong 已提交
2139
}
D
dapan1121 已提交
2140