tdatablock.c 75.9 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 "tlog.h"
20
#include "tname.h"
21

22
#define MALLOC_ALIGN_BYTES  256
23

24
int32_t colDataGetLength(const SColumnInfoData* pColumnInfoData, int32_t numOfRows) {
H
Haojun Liao 已提交
25 26 27 28
  ASSERT(pColumnInfoData != NULL);
  if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
    return pColumnInfoData->varmeta.length;
  } else {
29 30 31 32 33
    if (pColumnInfoData->info.type == TSDB_DATA_TYPE_NULL) {
      return 0;
    } else {
      return pColumnInfoData->info.bytes * numOfRows;
    }
H
Haojun Liao 已提交
34 35 36
  }
}

H
Haojun Liao 已提交
37 38 39 40
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 {
41
    return ((pColumnInfoData->info.type == TSDB_DATA_TYPE_NULL) ? 0 : pColumnInfoData->info.bytes * numOfRows) + BitmapLen(numOfRows);
H
Haojun Liao 已提交
42 43 44
  }
}

H
Haojun Liao 已提交
45 46 47 48
void colDataTrim(SColumnInfoData* pColumnInfoData) {
  // TODO
}

49
int32_t getJsonValueLen(const char* data) {
wmmhello's avatar
wmmhello 已提交
50 51 52 53 54 55 56 57 58
  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 已提交
59
  } else if (tTagIsJson(data)) {  // json string
wmmhello's avatar
wmmhello 已提交
60 61 62 63 64 65 66
    dataLen = ((STag*)(data))->len;
  } else {
    ASSERT(0);
  }
  return dataLen;
}

67 68 69 70
int32_t colDataAppend(SColumnInfoData* pColumnInfoData, uint32_t currentRow, const char* pData, bool isNull) {
  ASSERT(pColumnInfoData != NULL);

  if (isNull) {
H
Haojun Liao 已提交
71 72
    // There is a placehold for each NULL value of binary or nchar type.
    if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
L
Liu Jicong 已提交
73
      pColumnInfoData->varmeta.offset[currentRow] = -1;  // it is a null value of VAR type.
H
Haojun Liao 已提交
74 75 76 77
    } else {
      colDataSetNull_f(pColumnInfoData->nullbitmap, currentRow);
    }

H
Haojun Liao 已提交
78
    pColumnInfoData->hasNull = true;
79 80 81 82 83
    return 0;
  }

  int32_t type = pColumnInfoData->info.type;
  if (IS_VAR_DATA_TYPE(type)) {
wmmhello's avatar
wmmhello 已提交
84
    int32_t dataLen = 0;
85
    if (type == TSDB_DATA_TYPE_JSON) {
wmmhello's avatar
wmmhello 已提交
86
      dataLen = getJsonValueLen(pData);
87
    } else {
wmmhello's avatar
wmmhello 已提交
88
      dataLen = varDataTLen(pData);
89
    }
90

H
Haojun Liao 已提交
91
    SVarColAttr* pAttr = &pColumnInfoData->varmeta;
92
    if (pAttr->allocLen < pAttr->length + dataLen) {
H
Haojun Liao 已提交
93
      uint32_t newSize = pAttr->allocLen;
94
      if (newSize <= 1) {
H
Haojun Liao 已提交
95 96 97
        newSize = 8;
      }

98
      while (newSize < pAttr->length + dataLen) {
H
Haojun Liao 已提交
99 100 101
        newSize = newSize * 1.5;
      }

wafwerar's avatar
wafwerar 已提交
102
      char* buf = taosMemoryRealloc(pColumnInfoData->pData, newSize);
H
Haojun Liao 已提交
103
      if (buf == NULL) {
H
Haojun Liao 已提交
104
        return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
105 106 107 108 109 110 111 112 113
      }

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

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

114 115
    memcpy(pColumnInfoData->pData + len, pData, dataLen);
    pColumnInfoData->varmeta.length += dataLen;
116
  } else {
wmmhello's avatar
wmmhello 已提交
117
    memcpy(pColumnInfoData->pData + pColumnInfoData->info.bytes * currentRow, pData, pColumnInfoData->info.bytes);
118 119 120 121 122
  }

  return 0;
}

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
int32_t colDataReserve(SColumnInfoData* pColumnInfoData, size_t newSize) {
  if (!IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
    return TSDB_CODE_SUCCESS;
  }

  if (pColumnInfoData->varmeta.allocLen >= newSize) {
    return TSDB_CODE_SUCCESS;
  }

  if (pColumnInfoData->varmeta.allocLen < newSize) {
    char* buf = taosMemoryRealloc(pColumnInfoData->pData, newSize);
    if (buf == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }

    pColumnInfoData->pData = buf;
    pColumnInfoData->varmeta.allocLen = newSize;
  }

  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
145 146
static void doCopyNItems(struct SColumnInfoData* pColumnInfoData, int32_t currentRow, const char* pData,
                         int32_t itemLen, int32_t numOfRows) {
H
Haojun Liao 已提交
147 148 149 150 151 152 153
  ASSERT(pColumnInfoData->info.bytes >= itemLen);
  size_t start = 1;

  // the first item
  memcpy(pColumnInfoData->pData, pData, itemLen);

  int32_t t = 0;
L
Liu Jicong 已提交
154 155
  int32_t count = log(numOfRows) / log(2);
  while (t < count) {
H
Haojun Liao 已提交
156
    int32_t xlen = 1 << t;
L
Liu Jicong 已提交
157 158
    memcpy(pColumnInfoData->pData + start * itemLen + pColumnInfoData->varmeta.length, pColumnInfoData->pData,
           xlen * itemLen);
H
Haojun Liao 已提交
159 160 161 162 163 164
    t += 1;
    start += xlen;
  }

  // the tail part
  if (numOfRows > start) {
L
Liu Jicong 已提交
165 166
    memcpy(pColumnInfoData->pData + start * itemLen + currentRow * itemLen, pColumnInfoData->pData,
           (numOfRows - start) * itemLen);
H
Haojun Liao 已提交
167 168 169
  }

  if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
L
Liu Jicong 已提交
170
    for (int32_t i = 0; i < numOfRows; ++i) {
H
Haojun Liao 已提交
171 172 173 174 175 176 177
      pColumnInfoData->varmeta.offset[i + currentRow] = pColumnInfoData->varmeta.length + i * itemLen;
    }

    pColumnInfoData->varmeta.length += numOfRows * itemLen;
  }
}

L
Liu Jicong 已提交
178 179
int32_t colDataAppendNItems(SColumnInfoData* pColumnInfoData, uint32_t currentRow, const char* pData,
                            uint32_t numOfRows) {
H
Haojun Liao 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
  ASSERT(pData != NULL && pColumnInfoData != NULL);

  int32_t len = pColumnInfoData->info.bytes;
  if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
    len = varDataTLen(pData);
    if (pColumnInfoData->varmeta.allocLen < (numOfRows + currentRow) * len) {
      int32_t code = colDataReserve(pColumnInfoData, (numOfRows + currentRow) * len);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
    }
  }

  doCopyNItems(pColumnInfoData, currentRow, pData, len, numOfRows);
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
197 198
static void doBitmapMerge(SColumnInfoData* pColumnInfoData, int32_t numOfRow1, const SColumnInfoData* pSource,
                          int32_t numOfRow2) {
wmmhello's avatar
wmmhello 已提交
199 200
  if (numOfRow2 <= 0) return;

H
Haojun Liao 已提交
201 202 203 204 205 206 207
  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 已提交
208 209
    return;
  }
H
Haojun Liao 已提交
210

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

wmmhello's avatar
wmmhello 已提交
214 215 216
  if (BitmapLen(numOfRow1) == BitmapLen(total)) {
    return;
  }
H
Haojun Liao 已提交
217

wmmhello's avatar
wmmhello 已提交
218 219
  int32_t len = BitmapLen(numOfRow2);
  int32_t i = 0;
H
Haojun Liao 已提交
220

wmmhello's avatar
wmmhello 已提交
221
  uint8_t* start = (uint8_t*)&pColumnInfoData->nullbitmap[BitmapLen(numOfRow1)];
C
Cary Xu 已提交
222 223
  int32_t  overCount = BitmapLen(total) - BitmapLen(numOfRow1);
  while (i < len) {  // size limit of pSource->nullbitmap
wmmhello's avatar
wmmhello 已提交
224
    if (i >= 1) {
C
Cary Xu 已提交
225
      start[i - 1] |= (p[i] >> remindBits);  // copy remind bits
H
Haojun Liao 已提交
226
    }
wmmhello's avatar
wmmhello 已提交
227

C
Cary Xu 已提交
228
    if (i >= overCount) {  // size limit of pColumnInfoData->nullbitmap
wmmhello's avatar
wmmhello 已提交
229 230 231
      return;
    }

C
Cary Xu 已提交
232
    start[i] |= (p[i] << shiftBits);  // copy shift bits
wmmhello's avatar
wmmhello 已提交
233
    i += 1;
H
Haojun Liao 已提交
234 235 236
  }
}

H
Haojun Liao 已提交
237 238
int32_t colDataMergeCol(SColumnInfoData* pColumnInfoData, int32_t numOfRow1, int32_t* capacity,
                        const SColumnInfoData* pSource, int32_t numOfRow2) {
H
Haojun Liao 已提交
239 240 241 242 243
  ASSERT(pColumnInfoData != NULL && pSource != NULL && pColumnInfoData->info.type == pSource->info.type);
  if (numOfRow2 == 0) {
    return numOfRow1;
  }

wmmhello's avatar
wmmhello 已提交
244 245 246
  if (pSource->hasNull) {
    pColumnInfoData->hasNull = pSource->hasNull;
  }
247

248
  uint32_t finalNumOfRows = numOfRow1 + numOfRow2;
H
Haojun Liao 已提交
249 250
  if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
    // Handle the bitmap
251
    if (finalNumOfRows > (*capacity)) {
252 253 254 255 256 257 258
      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 已提交
259 260
    }

L
Liu Jicong 已提交
261
    for (int32_t i = 0; i < numOfRow2; ++i) {
262 263 264 265 266
      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;
      }
267
    }
H
Haojun Liao 已提交
268

269
    // copy data
H
Haojun Liao 已提交
270 271 272
    uint32_t len = pSource->varmeta.length;
    uint32_t oldLen = pColumnInfoData->varmeta.length;
    if (pColumnInfoData->varmeta.allocLen < len + oldLen) {
wafwerar's avatar
wafwerar 已提交
273
      char* tmp = taosMemoryRealloc(pColumnInfoData->pData, len + oldLen);
H
Haojun Liao 已提交
274
      if (tmp == NULL) {
275
        return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
276 277 278 279 280 281
      }

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

282 283 284
    if (pColumnInfoData->pData && pSource->pData) { // TD-20382
      memcpy(pColumnInfoData->pData + oldLen, pSource->pData, len);
    }
285
    pColumnInfoData->varmeta.length = len + oldLen;
H
Haojun Liao 已提交
286
  } else {
287
    if (finalNumOfRows > (*capacity)) {
H
Haojun Liao 已提交
288
      // all data may be null, when the pColumnInfoData->info.type == 0, bytes == 0;
289
      char* tmp = taosMemoryRealloc(pColumnInfoData->pData, finalNumOfRows * pColumnInfoData->info.bytes);
290
      if (tmp == NULL) {
291
        return TSDB_CODE_OUT_OF_MEMORY;
292
      }
H
Haojun Liao 已提交
293

294 295 296 297 298 299 300 301 302 303
      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 已提交
304 305
    }

306 307
    doBitmapMerge(pColumnInfoData, numOfRow1, pSource, numOfRow2);

X
Xiaoyu Wang 已提交
308 309 310 311
    if (pSource->pData) {
      int32_t offset = pColumnInfoData->info.bytes * numOfRow1;
      memcpy(pColumnInfoData->pData + offset, pSource->pData, pSource->info.bytes * numOfRow2);
    }
H
Haojun Liao 已提交
312 313 314 315 316
  }

  return numOfRow1 + numOfRow2;
}

L
Liu Jicong 已提交
317 318
int32_t colDataAssign(SColumnInfoData* pColumnInfoData, const SColumnInfoData* pSource, int32_t numOfRows,
                      const SDataBlockInfo* pBlockInfo) {
319
  ASSERT(pColumnInfoData != NULL && pSource != NULL && pColumnInfoData->info.type == pSource->info.type);
320
  if (numOfRows <= 0) {
321 322 323
    return numOfRows;
  }

324 325 326
  if (pBlockInfo != NULL) {
    ASSERT(pBlockInfo->capacity >= numOfRows);
  }
327

328 329
  if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
    memcpy(pColumnInfoData->varmeta.offset, pSource->varmeta.offset, sizeof(int32_t) * numOfRows);
330 331 332 333 334 335 336 337 338
    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;
    }
339 340

    pColumnInfoData->varmeta.length = pSource->varmeta.length;
341 342 343
    if (pColumnInfoData->pData != NULL && pSource->pData != NULL) {
      memcpy(pColumnInfoData->pData, pSource->pData, pSource->varmeta.length);
    }
344 345
  } else {
    memcpy(pColumnInfoData->nullbitmap, pSource->nullbitmap, BitmapLen(numOfRows));
346
    if (pSource->pData != NULL) {
D
dapan1121 已提交
347 348
      memcpy(pColumnInfoData->pData, pSource->pData, pSource->info.bytes * numOfRows);
    }
349 350
  }

351 352
  pColumnInfoData->hasNull = pSource->hasNull;
  pColumnInfoData->info = pSource->info;
353 354 355
  return 0;
}

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

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

360
int32_t blockDataUpdateTsWindow(SSDataBlock* pDataBlock, int32_t tsColumnIndex) {
361 362 363 364
  if (pDataBlock == NULL || pDataBlock->info.rows <= 0) {
    return 0;
  }

365 366
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  if (numOfCols <= 0) {
367 368 369
    return -1;
  }

370 371
  int32_t index = (tsColumnIndex == -1) ? 0 : tsColumnIndex;

372
  SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, index);
373 374 375 376
  if (pColInfoData->info.type != TSDB_DATA_TYPE_TIMESTAMP) {
    return 0;
  }

377 378 379 380 381 382
  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);

383 384 385
  return 0;
}

386
int32_t blockDataMerge(SSDataBlock* pDest, const SSDataBlock* pSrc) {
wmmhello's avatar
wmmhello 已提交
387
  assert(pSrc != NULL && pDest != NULL);
388 389
  int32_t capacity = pDest->info.capacity;

390 391
  size_t numOfCols = taosArrayGetSize(pDest->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
392
    SColumnInfoData* pCol2 = taosArrayGet(pDest->pDataBlock, i);
393
    SColumnInfoData* pCol1 = taosArrayGet(pSrc->pDataBlock, i);
H
Haojun Liao 已提交
394

395 396
    capacity = pDest->info.capacity;
    colDataMergeCol(pCol2, pDest->info.rows, &capacity, pCol1, pSrc->info.rows);
H
Haojun Liao 已提交
397 398
  }

399
  pDest->info.capacity = capacity;
H
Haojun Liao 已提交
400 401 402 403 404 405 406
  pDest->info.rows += pSrc->info.rows;
  return TSDB_CODE_SUCCESS;
}

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

407 408
  size_t total = 0;
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
L
Liu Jicong 已提交
409
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
410
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
H
Haojun Liao 已提交
411
    total += colDataGetFullLength(pColInfoData, pBlock->info.rows);
H
Haojun Liao 已提交
412 413 414 415 416 417 418
  }

  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 已提交
419 420
int32_t blockDataSplitRows(SSDataBlock* pBlock, bool hasVarCol, int32_t startIndex, int32_t* stopIndex,
                           int32_t pageSize) {
H
Haojun Liao 已提交
421 422
  ASSERT(pBlock != NULL && stopIndex != NULL);

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

H
Haojun Liao 已提交
426 427
  int32_t bitmapChar = 1;

L
Liu Jicong 已提交
428
  size_t headerSize = sizeof(int32_t);
429
  size_t colHeaderSize = sizeof(int32_t) * numOfCols;
L
Liu Jicong 已提交
430
  size_t payloadSize = pageSize - (headerSize + colHeaderSize);
431

H
Haojun Liao 已提交
432
  // TODO speedup by checking if the whole page can fit in firstly.
H
Haojun Liao 已提交
433
  if (!hasVarCol) {
L
Liu Jicong 已提交
434
    size_t  rowSize = blockDataGetRowSize(pBlock);
435 436
    int32_t capacity = payloadSize / (rowSize + numOfCols * bitmapChar / 8.0);
    ASSERT(capacity > 0);
437

438
    *stopIndex = startIndex + capacity - 1;
H
Haojun Liao 已提交
439 440 441
    if (*stopIndex >= numOfRows) {
      *stopIndex = numOfRows - 1;
    }
442

H
Haojun Liao 已提交
443
    return TSDB_CODE_SUCCESS;
444
  }
wmmhello's avatar
wmmhello 已提交
445 446 447 448 449 450
  // 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)) {
451
        if (pColInfoData->varmeta.offset[j] != -1) {
wmmhello's avatar
wmmhello 已提交
452 453
          char* p = colDataGetData(pColInfoData, j);
          size += varDataTLen(p);
H
Haojun Liao 已提交
454 455
        }

wmmhello's avatar
wmmhello 已提交
456
        size += sizeof(pColInfoData->varmeta.offset[0]);
457
      } else {
wmmhello's avatar
wmmhello 已提交
458
        size += pColInfoData->info.bytes;
H
Haojun Liao 已提交
459

wmmhello's avatar
wmmhello 已提交
460 461 462
        if (((j - startIndex) & 0x07) == 0) {
          size += 1;  // the space for null bitmap
        }
H
Haojun Liao 已提交
463 464 465
      }
    }

wmmhello's avatar
wmmhello 已提交
466
    if (size > pageSize) {  // pageSize must be able to hold one row
wmmhello's avatar
wmmhello 已提交
467
      *stopIndex = j - 1;
wmmhello's avatar
wmmhello 已提交
468
      ASSERT(*stopIndex >= startIndex);
wmmhello's avatar
wmmhello 已提交
469 470 471

      return TSDB_CODE_SUCCESS;
    }
H
Haojun Liao 已提交
472
  }
wmmhello's avatar
wmmhello 已提交
473 474 475 476

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

479 480 481 482 483
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;
  }

484
  SSDataBlock* pDst = createDataBlock();
485 486 487 488
  if (pDst == NULL) {
    return NULL;
  }

489
  pDst->info = pBlock->info;
490
  pDst->info.rows = 0;
491
  pDst->info.capacity = 0;
492 493
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
L
Liu Jicong 已提交
494
    SColumnInfoData  colInfo = {0};
495 496
    SColumnInfoData* pSrcCol = taosArrayGet(pBlock->pDataBlock, i);
    colInfo.info = pSrcCol->info;
497
    blockDataAppendColInfo(pDst, &colInfo);
498 499
  }

500 501 502
  blockDataEnsureCapacity(pDst, rowCount);

  for (int32_t i = 0; i < numOfCols; ++i) {
503 504 505 506
    SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, i);
    SColumnInfoData* pDstCol = taosArrayGet(pDst->pDataBlock, i);

    for (int32_t j = startIndex; j < (startIndex + rowCount); ++j) {
507 508
      bool isNull = false;
      if (pBlock->pBlockAgg == NULL) {
509
        isNull = colDataIsNull_s(pColData, j);
510 511 512
      } else {
        isNull = colDataIsNull(pColData, pBlock->info.rows, j, pBlock->pBlockAgg[i]);
      }
513

514 515 516 517 518 519
      if (isNull) {
        colDataAppendNULL(pDstCol, j - startIndex);
      } else {
        char* p = colDataGetData(pColData, j);
        colDataAppend(pDstCol, j - startIndex, p, false);
      }
520 521 522 523 524 525 526
    }
  }

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

H
Haojun Liao 已提交
527 528
/**
 *
529 530 531 532 533
 * +------------------+---------------------------------------------+
 * |the number of rows|                    column #1                |
 * |    (4 bytes)     |------------+-----------------------+--------+
 * |                  | null bitmap| column length(4bytes) | values |
 * +------------------+------------+-----------------------+--------+
H
Haojun Liao 已提交
534 535 536 537
 * @param buf
 * @param pBlock
 * @return
 */
538
int32_t blockDataToBuf(char* buf, const SSDataBlock* pBlock) {
H
Haojun Liao 已提交
539 540 541
  ASSERT(pBlock != NULL);

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

L
Liu Jicong 已提交
544
  size_t  numOfCols = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
545 546 547 548
  int32_t numOfRows = pBlock->info.rows;

  char* pStart = buf + sizeof(uint32_t);

L
Liu Jicong 已提交
549
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
550 551 552 553 554 555 556 557 558
    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);
    }

559
    uint32_t dataSize = colDataGetLength(pCol, numOfRows);
560

L
Liu Jicong 已提交
561
    *(int32_t*)pStart = dataSize;
562 563
    pStart += sizeof(int32_t);

H
Haojun Liao 已提交
564 565 566 567 568 569 570
    memcpy(pStart, pCol->pData, dataSize);
    pStart += dataSize;
  }

  return 0;
}

571
int32_t blockDataFromBuf(SSDataBlock* pBlock, const char* buf) {
L
Liu Jicong 已提交
572
  int32_t numOfRows = *(int32_t*)buf;
573
  blockDataEnsureCapacity(pBlock, numOfRows);
574

575
  pBlock->info.rows = numOfRows;
L
Liu Jicong 已提交
576
  size_t      numOfCols = taosArrayGetSize(pBlock->pDataBlock);
577 578
  const char* pStart = buf + sizeof(uint32_t);

L
Liu Jicong 已提交
579
  for (int32_t i = 0; i < numOfCols; ++i) {
580 581 582
    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, i);

    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
H
Haojun Liao 已提交
583
      size_t metaSize = pBlock->info.rows * sizeof(int32_t);
C
Cary Xu 已提交
584
      char*  tmp = taosMemoryRealloc(pCol->varmeta.offset, metaSize);  // preview calloc is too small
wmmhello's avatar
wmmhello 已提交
585 586 587 588
      if (tmp == NULL) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      pCol->varmeta.offset = (int32_t*)tmp;
589 590 591 592 593 594 595
      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 已提交
596
    int32_t colLength = *(int32_t*)pStart;
597 598
    pStart += sizeof(int32_t);

599 600
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
      if (pCol->varmeta.allocLen < colLength) {
wafwerar's avatar
wafwerar 已提交
601
        char* tmp = taosMemoryRealloc(pCol->pData, colLength);
602 603 604 605 606 607 608 609 610 611
        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);
612 613 614 615 616
    }

    memcpy(pCol->pData, pStart, colLength);
    pStart += colLength;
  }
617 618

  return TSDB_CODE_SUCCESS;
619 620
}

621
// todo remove this
H
Haojun Liao 已提交
622
int32_t blockDataFromBuf1(SSDataBlock* pBlock, const char* buf, size_t capacity) {
X
Xiaoyu Wang 已提交
623
  pBlock->info.rows = *(int32_t*)buf;
H
Haojun Liao 已提交
624
  pBlock->info.id.groupId = *(uint64_t*)(buf + sizeof(int32_t));
H
Haojun Liao 已提交
625

626 627
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);

628
  const char* pStart = buf + sizeof(uint32_t) + sizeof(uint64_t);
H
Haojun Liao 已提交
629 630 631

  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, i);
632
    pCol->hasNull = true;
H
Haojun Liao 已提交
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660

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

661 662 663 664
    if (!colDataIsNNull_s(pCol, 0, pBlock->info.rows)) {
      memcpy(pCol->pData, pStart, colLength);
    }

665
    pStart += pCol->info.bytes * capacity;
H
Haojun Liao 已提交
666 667 668 669 670
  }

  return TSDB_CODE_SUCCESS;
}

671
size_t blockDataGetRowSize(SSDataBlock* pBlock) {
H
Haojun Liao 已提交
672
  ASSERT(pBlock != NULL);
673 674
  if (pBlock->info.rowSize == 0) {
    size_t rowSize = 0;
H
Haojun Liao 已提交
675

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

    pBlock->info.rowSize = rowSize;
H
Haojun Liao 已提交
683 684
  }

685
  return pBlock->info.rowSize;
H
Haojun Liao 已提交
686 687
}

H
Haojun Liao 已提交
688 689 690 691 692
/**
 * @refitem blockDataToBuf for the meta size
 * @param pBlock
 * @return
 */
693
size_t blockDataGetSerialMetaSize(uint32_t numOfCols) {
L
Liu Jicong 已提交
694 695
  // | version | total length | total rows | total columns | flag seg| block group id | column schema | each column
  // length |
696 697
  return sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) + sizeof(int32_t) + sizeof(uint64_t) +
         numOfCols * (sizeof(int8_t) + sizeof(int32_t)) + numOfCols * sizeof(int32_t);
H
Haojun Liao 已提交
698 699
}

X
Xiaoyu Wang 已提交
700
double blockDataGetSerialRowSize(const SSDataBlock* pBlock) {
H
Haojun Liao 已提交
701 702 703
  ASSERT(pBlock != NULL);
  double rowSize = 0;

704
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
L
Liu Jicong 已提交
705
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
706 707 708 709 710 711
    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 已提交
712
      rowSize += 1 / 8.0;  // one bit for each record
H
Haojun Liao 已提交
713 714 715 716 717 718
    }
  }

  return rowSize;
}

H
Haojun Liao 已提交
719
typedef struct SSDataBlockSortHelper {
L
Liu Jicong 已提交
720 721
  SArray*      orderInfo;  // SArray<SBlockOrderInfo>
  SSDataBlock* pDataBlock;
H
Haojun Liao 已提交
722 723 724
} SSDataBlockSortHelper;

int32_t dataBlockCompar(const void* p1, const void* p2, const void* param) {
L
Liu Jicong 已提交
725
  const SSDataBlockSortHelper* pHelper = (const SSDataBlockSortHelper*)param;
H
Haojun Liao 已提交
726 727 728

  SSDataBlock* pDataBlock = pHelper->pDataBlock;

L
Liu Jicong 已提交
729 730
  int32_t left = *(int32_t*)p1;
  int32_t right = *(int32_t*)p2;
H
Haojun Liao 已提交
731 732

  SArray* pInfo = pHelper->orderInfo;
733

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

738
    if (pColInfoData->hasNull) {
739 740
      bool leftNull = colDataIsNull(pColInfoData, pDataBlock->info.rows, left, NULL);
      bool rightNull = colDataIsNull(pColInfoData, pDataBlock->info.rows, right, NULL);
741
      if (leftNull && rightNull) {
L
Liu Jicong 已提交
742
        continue;  // continue to next slot
743
      }
H
Haojun Liao 已提交
744

745
      if (rightNull) {
H
Haojun Liao 已提交
746
        return pOrder->nullFirst ? 1 : -1;
747
      }
H
Haojun Liao 已提交
748

749
      if (leftNull) {
H
Haojun Liao 已提交
750
        return pOrder->nullFirst ? -1 : 1;
751
      }
H
Haojun Liao 已提交
752 753
    }

L
Liu Jicong 已提交
754
    void* left1 = colDataGetData(pColInfoData, left);
755
    void* right1 = colDataGetData(pColInfoData, right);
wmmhello's avatar
wmmhello 已提交
756 757 758 759 760 761
    if (pColInfoData->info.type == TSDB_DATA_TYPE_JSON) {
      if (tTagIsJson(left1) || tTagIsJson(right1)) {
        terrno = TSDB_CODE_QRY_JSON_NOT_SUPPORT_ERROR;
        return 0;
      }
    }
762
    __compar_fn_t fn = getKeyComparFunc(pColInfoData->info.type, pOrder->order);
763

764 765 766 767 768
    int ret = fn(left1, right1);
    if (ret == 0) {
      continue;
    } else {
      return ret;
H
Haojun Liao 已提交
769 770 771 772 773 774
    }
  }

  return 0;
}

L
Liu Jicong 已提交
775 776
static int32_t doAssignOneTuple(SColumnInfoData* pDstCols, int32_t numOfRows, const SSDataBlock* pSrcBlock,
                                int32_t tupleIndex) {
H
Haojun Liao 已提交
777
  int32_t code = 0;
L
Liu Jicong 已提交
778
  size_t  numOfCols = taosArrayGetSize(pSrcBlock->pDataBlock);
H
Haojun Liao 已提交
779 780 781 782 783

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

784
    if (pSrc->hasNull && colDataIsNull(pSrc, pSrcBlock->info.rows, tupleIndex, pSrcBlock->pBlockAgg[i])) {
H
Haojun Liao 已提交
785 786 787 788
      code = colDataAppend(pDst, numOfRows, NULL, true);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
H
Haojun Liao 已提交
789
    } else {
790
      char* p = colDataGetData(pSrc, tupleIndex);
H
Haojun Liao 已提交
791 792 793 794
      code = colDataAppend(pDst, numOfRows, p, false);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
H
Haojun Liao 已提交
795 796
    }
  }
797 798

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
799 800
}

801
static int32_t blockDataAssign(SColumnInfoData* pCols, const SSDataBlock* pDataBlock, const int32_t* index) {
H
Haojun Liao 已提交
802
#if 0
H
Haojun Liao 已提交
803
  for (int32_t i = 0; i < pDataBlock->info.rows; ++i) {
H
Haojun Liao 已提交
804 805 806 807
    int32_t code = doAssignOneTuple(pCols, i, pDataBlock, index[i]);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
H
Haojun Liao 已提交
808
  }
H
Haojun Liao 已提交
809
#else
810 811
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
812 813 814 815
    SColumnInfoData* pDst = &pCols[i];
    SColumnInfoData* pSrc = taosArrayGet(pDataBlock->pDataBlock, i);

    if (IS_VAR_DATA_TYPE(pSrc->info.type)) {
816 817 818
      if (pSrc->varmeta.length != 0) {
        memcpy(pDst->pData, pSrc->pData, pSrc->varmeta.length);
      }
L
Liu Jicong 已提交
819
      pDst->varmeta.length = pSrc->varmeta.length;
H
Haojun Liao 已提交
820

L
Liu Jicong 已提交
821 822 823
      for (int32_t j = 0; j < pDataBlock->info.rows; ++j) {
        pDst->varmeta.offset[j] = pSrc->varmeta.offset[index[j]];
      }
H
Haojun Liao 已提交
824
    } else {
wmmhello's avatar
wmmhello 已提交
825 826 827 828
      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 已提交
829
        }
wmmhello's avatar
wmmhello 已提交
830
        memcpy(pDst->pData + j * pDst->info.bytes, pSrc->pData + index[j] * pDst->info.bytes, pDst->info.bytes);
H
Haojun Liao 已提交
831 832 833 834
      }
    }
  }
#endif
H
Haojun Liao 已提交
835
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
836 837 838
}

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

wafwerar's avatar
wafwerar 已提交
842
  SColumnInfoData* pCols = taosMemoryCalloc(numOfCols, sizeof(SColumnInfoData));
H
Haojun Liao 已提交
843 844 845 846
  if (pCols == NULL) {
    return NULL;
  }

L
Liu Jicong 已提交
847
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
848 849 850 851
    SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, i);
    pCols[i].info = pColInfoData->info;

    if (IS_VAR_DATA_TYPE(pCols[i].info.type)) {
wafwerar's avatar
wafwerar 已提交
852 853
      pCols[i].varmeta.offset = taosMemoryCalloc(rows, sizeof(int32_t));
      pCols[i].pData = taosMemoryCalloc(1, pColInfoData->varmeta.length);
H
Haojun Liao 已提交
854 855 856

      pCols[i].varmeta.length = pColInfoData->varmeta.length;
      pCols[i].varmeta.allocLen = pCols[i].varmeta.length;
H
Haojun Liao 已提交
857
    } else {
wafwerar's avatar
wafwerar 已提交
858 859
      pCols[i].nullbitmap = taosMemoryCalloc(1, BitmapLen(rows));
      pCols[i].pData = taosMemoryCalloc(rows, pCols[i].info.bytes);
H
Haojun Liao 已提交
860 861 862 863 864 865
    }
  }

  return pCols;
}

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

L
Liu Jicong 已提交
869
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
870 871 872 873
    SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, i);
    pColInfoData->info = pCols[i].info;

    if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
wafwerar's avatar
wafwerar 已提交
874
      taosMemoryFreeClear(pColInfoData->varmeta.offset);
H
Haojun Liao 已提交
875 876
      pColInfoData->varmeta = pCols[i].varmeta;
    } else {
wafwerar's avatar
wafwerar 已提交
877
      taosMemoryFreeClear(pColInfoData->nullbitmap);
H
Haojun Liao 已提交
878 879 880
      pColInfoData->nullbitmap = pCols[i].nullbitmap;
    }

wafwerar's avatar
wafwerar 已提交
881
    taosMemoryFreeClear(pColInfoData->pData);
H
Haojun Liao 已提交
882 883 884
    pColInfoData->pData = pCols[i].pData;
  }

wafwerar's avatar
wafwerar 已提交
885
  taosMemoryFreeClear(pCols);
H
Haojun Liao 已提交
886 887 888
}

static int32_t* createTupleIndex(size_t rows) {
wafwerar's avatar
wafwerar 已提交
889
  int32_t* index = taosMemoryCalloc(rows, sizeof(int32_t));
H
Haojun Liao 已提交
890 891 892 893
  if (index == NULL) {
    return NULL;
  }

L
Liu Jicong 已提交
894
  for (int32_t i = 0; i < rows; ++i) {
H
Haojun Liao 已提交
895 896 897 898 899 900
    index[i] = i;
  }

  return index;
}

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

H
Haojun Liao 已提交
903
int32_t blockDataSort(SSDataBlock* pDataBlock, SArray* pOrderInfo) {
H
Haojun Liao 已提交
904 905 906 907 908 909 910
  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 已提交
911 912 913 914 915 916 917

  bool sortColumnHasNull = false;
  bool varTypeSort = false;

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

H
Haojun Liao 已提交
918
    SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, pInfo->slotId);
H
Haojun Liao 已提交
919 920 921 922 923 924 925 926 927
    if (pColInfoData->hasNull) {
      sortColumnHasNull = true;
    }

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

928 929
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);

H
Haojun Liao 已提交
930
  if (taosArrayGetSize(pOrderInfo) == 1 && (!sortColumnHasNull)) {
931
    if (numOfCols == 1) {
H
Haojun Liao 已提交
932 933 934 935 936
      if (!varTypeSort) {
        SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, 0);
        SBlockOrderInfo* pOrder = taosArrayGet(pOrderInfo, 0);

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

938
        __compar_fn_t fn = getKeyComparFunc(pColInfoData->info.type, pOrder->order);
wafwerar's avatar
wafwerar 已提交
939
        taosSort(pColInfoData->pData, pDataBlock->info.rows, pColInfoData->info.bytes, fn);
H
Haojun Liao 已提交
940 941

        int64_t p1 = taosGetTimestampUs();
942
        uDebug("blockDataSort easy cost:%" PRId64 ", rows:%d\n", p1 - p0, pDataBlock->info.rows);
H
Haojun Liao 已提交
943 944 945 946

        return TSDB_CODE_SUCCESS;
      } else {  // var data type
      }
947
    } else if (numOfCols == 2) {
H
Haojun Liao 已提交
948 949 950
    }
  }

H
Haojun Liao 已提交
951 952 953 954 955 956
  int32_t* index = createTupleIndex(rows);
  if (index == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

957 958
  int64_t p0 = taosGetTimestampUs();

H
Haojun Liao 已提交
959
  SSDataBlockSortHelper helper = {.pDataBlock = pDataBlock, .orderInfo = pOrderInfo};
L
Liu Jicong 已提交
960
  for (int32_t i = 0; i < taosArrayGetSize(helper.orderInfo); ++i) {
H
Haojun Liao 已提交
961
    struct SBlockOrderInfo* pInfo = taosArrayGet(helper.orderInfo, i);
H
Haojun Liao 已提交
962
    pInfo->pColData = taosArrayGet(pDataBlock->pDataBlock, pInfo->slotId);
H
Haojun Liao 已提交
963 964
  }

X
Xiaoyu Wang 已提交
965
  terrno = 0;
H
Haojun Liao 已提交
966
  taosqsort(index, rows, sizeof(int32_t), &helper, dataBlockCompar);
X
Xiaoyu Wang 已提交
967
  if (terrno) return terrno;
H
Haojun Liao 已提交
968

969 970
  int64_t p1 = taosGetTimestampUs();

H
Haojun Liao 已提交
971 972
  SColumnInfoData* pCols = createHelpColInfoData(pDataBlock);
  if (pCols == NULL) {
973
    destroyTupleIndex(index);
H
Haojun Liao 已提交
974 975 976 977
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

978 979
  int64_t p2 = taosGetTimestampUs();

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

982
  int64_t p3 = taosGetTimestampUs();
H
Haojun Liao 已提交
983 984

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

C
Cary Xu 已提交
987 988 989
  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 已提交
990
  destroyTupleIndex(index);
H
Haojun Liao 已提交
991 992

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
993
}
994

H
Haojun Liao 已提交
995 996
typedef struct SHelper {
  int32_t index;
L
Liu Jicong 已提交
997 998 999 1000 1001
  union {
    char*   pData;
    int64_t i64;
    double  d64;
  };
H
Haojun Liao 已提交
1002 1003 1004 1005 1006 1007
} SHelper;

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

L
Liu Jicong 已提交
1008
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
1009
    SBlockOrderInfo* pInfo = taosArrayGet(pOrderInfo, i);
H
Haojun Liao 已提交
1010
    SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, pInfo->slotId);
H
Haojun Liao 已提交
1011 1012 1013 1014 1015 1016
    pInfo->pColData = pColInfo;
    sortValLengthPerRow += pColInfo->info.bytes;
  }

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

wafwerar's avatar
wafwerar 已提交
1017 1018
  char*    buf = taosMemoryCalloc(1, len);
  SHelper* phelper = taosMemoryCalloc(numOfRows, sizeof(SHelper));
L
Liu Jicong 已提交
1019
  for (int32_t i = 0; i < numOfRows; ++i) {
H
Haojun Liao 已提交
1020 1021 1022 1023 1024
    phelper[i].index = i;
    phelper[i].pData = buf + sortValLengthPerRow * i;
  }

  int32_t offset = 0;
L
Liu Jicong 已提交
1025
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
1026
    SBlockOrderInfo* pInfo = taosArrayGet(pOrderInfo, i);
L
Liu Jicong 已提交
1027 1028 1029 1030
    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 已提交
1031 1032 1033 1034 1035 1036 1037 1038 1039
    }

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

  return phelper;
}

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

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

L
Liu Jicong 已提交
1044 1045
  SHelper* left = (SHelper*)p1;
  SHelper* right = (SHelper*)p2;
H
Haojun Liao 已提交
1046 1047 1048 1049

  SArray* pInfo = pHelper->orderInfo;

  int32_t offset = 0;
L
Liu Jicong 已提交
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
  //  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 已提交
1094 1095 1096 1097 1098

  return 0;
}

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

H
Haojun Liao 已提交
1102
  SSDataBlockSortHelper helper = {.pDataBlock = pDataBlock, .orderInfo = pOrderInfo};
H
Haojun Liao 已提交
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112

  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 已提交
1113
  int64_t          p1 = taosGetTimestampUs();
H
Haojun Liao 已提交
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
  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 已提交
1133 1134
  printf("sort:%" PRId64 ", create:%" PRId64 ", assign:%" PRId64 ", copyback:%" PRId64 ", rows:%d\n", p1 - p0, p2 - p1,
         p3 - p2, p4 - p3, rows);
H
Haojun Liao 已提交
1135
  //  destroyTupleIndex(index);
1136
  return 0;
H
Haojun Liao 已提交
1137 1138
}

1139
void blockDataCleanup(SSDataBlock* pDataBlock) {
H
Haojun Liao 已提交
1140
  blockDataEmpty(pDataBlock);
H
Haojun Liao 已提交
1141
  SDataBlockInfo* pInfo = &pDataBlock->info;
H
Haojun Liao 已提交
1142 1143
  pInfo->id.uid = 0;
  pInfo->id.groupId = 0;
H
Haojun Liao 已提交
1144
}
1145

H
Haojun Liao 已提交
1146 1147 1148
void blockDataEmpty(SSDataBlock* pDataBlock) {
  SDataBlockInfo* pInfo = &pDataBlock->info;
  ASSERT(pInfo->rows <= pDataBlock->info.capacity);
H
Haojun Liao 已提交
1149
  if (pInfo->capacity == 0) {
1150 1151 1152
    return;
  }

1153 1154
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
1155
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
H
Haojun Liao 已提交
1156
    colInfoDataCleanup(p, pInfo->capacity);
1157
  }
H
Haojun Liao 已提交
1158 1159 1160 1161

  pInfo->rows = 0;
  pInfo->window.ekey = 0;
  pInfo->window.skey = 0;
1162 1163
}

1164
// todo temporarily disable it
H
Haojun Liao 已提交
1165
static int32_t doEnsureCapacity(SColumnInfoData* pColumn, const SDataBlockInfo* pBlockInfo, uint32_t numOfRows, bool clearPayload) {
1166
  ASSERT(numOfRows > 0 /*&& pBlockInfo->capacity >= pBlockInfo->rows*/);
H
Haojun Liao 已提交
1167
  if (numOfRows <= pBlockInfo->capacity) {
X
Xiaoyu Wang 已提交
1168 1169 1170
    return TSDB_CODE_SUCCESS;
  }

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

1174 1175
  int32_t existedRows = pBlockInfo->rows;

D
dapan1121 已提交
1176
  if (IS_VAR_DATA_TYPE(pColumn->info.type)) {
wafwerar's avatar
wafwerar 已提交
1177
    char* tmp = taosMemoryRealloc(pColumn->varmeta.offset, sizeof(int32_t) * numOfRows);
D
dapan1121 已提交
1178 1179 1180
    if (tmp == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
1181

D
dapan1121 已提交
1182
    pColumn->varmeta.offset = (int32_t*)tmp;
1183
    memset(&pColumn->varmeta.offset[existedRows], 0, sizeof(int32_t) * (numOfRows - existedRows));
D
dapan1121 已提交
1184
  } else {
1185
    // prepare for the null bitmap
wafwerar's avatar
wafwerar 已提交
1186
    char* tmp = taosMemoryRealloc(pColumn->nullbitmap, BitmapLen(numOfRows));
D
dapan1121 已提交
1187 1188 1189
    if (tmp == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
1190

1191
    int32_t oldLen = BitmapLen(existedRows);
D
dapan1121 已提交
1192
    pColumn->nullbitmap = tmp;
1193
    memset(&pColumn->nullbitmap[oldLen], 0, BitmapLen(numOfRows) - oldLen);
1194
    ASSERT(pColumn->info.bytes);
1195 1196 1197

    // make sure the allocated memory is MALLOC_ALIGN_BYTES aligned
    tmp = taosMemoryMallocAlign(MALLOC_ALIGN_BYTES, numOfRows * pColumn->info.bytes);
D
dapan1121 已提交
1198 1199 1200
    if (tmp == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
L
Liu Jicong 已提交
1201

1202 1203 1204 1205 1206 1207
    // copy back the existed data
    if (pColumn->pData != NULL) {
      memcpy(tmp, pColumn->pData, existedRows * pColumn->info.bytes);
      taosMemoryFreeClear(pColumn->pData);
    }

D
dapan1121 已提交
1208
    pColumn->pData = tmp;
1209 1210 1211

    // todo remove it soon
#if defined LINUX
H
Haojun Liao 已提交
1212
    ASSERT((((uint64_t)pColumn->pData) & (MALLOC_ALIGN_BYTES - 1)) == 0x0);
1213
#endif
H
Haojun Liao 已提交
1214

H
Haojun Liao 已提交
1215 1216 1217
    if (clearPayload) {
      memset(tmp + pColumn->info.bytes * existedRows, 0, pColumn->info.bytes * (numOfRows - existedRows));
    }
D
dapan1121 已提交
1218 1219 1220 1221 1222
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1223
void colInfoDataCleanup(SColumnInfoData* pColumn, uint32_t numOfRows) {
1224
  pColumn->hasNull = false;
H
Haojun Liao 已提交
1225

1226 1227
  if (IS_VAR_DATA_TYPE(pColumn->info.type)) {
    pColumn->varmeta.length = 0;
1228
    if (pColumn->varmeta.offset != NULL) {
H
Haojun Liao 已提交
1229 1230
      memset(pColumn->varmeta.offset, 0, sizeof(int32_t) * numOfRows);
    }
1231
  } else {
dengyihao's avatar
dengyihao 已提交
1232 1233 1234
    if (pColumn->nullbitmap != NULL) {
      memset(pColumn->nullbitmap, 0, BitmapLen(numOfRows));
    }
1235 1236 1237
  }
}

H
Haojun Liao 已提交
1238
int32_t colInfoDataEnsureCapacity(SColumnInfoData* pColumn, uint32_t numOfRows, bool clearPayload) {
1239
  SDataBlockInfo info = {0};
H
Haojun Liao 已提交
1240
  return doEnsureCapacity(pColumn, &info, numOfRows, clearPayload);
1241 1242
}

D
dapan1121 已提交
1243 1244
int32_t blockDataEnsureCapacity(SSDataBlock* pDataBlock, uint32_t numOfRows) {
  int32_t code = 0;
H
Haojun Liao 已提交
1245
  if (numOfRows == 0 || numOfRows <= pDataBlock->info.capacity) {
H
Haojun Liao 已提交
1246 1247
    return TSDB_CODE_SUCCESS;
  }
L
Liu Jicong 已提交
1248

1249 1250
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
D
dapan1121 已提交
1251
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
H
Haojun Liao 已提交
1252
    code = doEnsureCapacity(p, &pDataBlock->info, numOfRows, true);
D
dapan1121 已提交
1253 1254
    if (code) {
      return code;
1255 1256
    }
  }
H
Haojun Liao 已提交
1257

H
Haojun Liao 已提交
1258
  pDataBlock->info.capacity = numOfRows;
H
Haojun Liao 已提交
1259 1260 1261
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1262 1263 1264 1265 1266 1267
int32_t blockDataEnsureCapacityNoClear(SSDataBlock* pDataBlock, uint32_t numOfRows) {
  int32_t code = 0;
  if (numOfRows == 0 || numOfRows <= pDataBlock->info.capacity) {
    return TSDB_CODE_SUCCESS;
  }

1268 1269
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
D
dapan1121 已提交
1270
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
H
Haojun Liao 已提交
1271
    code = doEnsureCapacity(p, &pDataBlock->info, numOfRows, false);
D
dapan1121 已提交
1272 1273
    if (code) {
      return code;
1274 1275
    }
  }
H
Haojun Liao 已提交
1276

H
Haojun Liao 已提交
1277
  pDataBlock->info.capacity = numOfRows;
H
Haojun Liao 已提交
1278 1279 1280
  return TSDB_CODE_SUCCESS;
}

1281 1282 1283 1284 1285 1286 1287 1288
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);
wmmhello's avatar
wmmhello 已提交
1289
  pBlock->pDataBlock = NULL;
1290
  taosMemoryFreeClear(pBlock->pBlockAgg);
L
Liu Jicong 已提交
1291
  taosMemoryFree(pBlock->info.pTag);
1292 1293 1294
  memset(&pBlock->info, 0, sizeof(SDataBlockInfo));
}

H
Haojun Liao 已提交
1295 1296 1297 1298 1299
void* blockDataDestroy(SSDataBlock* pBlock) {
  if (pBlock == NULL) {
    return NULL;
  }

1300
  blockDataFreeRes(pBlock);
wafwerar's avatar
wafwerar 已提交
1301
  taosMemoryFreeClear(pBlock);
H
Haojun Liao 已提交
1302
  return NULL;
D
dapan1121 已提交
1303
}
1304

L
Liu Jicong 已提交
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
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 已提交
1328
    if (pSrc->pData == NULL && (!IS_VAR_DATA_TYPE(pSrc->info.type))) {
L
Liu Jicong 已提交
1329 1330 1331 1332 1333 1334
      continue;
    }

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

1335
  uint32_t cap = dst->info.capacity;
1336
  dst->info = src->info;
1337
  dst->info.capacity = cap;
L
Liu Jicong 已提交
1338 1339
  return 0;
}
1340

5
54liuyao 已提交
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
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);
    colDataAssign(pDst, pSrc, src->info.rows, &src->info);
  }
H
Haojun Liao 已提交
1357

1358
  uint32_t cap = dst->info.capacity;
1359
  dst->info = src->info;
1360
  dst->info.capacity = cap;
5
54liuyao 已提交
1361 1362 1363
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1364 1365 1366
SSDataBlock* createSpecialDataBlock(EStreamType type) {
  SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
  pBlock->info.hasVarCol = false;
H
Haojun Liao 已提交
1367
  pBlock->info.id.groupId = 0;
L
Liu Jicong 已提交
1368 1369
  pBlock->info.rows = 0;
  pBlock->info.type = type;
1370
  pBlock->info.rowSize = sizeof(TSKEY) + sizeof(TSKEY) + sizeof(uint64_t) + sizeof(uint64_t) + sizeof(TSKEY) +
L
Liu Jicong 已提交
1371
                         sizeof(TSKEY) + VARSTR_HEADER_SIZE + TSDB_TABLE_NAME_LEN;
L
Liu Jicong 已提交
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
  pBlock->info.watermark = INT64_MIN;

  pBlock->pDataBlock = taosArrayInit(6, sizeof(SColumnInfoData));
  SColumnInfoData infoData = {0};
  infoData.info.type = TSDB_DATA_TYPE_TIMESTAMP;
  infoData.info.bytes = sizeof(TSKEY);
  // window start ts
  taosArrayPush(pBlock->pDataBlock, &infoData);
  // window end ts
  taosArrayPush(pBlock->pDataBlock, &infoData);

  infoData.info.type = TSDB_DATA_TYPE_UBIGINT;
  infoData.info.bytes = sizeof(uint64_t);
  // uid
  taosArrayPush(pBlock->pDataBlock, &infoData);
  // group id
  taosArrayPush(pBlock->pDataBlock, &infoData);

1390 1391
  infoData.info.type = TSDB_DATA_TYPE_TIMESTAMP;
  infoData.info.bytes = sizeof(TSKEY);
L
Liu Jicong 已提交
1392 1393 1394 1395 1396
  // calculate start ts
  taosArrayPush(pBlock->pDataBlock, &infoData);
  // calculate end ts
  taosArrayPush(pBlock->pDataBlock, &infoData);

1397 1398
  // table name
  infoData.info.type = TSDB_DATA_TYPE_VARCHAR;
L
Liu Jicong 已提交
1399
  infoData.info.bytes = VARSTR_HEADER_SIZE + TSDB_TABLE_NAME_LEN;
1400 1401
  taosArrayPush(pBlock->pDataBlock, &infoData);

L
Liu Jicong 已提交
1402 1403 1404
  return pBlock;
}

1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
SSDataBlock* blockCopyOneRow(const SSDataBlock* pDataBlock, int32_t rowIdx) {
  if (pDataBlock == NULL) {
    return NULL;
  }

  SSDataBlock* pBlock = createDataBlock();
  pBlock->info = pDataBlock->info;
  pBlock->info.rows = 0;
  pBlock->info.capacity = 0;

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

  int32_t code = blockDataEnsureCapacity(pBlock, 1);
  if (code != TSDB_CODE_SUCCESS) {
    terrno = code;
    blockDataDestroy(pBlock);
    return NULL;
  }

  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, i);
    SColumnInfoData* pSrc = taosArrayGet(pDataBlock->pDataBlock, i);
    void*            pData = colDataGetData(pSrc, rowIdx);
    bool             isNull = colDataIsNull(pSrc, pDataBlock->info.rows, rowIdx, NULL);
    colDataAppend(pDst, 0, pData, isNull);
  }

  pBlock->info.rows = 1;

  return pBlock;
}

1442
SSDataBlock* createOneDataBlock(const SSDataBlock* pDataBlock, bool copyData) {
C
Cary Xu 已提交
1443
  if (pDataBlock == NULL) {
1444 1445
    return NULL;
  }
1446

1447 1448 1449 1450
  SSDataBlock* pBlock = createDataBlock();
  pBlock->info = pDataBlock->info;
  pBlock->info.rows = 0;
  pBlock->info.capacity = 0;
1451
  pBlock->info.rowSize = 0;
1452

1453
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
L
Liu Jicong 已提交
1454
  for (int32_t i = 0; i < numOfCols; ++i) {
1455
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
1456 1457
    SColumnInfoData  colInfo = {.hasNull = true, .info = p->info};
    blockDataAppendColInfo(pBlock, &colInfo);
1458 1459
  }

1460
  if (copyData) {
1461 1462 1463 1464 1465 1466 1467
    int32_t code = blockDataEnsureCapacity(pBlock, pDataBlock->info.rows);
    if (code != TSDB_CODE_SUCCESS) {
      terrno = code;
      blockDataDestroy(pBlock);
      return NULL;
    }

1468 1469 1470
    for (int32_t i = 0; i < numOfCols; ++i) {
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, i);
      SColumnInfoData* pSrc = taosArrayGet(pDataBlock->pDataBlock, i);
1471
      colDataAssign(pDst, pSrc, pDataBlock->info.rows, &pDataBlock->info);
1472 1473 1474 1475 1476 1477
    }

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

1478 1479 1480
  return pBlock;
}

1481 1482 1483 1484
SSDataBlock* createDataBlock() {
  SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
  if (pBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
1485
    return NULL;
1486 1487 1488 1489 1490 1491
  }

  pBlock->pDataBlock = taosArrayInit(4, sizeof(SColumnInfoData));
  if (pBlock->pDataBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    taosMemoryFree(pBlock);
wmmhello's avatar
wmmhello 已提交
1492
    return NULL;
1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
  }

  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 已提交
1514
  // todo disable it temporarily
L
Liu Jicong 已提交
1515
  //  ASSERT(pColInfoData->info.type != 0);
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
  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 已提交
1527
  col.info.type = type;
1528 1529 1530 1531 1532
  col.info.bytes = bytes;

  return col;
}

L
Liu Jicong 已提交
1533
SColumnInfoData* bdGetColumnInfoData(const SSDataBlock* pBlock, int32_t index) {
1534 1535 1536 1537 1538 1539 1540 1541
  ASSERT(pBlock != NULL);
  if (index >= taosArrayGetSize(pBlock->pDataBlock)) {
    return NULL;
  }

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

1542
size_t blockDataGetCapacityInRow(const SSDataBlock* pBlock, size_t pageSize) {
1543
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
1544

1545
  int32_t payloadSize = pageSize - blockDataGetSerialMetaSize(numOfCols);
1546 1547
  int32_t rowSize = pBlock->info.rowSize;
  int32_t nRows = payloadSize / rowSize;
H
Haojun Liao 已提交
1548
  ASSERT(nRows >= 1);
1549 1550 1551

  // the true value must be less than the value of nRows
  int32_t additional = 0;
1552
  for (int32_t i = 0; i < numOfCols; ++i) {
1553 1554 1555 1556 1557 1558 1559 1560 1561
    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;
1562
  ASSERT(newRows <= nRows && newRows >= 1);
1563 1564

  return newRows;
1565
}
H
Haojun Liao 已提交
1566

1567
void colDataDestroy(SColumnInfoData* pColData) {
L
Liu Jicong 已提交
1568
  if (!pColData) return;
1569
  if (IS_VAR_DATA_TYPE(pColData->info.type)) {
wmmhello's avatar
wmmhello 已提交
1570
    taosMemoryFreeClear(pColData->varmeta.offset);
1571
  } else {
wmmhello's avatar
wmmhello 已提交
1572
    taosMemoryFreeClear(pColData->nullbitmap);
1573 1574
  }

wmmhello's avatar
wmmhello 已提交
1575
  taosMemoryFreeClear(pColData->pData);
1576 1577
}

H
Haojun Liao 已提交
1578 1579 1580 1581
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 已提交
1582 1583
  if (n % 8 == 0) {
    memmove(nullBitmap, nullBitmap + n / 8, newLen);
H
Haojun Liao 已提交
1584
  } else {
1585
    int32_t  tail = n % 8;
1586
    int32_t  i = 0;
C
Cary Xu 已提交
1587
    uint8_t* p = (uint8_t*)nullBitmap;
H
Haojun Liao 已提交
1588

1589 1590 1591 1592 1593 1594 1595 1596 1597
    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 已提交
1598

1599
        i += 1;
H
Haojun Liao 已提交
1600
      }
1601 1602
    } else if (n > 8) {
      int32_t gap = len - newLen;
1603
      while (i < newLen) {
1604 1605 1606 1607 1608 1609 1610
        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 已提交
1611

1612 1613
        i += 1;
      }
H
Haojun Liao 已提交
1614 1615 1616 1617
    }
  }
}

X
Xiaoyu Wang 已提交
1618
static int32_t colDataMoveVarData(SColumnInfoData* pColInfoData, size_t start, size_t end) {
wmmhello's avatar
wmmhello 已提交
1619 1620 1621
  int32_t dataOffset = -1;
  int32_t dataLen = 0;
  int32_t beigin = start;
X
Xiaoyu Wang 已提交
1622
  while (beigin < end) {
wmmhello's avatar
wmmhello 已提交
1623
    int32_t offset = pColInfoData->varmeta.offset[beigin];
X
Xiaoyu Wang 已提交
1624
    if (offset == -1) {
wmmhello's avatar
wmmhello 已提交
1625 1626 1627
      beigin++;
      continue;
    }
X
Xiaoyu Wang 已提交
1628
    if (start != 0) {
wmmhello's avatar
wmmhello 已提交
1629 1630
      pColInfoData->varmeta.offset[beigin] = dataLen;
    }
X
Xiaoyu Wang 已提交
1631 1632
    char* data = pColInfoData->pData + offset;
    if (dataOffset == -1) dataOffset = offset;  // mark the begin of data
wmmhello's avatar
wmmhello 已提交
1633 1634 1635 1636 1637 1638 1639 1640
    int32_t type = pColInfoData->info.type;
    if (type == TSDB_DATA_TYPE_JSON) {
      dataLen += getJsonValueLen(data);
    } else {
      dataLen += varDataTLen(data);
    }
    beigin++;
  }
1641

X
Xiaoyu Wang 已提交
1642
  if (dataOffset > 0) {
wmmhello's avatar
wmmhello 已提交
1643 1644
    memmove(pColInfoData->pData, pColInfoData->pData + dataOffset, dataLen);
  }
1645 1646

  memmove(pColInfoData->varmeta.offset, &pColInfoData->varmeta.offset[start], (end - start) * sizeof(int32_t));
wmmhello's avatar
wmmhello 已提交
1647 1648 1649
  return dataLen;
}

H
Haojun Liao 已提交
1650 1651
static void colDataTrimFirstNRows(SColumnInfoData* pColInfoData, size_t n, size_t total) {
  if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
wmmhello's avatar
wmmhello 已提交
1652
    pColInfoData->varmeta.length = colDataMoveVarData(pColInfoData, n, total);
H
Haojun Liao 已提交
1653 1654

    // clear the offset value of the unused entries.
1655
    memset(&pColInfoData->varmeta.offset[total - n], 0, n);
H
Haojun Liao 已提交
1656 1657 1658 1659 1660 1661 1662
  } 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 已提交
1663
int32_t blockDataTrimFirstNRows(SSDataBlock* pBlock, size_t n) {
H
Haojun Liao 已提交
1664 1665 1666 1667 1668
  if (n == 0) {
    return TSDB_CODE_SUCCESS;
  }

  if (pBlock->info.rows <= n) {
H
Haojun Liao 已提交
1669
    blockDataEmpty(pBlock);
H
Haojun Liao 已提交
1670
  } else {
1671 1672
    size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
1673 1674 1675 1676 1677 1678 1679 1680 1681
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
      colDataTrimFirstNRows(pColInfoData, n, pBlock->info.rows);
    }

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

wmmhello's avatar
wmmhello 已提交
1682 1683
static void colDataKeepFirstNRows(SColumnInfoData* pColInfoData, size_t n, size_t total) {
  if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
wmmhello's avatar
wmmhello 已提交
1684
    pColInfoData->varmeta.length = colDataMoveVarData(pColInfoData, 0, n);
wmmhello's avatar
wmmhello 已提交
1685
    memset(&pColInfoData->varmeta.offset[n], 0, total - n);
H
Haojun Liao 已提交
1686
  } else {  // reset the bitmap value
1687 1688
    /*int32_t stopIndex = BitmapLen(n) * 8;
    for(int32_t i = n; i < stopIndex; ++i) {
H
Haojun Liao 已提交
1689 1690 1691 1692 1693
      colDataClearNull_f(pColInfoData->nullbitmap, i);
    }

    int32_t remain = BitmapLen(total) - BitmapLen(n);
    if (remain > 0) {
1694 1695
      memset(pColInfoData->nullbitmap+BitmapLen(n), 0, remain);
    }*/
wmmhello's avatar
wmmhello 已提交
1696 1697 1698 1699 1700
  }
}

int32_t blockDataKeepFirstNRows(SSDataBlock* pBlock, size_t n) {
  if (n == 0) {
H
Haojun Liao 已提交
1701
    blockDataEmpty(pBlock);
wmmhello's avatar
wmmhello 已提交
1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
    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 已提交
1719
int32_t tEncodeDataBlock(void** buf, const SSDataBlock* pBlock) {
H
Haojun Liao 已提交
1720
  int64_t tbUid = pBlock->info.id.uid;
1721
  int16_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
  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);
1735
    tlen += taosEncodeFixedI8(buf, pColData->info.type);
H
Haojun Liao 已提交
1736
    tlen += taosEncodeFixedI32(buf, pColData->info.bytes);
S
slzhou@taodata.com 已提交
1737
    tlen += taosEncodeFixedBool(buf, pColData->hasNull);
H
Haojun Liao 已提交
1738 1739 1740 1741 1742 1743 1744 1745

    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 已提交
1746
    tlen += taosEncodeFixedI32(buf, len);
H
Haojun Liao 已提交
1747 1748 1749 1750 1751 1752 1753 1754 1755

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

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

1756 1757
  int16_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);

H
Haojun Liao 已提交
1758
  buf = taosDecodeFixedU64(buf, &pBlock->info.id.uid);
1759
  buf = taosDecodeFixedI16(buf, &numOfCols);
H
Haojun Liao 已提交
1760 1761 1762 1763 1764 1765 1766
  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);
1767
    buf = taosDecodeFixedI8(buf, &data.info.type);
H
Haojun Liao 已提交
1768
    buf = taosDecodeFixedI32(buf, &data.info.bytes);
S
slzhou@taodata.com 已提交
1769
    buf = taosDecodeFixedBool(buf, &data.hasNull);
H
Haojun Liao 已提交
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779

    if (IS_VAR_DATA_TYPE(data.info.type)) {
      buf = taosDecodeBinary(buf, (void**)&data.varmeta.offset, pBlock->info.rows * sizeof(int32_t));
    } 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);
1780 1781 1782 1783
    if (IS_VAR_DATA_TYPE(data.info.type)) {
      data.varmeta.length = len;
      data.varmeta.allocLen = len;
    }
S
slzhou 已提交
1784
    taosArrayPush(pBlock->pDataBlock, &data);
H
Haojun Liao 已提交
1785 1786
  }
  return (void*)buf;
L
Liu Jicong 已提交
1787
}
L
Liu Jicong 已提交
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801

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 已提交
1802
void* tDecodeDataBlocks(const void* buf, SArray** blocks) {
L
Liu Jicong 已提交
1803 1804
  int32_t sz;
  buf = taosDecodeFixedI32(buf, &sz);
L
Liu Jicong 已提交
1805 1806

  *blocks = taosArrayInit(sz, sizeof(SSDataBlock));
L
Liu Jicong 已提交
1807 1808 1809
  for (int32_t i = 0; i < sz; i++) {
    SSDataBlock pBlock = {0};
    buf = tDecodeDataBlock(buf, &pBlock);
L
Liu Jicong 已提交
1810
    taosArrayPush(*blocks, &pBlock);
L
Liu Jicong 已提交
1811 1812 1813
  }
  return (void*)buf;
}
L
Liu Jicong 已提交
1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846

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

  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;
    }
  }
1847 1848
  struct tm ptm = {0};
  taosLocalTime(&tt, &ptm);
L
Liu Jicong 已提交
1849
  size_t pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
L
Liu Jicong 已提交
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860

  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 已提交
1861

1862
void blockDebugShowDataBlock(SSDataBlock* pBlock, const char* flag) {
S
slzhou 已提交
1863 1864
  SArray* dataBlocks = taosArrayInit(1, sizeof(SSDataBlock*));
  taosArrayPush(dataBlocks, &pBlock);
1865 1866 1867 1868
  blockDebugShowDataBlocks(dataBlocks, flag);
  taosArrayDestroy(dataBlocks);
}

S
slzhou 已提交
1869
void blockDebugShowDataBlocks(const SArray* dataBlocks, const char* flag) {
C
Cary Xu 已提交
1870
  char    pBuf[128] = {0};
L
Liu Jicong 已提交
1871 1872
  int32_t sz = taosArrayGetSize(dataBlocks);
  for (int32_t i = 0; i < sz; i++) {
C
Cary Xu 已提交
1873
    SSDataBlock* pDataBlock = taosArrayGetP(dataBlocks, i);
L
Liu Jicong 已提交
1874
    size_t       numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
1875

L
Liu Jicong 已提交
1876
    int32_t rows = pDataBlock->info.rows;
C
Cary Xu 已提交
1877 1878
    printf("%s |block ver %" PRIi64 " |block type %d |child id %d|group id %" PRIu64 "\n", flag,
           pDataBlock->info.version, (int32_t)pDataBlock->info.type, pDataBlock->info.childId,
H
Haojun Liao 已提交
1879
           pDataBlock->info.id.groupId);
L
Liu Jicong 已提交
1880
    for (int32_t j = 0; j < rows; j++) {
C
Cary Xu 已提交
1881
      printf("%s |", flag);
1882
      for (int32_t k = 0; k < numOfCols; k++) {
L
Liu Jicong 已提交
1883 1884
        SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, k);
        void*            var = POINTER_SHIFT(pColInfoData->pData, j * pColInfoData->info.bytes);
5
54liuyao 已提交
1885
        if (colDataIsNull(pColInfoData, rows, j, NULL)) {
5
54liuyao 已提交
1886 1887 1888
          printf(" %15s |", "NULL");
          continue;
        }
L
Liu Jicong 已提交
1889 1890 1891 1892 1893
        switch (pColInfoData->info.type) {
          case TSDB_DATA_TYPE_TIMESTAMP:
            formatTimestamp(pBuf, *(uint64_t*)var, TSDB_TIME_PRECISION_MILLI);
            printf(" %25s |", pBuf);
            break;
C
Cary Xu 已提交
1894 1895 1896
          case TSDB_DATA_TYPE_BOOL:
            printf(" %15d |", *(int32_t*)var);
            break;
L
Liu Jicong 已提交
1897 1898 1899
          case TSDB_DATA_TYPE_INT:
            printf(" %15d |", *(int32_t*)var);
            break;
L
Liu Jicong 已提交
1900 1901 1902
          case TSDB_DATA_TYPE_UINT:
            printf(" %15u |", *(uint32_t*)var);
            break;
L
Liu Jicong 已提交
1903
          case TSDB_DATA_TYPE_BIGINT:
1904
            printf(" %15" PRId64 " |", *(int64_t*)var);
L
Liu Jicong 已提交
1905
            break;
L
Liu Jicong 已提交
1906
          case TSDB_DATA_TYPE_UBIGINT:
1907
            printf(" %15" PRIu64 " |", *(uint64_t*)var);
L
Liu Jicong 已提交
1908
            break;
C
Cary Xu 已提交
1909 1910 1911
          case TSDB_DATA_TYPE_FLOAT:
            printf(" %15f |", *(float*)var);
            break;
5
54liuyao 已提交
1912
          case TSDB_DATA_TYPE_DOUBLE:
C
Cary Xu 已提交
1913
            printf(" %15lf |", *(double*)var);
5
54liuyao 已提交
1914
            break;
C
Cary Xu 已提交
1915 1916
          case TSDB_DATA_TYPE_VARCHAR: {
            char*   pData = colDataGetVarData(pColInfoData, j);
C
Cary Xu 已提交
1917 1918
            int32_t dataSize = TMIN(sizeof(pBuf) - 1, varDataLen(pData));
            memset(pBuf, 0, dataSize + 1);
C
Cary Xu 已提交
1919 1920 1921 1922 1923
            strncpy(pBuf, varDataVal(pData), dataSize);
            printf(" %15s |", pBuf);
          } break;
          case TSDB_DATA_TYPE_NCHAR: {
            char*   pData = colDataGetVarData(pColInfoData, j);
C
Cary Xu 已提交
1924
            int32_t dataSize = TMIN(sizeof(pBuf), varDataLen(pData));
C
Cary Xu 已提交
1925
            memset(pBuf, 0, dataSize);
C
Cary Xu 已提交
1926
            (void)taosUcs4ToMbs((TdUcs4*)varDataVal(pData), dataSize, pBuf);
C
Cary Xu 已提交
1927 1928 1929 1930
            printf(" %15s |", pBuf);
          } break;
          default:
            break;
L
Liu Jicong 已提交
1931 1932 1933 1934 1935
        }
      }
      printf("\n");
    }
  }
5
54liuyao 已提交
1936 1937 1938 1939 1940 1941
}

// for debug
char* dumpBlockData(SSDataBlock* pDataBlock, const char* flag, char** pDataBuf) {
  int32_t size = 2048;
  *pDataBuf = taosMemoryCalloc(size, 1);
1942 1943
  char*   dumpBuf = *pDataBuf;
  char    pBuf[128] = {0};
5
54liuyao 已提交
1944 1945 1946
  int32_t colNum = taosArrayGetSize(pDataBlock->pDataBlock);
  int32_t rows = pDataBlock->info.rows;
  int32_t len = 0;
S
Shengliang Guan 已提交
1947 1948
  len += snprintf(dumpBuf + len, size - len,
                  "===stream===%s|block type %d|child id %d|group id:%" PRIu64 "|uid:%" PRId64
5
54liuyao 已提交
1949
                  "|rows:%d|version:%" PRIu64 "|cal start:%" PRIu64 "|cal end:%" PRIu64 "\n",
H
Haojun Liao 已提交
1950
                  flag, (int32_t)pDataBlock->info.type, pDataBlock->info.childId, pDataBlock->info.id.groupId,
5
54liuyao 已提交
1951
                  pDataBlock->info.id.uid, pDataBlock->info.rows, pDataBlock->info.version, pDataBlock->info.calWin.skey, pDataBlock->info.calWin.ekey);
S
Shengliang Guan 已提交
1952
  if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1953

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

5
54liuyao 已提交
1958 1959
    for (int32_t k = 0; k < colNum; k++) {
      SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, k);
5
54liuyao 已提交
1960
      if (colDataIsNull(pColInfoData, rows, j, NULL) || !pColInfoData->pData) {
5
54liuyao 已提交
1961
        len += snprintf(dumpBuf + len, size - len, " %15s |", "NULL");
L
Liu Jicong 已提交
1962
        if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1963 1964
        continue;
      }
5
54liuyao 已提交
1965 1966

      void* var = colDataGetData(pColInfoData, j);
5
54liuyao 已提交
1967 1968
      switch (pColInfoData->info.type) {
        case TSDB_DATA_TYPE_TIMESTAMP:
5
54liuyao 已提交
1969
          memset(pBuf, 0, sizeof(pBuf));
5
54liuyao 已提交
1970 1971
          formatTimestamp(pBuf, *(uint64_t*)var, TSDB_TIME_PRECISION_MILLI);
          len += snprintf(dumpBuf + len, size - len, " %25s |", pBuf);
L
Liu Jicong 已提交
1972
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1973
          break;
1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
        case TSDB_DATA_TYPE_TINYINT:
          len += snprintf(dumpBuf + len, size - len, " %15d |", *(int8_t*)var);
          if (len >= size - 1) return dumpBuf;
          break;
        case TSDB_DATA_TYPE_UTINYINT:
          len += snprintf(dumpBuf + len, size - len, " %15d |", *(uint8_t*)var);
          if (len >= size - 1) return dumpBuf;
          break;
        case TSDB_DATA_TYPE_SMALLINT:
          len += snprintf(dumpBuf + len, size - len, " %15d |", *(int16_t*)var);
          if (len >= size - 1) return dumpBuf;
          break;
        case TSDB_DATA_TYPE_USMALLINT:
          len += snprintf(dumpBuf + len, size - len, " %15d |", *(uint16_t*)var);
          if (len >= size - 1) return dumpBuf;
          break;
5
54liuyao 已提交
1990 1991
        case TSDB_DATA_TYPE_INT:
          len += snprintf(dumpBuf + len, size - len, " %15d |", *(int32_t*)var);
L
Liu Jicong 已提交
1992
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1993 1994 1995
          break;
        case TSDB_DATA_TYPE_UINT:
          len += snprintf(dumpBuf + len, size - len, " %15u |", *(uint32_t*)var);
L
Liu Jicong 已提交
1996
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1997 1998
          break;
        case TSDB_DATA_TYPE_BIGINT:
1999
          len += snprintf(dumpBuf + len, size - len, " %15" PRId64 " |", *(int64_t*)var);
L
Liu Jicong 已提交
2000
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2001 2002
          break;
        case TSDB_DATA_TYPE_UBIGINT:
2003
          len += snprintf(dumpBuf + len, size - len, " %15" PRIu64 " |", *(uint64_t*)var);
L
Liu Jicong 已提交
2004
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2005 2006 2007
          break;
        case TSDB_DATA_TYPE_FLOAT:
          len += snprintf(dumpBuf + len, size - len, " %15f |", *(float*)var);
L
Liu Jicong 已提交
2008
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2009 2010
          break;
        case TSDB_DATA_TYPE_DOUBLE:
5
54liuyao 已提交
2011 2012
          // len += snprintf(dumpBuf + len, size - len, " %15lf |", *(double*)var);
          // if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2013
          break;
5
54liuyao 已提交
2014 2015 2016 2017
        case TSDB_DATA_TYPE_BOOL:
          len += snprintf(dumpBuf + len, size - len, " %15d |", *(bool*)var);
          if (len >= size - 1) return dumpBuf;
          break;
5
54liuyao 已提交
2018
        case TSDB_DATA_TYPE_VARCHAR: {
5
54liuyao 已提交
2019
          memset(pBuf, 0, sizeof(pBuf));
L
Liu Jicong 已提交
2020
          char*   pData = colDataGetVarData(pColInfoData, j);
5
54liuyao 已提交
2021
          int32_t dataSize = TMIN(sizeof(pBuf), varDataLen(pData));
5
54liuyao 已提交
2022
          dataSize = TMIN(dataSize, 50);
5
54liuyao 已提交
2023
          memcpy(pBuf, varDataVal(pData), dataSize);
5
54liuyao 已提交
2024 2025
          len += snprintf(dumpBuf + len, size - len, " %15s |", pBuf);
          if (len >= size - 1) return dumpBuf;
L
Liu Jicong 已提交
2026
        } break;
5
54liuyao 已提交
2027
        case TSDB_DATA_TYPE_NCHAR: {
L
Liu Jicong 已提交
2028
          char*   pData = colDataGetVarData(pColInfoData, j);
5
54liuyao 已提交
2029 2030
          int32_t dataSize = TMIN(sizeof(pBuf), varDataLen(pData));
          memset(pBuf, 0, sizeof(pBuf));
C
Cary Xu 已提交
2031
          (void)taosUcs4ToMbs((TdUcs4*)varDataVal(pData), dataSize, pBuf);
5
54liuyao 已提交
2032 2033
          len += snprintf(dumpBuf + len, size - len, " %15s |", pBuf);
          if (len >= size - 1) return dumpBuf;
L
Liu Jicong 已提交
2034
        } break;
5
54liuyao 已提交
2035 2036 2037
      }
    }
    len += snprintf(dumpBuf + len, size - len, "\n");
L
Liu Jicong 已提交
2038
    if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2039 2040 2041
  }
  len += snprintf(dumpBuf + len, size - len, "%s |end\n", flag);
  return dumpBuf;
L
Liu Jicong 已提交
2042 2043
}

C
Cary Xu 已提交
2044 2045 2046 2047
/**
 * @brief TODO: Assume that the final generated result it less than 3M
 *
 * @param pReq
C
Cary Xu 已提交
2048
 * @param pDataBlocks
C
Cary Xu 已提交
2049
 * @param vgId
C
Cary Xu 已提交
2050
 * @param suid
L
Liu Jicong 已提交
2051
 *
C
Cary Xu 已提交
2052
 */
C
Cary Xu 已提交
2053
int32_t buildSubmitReqFromDataBlock(SSubmitReq** pReq, const SSDataBlock* pDataBlock, STSchema* pTSchema, int32_t vgId,
2054
                                    tb_uid_t suid) {
C
Cary Xu 已提交
2055
  int32_t bufSize = sizeof(SSubmitReq);
C
Cary Xu 已提交
2056
  int32_t sz = 1;
C
Cary Xu 已提交
2057
  for (int32_t i = 0; i < sz; ++i) {
C
Cary Xu 已提交
2058
    const SDataBlockInfo* pBlkInfo = &pDataBlock->info;
2059

C
Cary Xu 已提交
2060 2061
    int32_t colNum = taosArrayGetSize(pDataBlock->pDataBlock);
    bufSize += pBlkInfo->rows * (TD_ROW_HEAD_LEN + pBlkInfo->rowSize + BitmapLen(colNum));
C
Cary Xu 已提交
2062 2063 2064 2065
    bufSize += sizeof(SSubmitBlk);
  }

  *pReq = taosMemoryCalloc(1, bufSize);
2066
  if (!(*pReq)) {
C
Cary Xu 已提交
2067 2068 2069
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return TSDB_CODE_FAILED;
  }
C
Cary Xu 已提交
2070 2071
  void* pDataBuf = *pReq;

2072
  int32_t     msgLen = sizeof(SSubmitReq);
C
Cary Xu 已提交
2073 2074
  int32_t     numOfBlks = 0;
  SRowBuilder rb = {0};
C
Cary Xu 已提交
2075
  tdSRowInit(&rb, pTSchema->version);
C
Cary Xu 已提交
2076 2077

  for (int32_t i = 0; i < sz; ++i) {
L
Liu Jicong 已提交
2078 2079
    int32_t colNum = taosArrayGetSize(pDataBlock->pDataBlock);
    int32_t rows = pDataBlock->info.rows;
2080

2081 2082 2083 2084 2085
    if (colNum <= 1) {
      // invalid if only with TS col
      continue;
    }

2086
    if (rb.nCols != colNum) {
C
Cary Xu 已提交
2087 2088 2089 2090 2091
      tdSRowSetTpInfo(&rb, colNum, pTSchema->flen);
    }

    SSubmitBlk* pSubmitBlk = POINTER_SHIFT(pDataBuf, msgLen);
    pSubmitBlk->suid = suid;
H
Haojun Liao 已提交
2092
    pSubmitBlk->uid = pDataBlock->info.id.groupId;
C
Cary Xu 已提交
2093
    pSubmitBlk->numOfRows = rows;
C
Cary Xu 已提交
2094
    pSubmitBlk->sversion = pTSchema->version;
C
Cary Xu 已提交
2095 2096 2097

    msgLen += sizeof(SSubmitBlk);
    int32_t dataLen = 0;
L
Liu Jicong 已提交
2098
    for (int32_t j = 0; j < rows; ++j) {                               // iterate by row
C
Cary Xu 已提交
2099
      tdSRowResetBuf(&rb, POINTER_SHIFT(pDataBuf, msgLen + dataLen));  // set row buf
2100
      bool    isStartKey = false;
2101
      int32_t offset = 0;
C
Cary Xu 已提交
2102 2103
      for (int32_t k = 0; k < colNum; ++k) {  // iterate by column
        SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, k);
2104 2105
        STColumn*        pCol = &pTSchema->columns[k];
        void*            var = POINTER_SHIFT(pColInfoData->pData, j * pColInfoData->info.bytes);
C
Cary Xu 已提交
2106 2107 2108 2109
        switch (pColInfoData->info.type) {
          case TSDB_DATA_TYPE_TIMESTAMP:
            if (!isStartKey) {
              isStartKey = true;
2110
              tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID, TSDB_DATA_TYPE_TIMESTAMP, TD_VTYPE_NORM, var, true,
2111
                                  offset, k);
2112
              continue; // offset should keep 0 for next column
2113

2114 2115 2116
            } else if (colDataIsNull_s(pColInfoData, j)) {
              tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, TSDB_DATA_TYPE_TIMESTAMP, TD_VTYPE_NULL, NULL,
                                  false, offset, k);
C
Cary Xu 已提交
2117
            } else {
2118 2119
              tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, TSDB_DATA_TYPE_TIMESTAMP, TD_VTYPE_NORM, var,
                                  true, offset, k);
C
Cary Xu 已提交
2120 2121
            }
            break;
2122
          case TSDB_DATA_TYPE_NCHAR:
C
Cary Xu 已提交
2123
          case TSDB_DATA_TYPE_VARCHAR: {  // TSDB_DATA_TYPE_BINARY
2124 2125 2126 2127 2128 2129 2130 2131
            if (colDataIsNull_s(pColInfoData, j)) {
              tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, pColInfoData->info.type, TD_VTYPE_NULL, NULL,
                                  false, offset, k);
            } else {
              void* data = colDataGetData(pColInfoData, j);
              tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, pColInfoData->info.type, TD_VTYPE_NORM, data,
                                  true, offset, k);
            }
C
Cary Xu 已提交
2132 2133 2134 2135 2136
            break;
          }
          case TSDB_DATA_TYPE_VARBINARY:
          case TSDB_DATA_TYPE_DECIMAL:
          case TSDB_DATA_TYPE_BLOB:
2137
          case TSDB_DATA_TYPE_JSON:
C
Cary Xu 已提交
2138
          case TSDB_DATA_TYPE_MEDIUMBLOB:
C
Cary Xu 已提交
2139
            uError("the column type %" PRIi16 " is defined but not implemented yet", pColInfoData->info.type);
C
Cary Xu 已提交
2140
            ASSERT(0);
C
Cary Xu 已提交
2141 2142 2143
            break;
          default:
            if (pColInfoData->info.type < TSDB_DATA_TYPE_MAX && pColInfoData->info.type > TSDB_DATA_TYPE_NULL) {
2144
              if (colDataIsNull_s(pColInfoData, j)) {
L
Liu Jicong 已提交
2145 2146
                tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, pCol->type, TD_VTYPE_NULL, NULL, false,
                                    offset, k);
2147
              } else if (pCol->type == pColInfoData->info.type) {
C
Cary Xu 已提交
2148 2149
                tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, pCol->type, TD_VTYPE_NORM, var, true, offset,
                                    k);
2150
              } else {
C
Cary Xu 已提交
2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
                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);
2171
              }
C
Cary Xu 已提交
2172
            } else {
C
Cary Xu 已提交
2173
              uError("the column type %" PRIi16 " is undefined\n", pColInfoData->info.type);
C
Cary Xu 已提交
2174
              ASSERT(0);
C
Cary Xu 已提交
2175 2176 2177
            }
            break;
        }
2178
        offset += TYPE_BYTES[pCol->type];  // sum/avg would convert to int64_t/uint64_t/double during aggregation
C
Cary Xu 已提交
2179
      }
2180
      tdSRowEnd(&rb);
C
Cary Xu 已提交
2181
      dataLen += TD_ROW_LEN(rb.pBuf);
C
Cary Xu 已提交
2182 2183 2184
#ifdef TD_DEBUG_PRINT_ROW
      tdSRowPrint(rb.pBuf, pTSchema, __func__);
#endif
C
Cary Xu 已提交
2185
    }
C
Cary Xu 已提交
2186 2187 2188

    ++numOfBlks;

C
Cary Xu 已提交
2189 2190 2191 2192
    pSubmitBlk->dataLen = dataLen;
    msgLen += pSubmitBlk->dataLen;
  }

2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
  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->sversion = htonl(blk->sversion);
      blk->dataLen = htonl(blk->dataLen);
      blk->schemaLen = htonl(blk->schemaLen);
2208
      blk->numOfRows = htonl(blk->numOfRows);
2209 2210 2211 2212 2213
      blk = (SSubmitBlk*)(blk->data + dataLen);
    }
  } else {
    // no valid rows
    taosMemoryFreeClear(*pReq);
C
Cary Xu 已提交
2214
  }
C
Cary Xu 已提交
2215 2216

  return TSDB_CODE_SUCCESS;
C
Cary Xu 已提交
2217
}
L
Liu Jicong 已提交
2218

L
Liu Jicong 已提交
2219 2220
char* buildCtbNameByGroupId(const char* stbFullName, uint64_t groupId) {
  ASSERT(stbFullName[0] != 0);
2221
  SArray* tags = taosArrayInit(0, sizeof(void*));
L
Liu Jicong 已提交
2222 2223 2224 2225
  if (tags == NULL) {
    return NULL;
  }

2226
  SSmlKv* pTag = taosMemoryCalloc(1, sizeof(SSmlKv));
L
Liu Jicong 已提交
2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
  if (pTag == NULL) {
    taosArrayDestroy(tags);
    return NULL;
  }

  void* cname = taosMemoryCalloc(1, TSDB_TABLE_NAME_LEN + 1);
  if (cname == NULL) {
    taosArrayDestroy(tags);
    taosMemoryFree(pTag);
    return NULL;
  }

2239 2240 2241 2242
  pTag->key = "group_id";
  pTag->keyLen = strlen(pTag->key);
  pTag->type = TSDB_DATA_TYPE_UBIGINT;
  pTag->u = groupId;
L
Liu Jicong 已提交
2243
  pTag->length = sizeof(uint64_t);
2244 2245 2246 2247
  taosArrayPush(tags, &pTag);

  RandTableName rname = {
      .tags = tags,
L
Liu Jicong 已提交
2248 2249 2250
      .stbFullName = stbFullName,
      .stbFullNameLen = strlen(stbFullName),
      .ctbShortName = cname,
2251 2252 2253 2254 2255 2256 2257
  };

  buildChildTableName(&rname);

  taosMemoryFree(pTag);
  taosArrayDestroy(tags);

L
Liu Jicong 已提交
2258 2259
  ASSERT(rname.ctbShortName && rname.ctbShortName[0]);
  return rname.ctbShortName;
2260 2261
}

H
Haojun Liao 已提交
2262 2263 2264
int32_t blockEncode(const SSDataBlock* pBlock, char* data, int32_t numOfCols) {
  int32_t dataLen = 0;

2265
  // todo extract method
2266 2267 2268 2269
  int32_t* version = (int32_t*)data;
  *version = 1;
  data += sizeof(int32_t);

2270 2271 2272
  int32_t* actualLen = (int32_t*)data;
  data += sizeof(int32_t);

2273 2274 2275
  int32_t* rows = (int32_t*)data;
  *rows = pBlock->info.rows;
  data += sizeof(int32_t);
H
Haojun Liao 已提交
2276
  ASSERT(*rows > 0);
2277 2278 2279 2280 2281

  int32_t* cols = (int32_t*)data;
  *cols = numOfCols;
  data += sizeof(int32_t);

2282 2283 2284
  // flag segment.
  // the inital bit is for column info
  int32_t* flagSegment = (int32_t*)data;
L
Liu Jicong 已提交
2285
  *flagSegment = (1 << 31);
2286

2287 2288
  data += sizeof(int32_t);

2289 2290 2291
  uint64_t* groupId = (uint64_t*)data;
  data += sizeof(uint64_t);

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

2295 2296
    *((int8_t*)data) = pColInfoData->info.type;
    data += sizeof(int8_t);
2297

L
Liu Jicong 已提交
2298
    *((int32_t*)data) = pColInfoData->info.bytes;
2299 2300 2301
    data += sizeof(int32_t);
  }

2302 2303 2304
  int32_t* colSizes = (int32_t*)data;
  data += numOfCols * sizeof(int32_t);

H
Haojun Liao 已提交
2305
  dataLen = blockDataGetSerialMetaSize(numOfCols);
2306 2307 2308 2309 2310 2311

  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
2312
    size_t metaSize = 0;
2313
    if (IS_VAR_DATA_TYPE(pColRes->info.type)) {
2314
      metaSize = numOfRows * sizeof(int32_t);
2315 2316
      memcpy(data, pColRes->varmeta.offset, metaSize);
    } else {
2317 2318
      metaSize = BitmapLen(numOfRows);
      memcpy(data, pColRes->nullbitmap, metaSize);
2319 2320
    }

2321
    data += metaSize;
H
Haojun Liao 已提交
2322
    dataLen += metaSize;
2323

H
Haojun Liao 已提交
2324 2325
    colSizes[col] = colDataGetLength(pColRes, numOfRows);
    dataLen += colSizes[col];
2326 2327 2328
    if (pColRes->pData != NULL) {
      memmove(data, pColRes->pData, colSizes[col]);
    }
H
Haojun Liao 已提交
2329
    data += colSizes[col];
2330 2331 2332 2333

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

H
Haojun Liao 已提交
2334
  *actualLen = dataLen;
H
Haojun Liao 已提交
2335
  *groupId = pBlock->info.id.groupId;
H
Haojun Liao 已提交
2336 2337 2338 2339 2340
  ASSERT(dataLen > 0);

  uDebug("build data block, actualLen:%d, rows:%d, cols:%d", dataLen, *rows, *cols);

  return dataLen;
2341 2342
}

2343
const char* blockDecode(SSDataBlock* pBlock, const char* pData) {
2344 2345
  const char* pStart = pData;

L
Liu Jicong 已提交
2346
  int32_t version = *(int32_t*)pStart;
2347 2348 2349
  pStart += sizeof(int32_t);
  ASSERT(version == 1);

2350
  // total length sizeof(int32_t)
2351 2352 2353
  int32_t dataLen = *(int32_t*)pStart;
  pStart += sizeof(int32_t);

2354
  // total rows sizeof(int32_t)
L
Liu Jicong 已提交
2355
  int32_t numOfRows = *(int32_t*)pStart;
2356 2357 2358 2359 2360 2361 2362
  pStart += sizeof(int32_t);

  // total columns sizeof(int32_t)
  int32_t numOfCols = *(int32_t*)pStart;
  pStart += sizeof(int32_t);

  // has column info segment
2363 2364
  int32_t flagSeg = *(int32_t*)pStart;
  int32_t hasColumnInfo = (flagSeg >> 31);
2365 2366 2367
  pStart += sizeof(int32_t);

  // group id sizeof(uint64_t)
H
Haojun Liao 已提交
2368
  pBlock->info.id.groupId = *(uint64_t*)pStart;
2369 2370
  pStart += sizeof(uint64_t);

2371 2372 2373 2374 2375
  if (pBlock->pDataBlock == NULL) {
    pBlock->pDataBlock = taosArrayInit(numOfCols, sizeof(SColumnInfoData));
    taosArraySetSize(pBlock->pDataBlock, numOfCols);
  }

L
Liu Jicong 已提交
2376
  for (int32_t i = 0; i < numOfCols; ++i) {
2377
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
麦壳饼's avatar
麦壳饼 已提交
2378
    pColInfoData->info.type = *(int8_t*)pStart;
2379
    pStart += sizeof(int8_t);
2380 2381 2382

    pColInfoData->info.bytes = *(int32_t*)pStart;
    pStart += sizeof(int32_t);
2383 2384 2385 2386

    if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
      pBlock->info.hasVarCol = true;
    }
2387 2388 2389 2390
  }

  blockDataEnsureCapacity(pBlock, numOfRows);

2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402
  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;

2403 2404 2405 2406 2407 2408 2409 2410
      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];
2411
      }
2412 2413

      pColInfoData->varmeta.length = colLen[i];
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429
    } 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];
  }

2430
  pBlock->info.rows = numOfRows;
2431 2432
  ASSERT(pStart - pData == dataLen);
  return pStart;
L
Liu Jicong 已提交
2433
}