tdatablock.c 75.1 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 32
23

24
int32_t colDataGetLength(const SColumnInfoData* pColumnInfoData, int32_t numOfRows) {
H
Haojun Liao 已提交
25
  if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
D
dapan1121 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39
    if (pColumnInfoData->reassigned) {
      int32_t totalSize = 0;
      for (int32_t row = 0; row < numOfRows; ++row) {
        char* pColData = pColumnInfoData->pData + pColumnInfoData->varmeta.offset[row];
        int32_t colSize = 0;
        if (pColumnInfoData->info.type == TSDB_DATA_TYPE_JSON) {
          colSize = getJsonValueLen(pColData);
        } else {
          colSize = varDataTLen(pColData);
        }
        totalSize += colSize;
      }
      return totalSize;
    }
H
Haojun Liao 已提交
40 41
    return pColumnInfoData->varmeta.length;
  } else {
42 43 44 45 46
    if (pColumnInfoData->info.type == TSDB_DATA_TYPE_NULL) {
      return 0;
    } else {
      return pColumnInfoData->info.bytes * numOfRows;
    }
H
Haojun Liao 已提交
47 48 49
  }
}

50 51 52 53 54 55 56 57 58 59
int32_t colDataGetRowLength(const SColumnInfoData* pColumnInfoData, int32_t rowIdx) {
  if (colDataIsNull_s(pColumnInfoData, rowIdx)) return 0;

  if (!IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) return pColumnInfoData->info.bytes;
  if (pColumnInfoData->info.type == TSDB_DATA_TYPE_JSON)
    return getJsonValueLen(colDataGetData(pColumnInfoData, rowIdx));
  else
    return varDataTLen(colDataGetData(pColumnInfoData, rowIdx));
}

H
Haojun Liao 已提交
60 61 62 63
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 {
64 65
    return ((pColumnInfoData->info.type == TSDB_DATA_TYPE_NULL) ? 0 : pColumnInfoData->info.bytes * numOfRows) +
           BitmapLen(numOfRows);
H
Haojun Liao 已提交
66 67 68
  }
}

69
int32_t getJsonValueLen(const char* data) {
wmmhello's avatar
wmmhello 已提交
70 71 72 73 74 75 76 77 78
  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 已提交
79
  } else if (tTagIsJson(data)) {  // json string
wmmhello's avatar
wmmhello 已提交
80 81 82 83 84 85 86
    dataLen = ((STag*)(data))->len;
  } else {
    ASSERT(0);
  }
  return dataLen;
}

87
int32_t colDataSetVal(SColumnInfoData* pColumnInfoData, uint32_t rowIndex, const char* pData, bool isNull) {
88
  if (isNull) {
H
Haojun Liao 已提交
89 90
    // There is a placehold for each NULL value of binary or nchar type.
    if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
91
      pColumnInfoData->varmeta.offset[rowIndex] = -1;  // it is a null value of VAR type.
H
Haojun Liao 已提交
92
    } else {
93
      colDataSetNull_f_s(pColumnInfoData, rowIndex);
H
Haojun Liao 已提交
94 95
    }

H
Haojun Liao 已提交
96
    pColumnInfoData->hasNull = true;
97 98 99 100 101
    return 0;
  }

  int32_t type = pColumnInfoData->info.type;
  if (IS_VAR_DATA_TYPE(type)) {
wmmhello's avatar
wmmhello 已提交
102
    int32_t dataLen = 0;
103
    if (type == TSDB_DATA_TYPE_JSON) {
wmmhello's avatar
wmmhello 已提交
104
      dataLen = getJsonValueLen(pData);
105
    } else {
wmmhello's avatar
wmmhello 已提交
106
      dataLen = varDataTLen(pData);
107
    }
108

H
Haojun Liao 已提交
109
    SVarColAttr* pAttr = &pColumnInfoData->varmeta;
110
    if (pAttr->allocLen < pAttr->length + dataLen) {
H
Haojun Liao 已提交
111
      uint32_t newSize = pAttr->allocLen;
112
      if (newSize <= 1) {
H
Haojun Liao 已提交
113 114 115
        newSize = 8;
      }

116
      while (newSize < pAttr->length + dataLen) {
H
Haojun Liao 已提交
117
        newSize = newSize * 1.5;
118 119 120
        if (newSize > UINT32_MAX) {
          return TSDB_CODE_OUT_OF_MEMORY;
        }
H
Haojun Liao 已提交
121 122
      }

wafwerar's avatar
wafwerar 已提交
123
      char* buf = taosMemoryRealloc(pColumnInfoData->pData, newSize);
H
Haojun Liao 已提交
124
      if (buf == NULL) {
H
Haojun Liao 已提交
125
        return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
126 127 128 129 130 131 132
      }

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

    uint32_t len = pColumnInfoData->varmeta.length;
133
    pColumnInfoData->varmeta.offset[rowIndex] = len;
H
Haojun Liao 已提交
134

H
Haojun Liao 已提交
135
    memmove(pColumnInfoData->pData + len, pData, dataLen);
136
    pColumnInfoData->varmeta.length += dataLen;
137
  } else {
138
    memcpy(pColumnInfoData->pData + pColumnInfoData->info.bytes * rowIndex, pData, pColumnInfoData->info.bytes);
139
    colDataClearNull_f(pColumnInfoData->nullbitmap, rowIndex);
140 141 142 143 144
  }

  return 0;
}

D
dapan1121 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157
int32_t colDataReassignVal(SColumnInfoData* pColumnInfoData, uint32_t dstRowIdx, uint32_t srcRowIdx, const char* pData) {
  int32_t type = pColumnInfoData->info.type;
  if (IS_VAR_DATA_TYPE(type)) {
    int32_t dataLen = 0;
    if (type == TSDB_DATA_TYPE_JSON) {
      dataLen = getJsonValueLen(pData);
    } else {
      dataLen = varDataTLen(pData);
    }

    SVarColAttr* pAttr = &pColumnInfoData->varmeta;

    pColumnInfoData->varmeta.offset[dstRowIdx] = pColumnInfoData->varmeta.offset[srcRowIdx];
D
dapan1121 已提交
158
    pColumnInfoData->reassigned = true;
D
dapan1121 已提交
159 160 161 162 163 164 165 166 167
  } else {
    memcpy(pColumnInfoData->pData + pColumnInfoData->info.bytes * dstRowIdx, pData, pColumnInfoData->info.bytes);
    colDataClearNull_f(pColumnInfoData->nullbitmap, dstRowIdx);
  }

  return 0;
}


168
static int32_t colDataReserve(SColumnInfoData* pColumnInfoData, size_t newSize) {
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
  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;
}

D
dapan1121 已提交
190 191 192 193 194 195 196 197 198 199 200
static int32_t doCopyNItems(struct SColumnInfoData* pColumnInfoData, int32_t currentRow, const char* pData,
                         int32_t itemLen, int32_t numOfRows, bool trimValue) {
  if (pColumnInfoData->info.bytes < itemLen) {
    uWarn("column/tag actual data len %d is bigger than schema len %d, trim it:%d", itemLen, pColumnInfoData->info.bytes, trimValue);
    if (trimValue) {
      itemLen = pColumnInfoData->info.bytes;
    } else {
      return TSDB_CODE_TDB_INVALID_TABLE_SCHEMA_VER;
    }
  }
  
H
Haojun Liao 已提交
201 202 203 204 205 206
  size_t start = 1;

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

  int32_t t = 0;
L
Liu Jicong 已提交
207 208
  int32_t count = log(numOfRows) / log(2);
  while (t < count) {
H
Haojun Liao 已提交
209
    int32_t xlen = 1 << t;
L
Liu Jicong 已提交
210 211
    memcpy(pColumnInfoData->pData + start * itemLen + pColumnInfoData->varmeta.length, pColumnInfoData->pData,
           xlen * itemLen);
H
Haojun Liao 已提交
212 213 214 215 216 217
    t += 1;
    start += xlen;
  }

  // the tail part
  if (numOfRows > start) {
L
Liu Jicong 已提交
218 219
    memcpy(pColumnInfoData->pData + start * itemLen + currentRow * itemLen, pColumnInfoData->pData,
           (numOfRows - start) * itemLen);
H
Haojun Liao 已提交
220 221 222
  }

  if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
L
Liu Jicong 已提交
223
    for (int32_t i = 0; i < numOfRows; ++i) {
H
Haojun Liao 已提交
224 225 226 227 228
      pColumnInfoData->varmeta.offset[i + currentRow] = pColumnInfoData->varmeta.length + i * itemLen;
    }

    pColumnInfoData->varmeta.length += numOfRows * itemLen;
  }
D
dapan1121 已提交
229 230

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
231 232
}

233
int32_t colDataSetNItems(SColumnInfoData* pColumnInfoData, uint32_t currentRow, const char* pData,
D
dapan1121 已提交
234
                            uint32_t numOfRows, bool trimValue) {
H
Haojun Liao 已提交
235 236 237 238 239 240 241 242 243 244 245
  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;
      }
    }
  }

D
dapan1121 已提交
246
  return doCopyNItems(pColumnInfoData, currentRow, pData, len, numOfRows, trimValue);
H
Haojun Liao 已提交
247 248
}

L
Liu Jicong 已提交
249 250
static void doBitmapMerge(SColumnInfoData* pColumnInfoData, int32_t numOfRow1, const SColumnInfoData* pSource,
                          int32_t numOfRow2) {
wmmhello's avatar
wmmhello 已提交
251 252
  if (numOfRow2 <= 0) return;

H
Haojun Liao 已提交
253 254 255 256 257 258 259
  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 已提交
260 261
    return;
  }
H
Haojun Liao 已提交
262

wmmhello's avatar
wmmhello 已提交
263
  uint8_t* p = (uint8_t*)pSource->nullbitmap;
264
  pColumnInfoData->nullbitmap[BitmapLen(numOfRow1) - 1] &= (0B11111111 << shiftBits);  // clear remind bits
wmmhello's avatar
wmmhello 已提交
265
  pColumnInfoData->nullbitmap[BitmapLen(numOfRow1) - 1] |= (p[0] >> remindBits);  // copy remind bits
H
Haojun Liao 已提交
266

wmmhello's avatar
wmmhello 已提交
267 268 269
  if (BitmapLen(numOfRow1) == BitmapLen(total)) {
    return;
  }
H
Haojun Liao 已提交
270

wmmhello's avatar
wmmhello 已提交
271 272
  int32_t len = BitmapLen(numOfRow2);
  int32_t i = 0;
H
Haojun Liao 已提交
273

wmmhello's avatar
wmmhello 已提交
274
  uint8_t* start = (uint8_t*)&pColumnInfoData->nullbitmap[BitmapLen(numOfRow1)];
C
Cary Xu 已提交
275
  int32_t  overCount = BitmapLen(total) - BitmapLen(numOfRow1);
276
  memset(start, 0, overCount);
C
Cary Xu 已提交
277
  while (i < len) {  // size limit of pSource->nullbitmap
wmmhello's avatar
wmmhello 已提交
278
    if (i >= 1) {
C
Cary Xu 已提交
279
      start[i - 1] |= (p[i] >> remindBits);  // copy remind bits
H
Haojun Liao 已提交
280
    }
wmmhello's avatar
wmmhello 已提交
281

C
Cary Xu 已提交
282
    if (i >= overCount) {  // size limit of pColumnInfoData->nullbitmap
wmmhello's avatar
wmmhello 已提交
283 284 285
      return;
    }

C
Cary Xu 已提交
286
    start[i] |= (p[i] << shiftBits);  // copy shift bits
wmmhello's avatar
wmmhello 已提交
287
    i += 1;
H
Haojun Liao 已提交
288 289 290
  }
}

H
Haojun Liao 已提交
291 292
int32_t colDataMergeCol(SColumnInfoData* pColumnInfoData, int32_t numOfRow1, int32_t* capacity,
                        const SColumnInfoData* pSource, int32_t numOfRow2) {
G
Ganlin Zhao 已提交
293 294 295 296
  if (pColumnInfoData->info.type != pSource->info.type) {
    return TSDB_CODE_FAILED;
  }

H
Haojun Liao 已提交
297 298 299 300
  if (numOfRow2 == 0) {
    return numOfRow1;
  }

wmmhello's avatar
wmmhello 已提交
301 302 303
  if (pSource->hasNull) {
    pColumnInfoData->hasNull = pSource->hasNull;
  }
304

305
  uint32_t finalNumOfRows = numOfRow1 + numOfRow2;
H
Haojun Liao 已提交
306 307
  if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
    // Handle the bitmap
308
    if (finalNumOfRows > (*capacity)) {
309 310 311 312 313 314 315
      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 已提交
316 317
    }

L
Liu Jicong 已提交
318
    for (int32_t i = 0; i < numOfRow2; ++i) {
319 320 321 322 323
      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;
      }
324
    }
H
Haojun Liao 已提交
325

326
    // copy data
H
Haojun Liao 已提交
327 328 329
    uint32_t len = pSource->varmeta.length;
    uint32_t oldLen = pColumnInfoData->varmeta.length;
    if (pColumnInfoData->varmeta.allocLen < len + oldLen) {
wafwerar's avatar
wafwerar 已提交
330
      char* tmp = taosMemoryRealloc(pColumnInfoData->pData, len + oldLen);
H
Haojun Liao 已提交
331
      if (tmp == NULL) {
332
        return TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
333 334 335 336 337 338
      }

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

339
    if (pColumnInfoData->pData && pSource->pData) {  // TD-20382
340 341
      memcpy(pColumnInfoData->pData + oldLen, pSource->pData, len);
    }
342
    pColumnInfoData->varmeta.length = len + oldLen;
H
Haojun Liao 已提交
343
  } else {
344
    if (finalNumOfRows > (*capacity)) {
H
Haojun Liao 已提交
345
      // all data may be null, when the pColumnInfoData->info.type == 0, bytes == 0;
346
      char* tmp = taosMemoryRealloc(pColumnInfoData->pData, finalNumOfRows * pColumnInfoData->info.bytes);
347
      if (tmp == NULL) {
348
        return TSDB_CODE_OUT_OF_MEMORY;
349
      }
H
Haojun Liao 已提交
350

351 352 353
      pColumnInfoData->pData = tmp;
      if (BitmapLen(numOfRow1) < BitmapLen(finalNumOfRows)) {
        char*    btmp = taosMemoryRealloc(pColumnInfoData->nullbitmap, BitmapLen(finalNumOfRows));
354 355 356
        if (btmp == NULL) {
          return TSDB_CODE_OUT_OF_MEMORY;
        }
357 358 359 360 361 362
        uint32_t extend = BitmapLen(finalNumOfRows) - BitmapLen(numOfRow1);
        memset(btmp + BitmapLen(numOfRow1), 0, extend);
        pColumnInfoData->nullbitmap = btmp;
      }

      *capacity = finalNumOfRows;
H
Haojun Liao 已提交
363 364
    }

365 366
    doBitmapMerge(pColumnInfoData, numOfRow1, pSource, numOfRow2);

X
Xiaoyu Wang 已提交
367 368 369 370
    if (pSource->pData) {
      int32_t offset = pColumnInfoData->info.bytes * numOfRow1;
      memcpy(pColumnInfoData->pData + offset, pSource->pData, pSource->info.bytes * numOfRow2);
    }
H
Haojun Liao 已提交
371 372 373 374 375
  }

  return numOfRow1 + numOfRow2;
}

L
Liu Jicong 已提交
376 377
int32_t colDataAssign(SColumnInfoData* pColumnInfoData, const SColumnInfoData* pSource, int32_t numOfRows,
                      const SDataBlockInfo* pBlockInfo) {
X
Xiaoyu Wang 已提交
378
  if (pColumnInfoData->info.type != pSource->info.type || (pBlockInfo != NULL && pBlockInfo->capacity < numOfRows)) {
G
Ganlin Zhao 已提交
379
    return TSDB_CODE_FAILED;
380 381
  }

G
Ganlin Zhao 已提交
382 383
  if (numOfRows <= 0) {
    return numOfRows;
384
  }
385

386 387
  if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
    memcpy(pColumnInfoData->varmeta.offset, pSource->varmeta.offset, sizeof(int32_t) * numOfRows);
388 389 390 391 392 393 394 395 396
    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;
    }
397 398

    pColumnInfoData->varmeta.length = pSource->varmeta.length;
399 400 401
    if (pColumnInfoData->pData != NULL && pSource->pData != NULL) {
      memcpy(pColumnInfoData->pData, pSource->pData, pSource->varmeta.length);
    }
402 403
  } else {
    memcpy(pColumnInfoData->nullbitmap, pSource->nullbitmap, BitmapLen(numOfRows));
404
    if (pSource->pData != NULL) {
D
dapan1121 已提交
405 406
      memcpy(pColumnInfoData->pData, pSource->pData, pSource->info.bytes * numOfRows);
    }
407 408
  }

409 410
  pColumnInfoData->hasNull = pSource->hasNull;
  pColumnInfoData->info = pSource->info;
411 412 413
  return 0;
}

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

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

418
int32_t blockDataUpdateTsWindow(SSDataBlock* pDataBlock, int32_t tsColumnIndex) {
419
  if (pDataBlock == NULL || pDataBlock->info.rows <= 0 || pDataBlock->info.dataLoad == 0) {
420 421 422
    return 0;
  }

G
Ganlin Zhao 已提交
423 424 425 426
  if (pDataBlock->info.rows > 0) {
    //    ASSERT(pDataBlock->info.dataLoad == 1);
  }

427 428
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  if (numOfCols <= 0) {
429 430 431
    return -1;
  }

432 433
  int32_t index = (tsColumnIndex == -1) ? 0 : tsColumnIndex;

434
  SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, index);
435 436 437 438
  if (pColInfoData->info.type != TSDB_DATA_TYPE_TIMESTAMP) {
    return 0;
  }

439 440 441 442 443 444
  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);

445 446 447
  return 0;
}

448
int32_t blockDataMerge(SSDataBlock* pDest, const SSDataBlock* pSrc) {
449 450
  int32_t capacity = pDest->info.capacity;

451 452
  size_t numOfCols = taosArrayGetSize(pDest->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
453
    SColumnInfoData* pCol2 = taosArrayGet(pDest->pDataBlock, i);
454
    SColumnInfoData* pCol1 = taosArrayGet(pSrc->pDataBlock, i);
H
Haojun Liao 已提交
455

456 457
    capacity = pDest->info.capacity;
    colDataMergeCol(pCol2, pDest->info.rows, &capacity, pCol1, pSrc->info.rows);
H
Haojun Liao 已提交
458 459
  }

460
  pDest->info.capacity = capacity;
H
Haojun Liao 已提交
461 462 463 464 465
  pDest->info.rows += pSrc->info.rows;
  return TSDB_CODE_SUCCESS;
}

size_t blockDataGetSize(const SSDataBlock* pBlock) {
466 467
  size_t total = 0;
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
L
Liu Jicong 已提交
468
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
469
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
H
Haojun Liao 已提交
470
    total += colDataGetFullLength(pColInfoData, pBlock->info.rows);
H
Haojun Liao 已提交
471 472 473 474 475 476 477
  }

  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 已提交
478 479
int32_t blockDataSplitRows(SSDataBlock* pBlock, bool hasVarCol, int32_t startIndex, int32_t* stopIndex,
                           int32_t pageSize) {
L
Liu Jicong 已提交
480
  size_t  numOfCols = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
481 482
  int32_t numOfRows = pBlock->info.rows;

H
Haojun Liao 已提交
483 484
  int32_t bitmapChar = 1;

L
Liu Jicong 已提交
485
  size_t headerSize = sizeof(int32_t);
486
  size_t colHeaderSize = sizeof(int32_t) * numOfCols;
487

H
Haojun Liao 已提交
488
  // TODO speedup by checking if the whole page can fit in firstly.
H
Haojun Liao 已提交
489
  if (!hasVarCol) {
L
Liu Jicong 已提交
490
    size_t  rowSize = blockDataGetRowSize(pBlock);
G
Ganlin Zhao 已提交
491
    int32_t capacity = blockDataGetCapacityInRow(pBlock, pageSize, headerSize + colHeaderSize);
G
Ganlin Zhao 已提交
492 493 494
    if (capacity <= 0) {
      return TSDB_CODE_FAILED;
    }
495

496
    *stopIndex = startIndex + capacity - 1;
H
Haojun Liao 已提交
497 498 499
    if (*stopIndex >= numOfRows) {
      *stopIndex = numOfRows - 1;
    }
500

H
Haojun Liao 已提交
501
    return TSDB_CODE_SUCCESS;
502
  }
wmmhello's avatar
wmmhello 已提交
503 504 505 506 507 508
  // 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)) {
509
        if (pColInfoData->varmeta.offset[j] != -1) {
wmmhello's avatar
wmmhello 已提交
510 511
          char* p = colDataGetData(pColInfoData, j);
          size += varDataTLen(p);
H
Haojun Liao 已提交
512 513
        }

wmmhello's avatar
wmmhello 已提交
514
        size += sizeof(pColInfoData->varmeta.offset[0]);
515
      } else {
wmmhello's avatar
wmmhello 已提交
516
        size += pColInfoData->info.bytes;
H
Haojun Liao 已提交
517

wmmhello's avatar
wmmhello 已提交
518 519 520
        if (((j - startIndex) & 0x07) == 0) {
          size += 1;  // the space for null bitmap
        }
H
Haojun Liao 已提交
521 522 523
      }
    }

wmmhello's avatar
wmmhello 已提交
524
    if (size > pageSize) {  // pageSize must be able to hold one row
wmmhello's avatar
wmmhello 已提交
525
      *stopIndex = j - 1;
G
Ganlin Zhao 已提交
526 527 528
      if (*stopIndex < startIndex) {
        return TSDB_CODE_FAILED;
      }
wmmhello's avatar
wmmhello 已提交
529 530 531

      return TSDB_CODE_SUCCESS;
    }
H
Haojun Liao 已提交
532
  }
wmmhello's avatar
wmmhello 已提交
533 534 535 536

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

539 540 541 542 543
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;
  }

544
  SSDataBlock* pDst = createDataBlock();
545 546 547 548
  if (pDst == NULL) {
    return NULL;
  }

549
  pDst->info = pBlock->info;
550
  pDst->info.rows = 0;
551
  pDst->info.capacity = 0;
552 553
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
L
Liu Jicong 已提交
554
    SColumnInfoData  colInfo = {0};
555 556
    SColumnInfoData* pSrcCol = taosArrayGet(pBlock->pDataBlock, i);
    colInfo.info = pSrcCol->info;
557
    blockDataAppendColInfo(pDst, &colInfo);
558 559
  }

560 561 562
  blockDataEnsureCapacity(pDst, rowCount);

  for (int32_t i = 0; i < numOfCols; ++i) {
563 564 565 566
    SColumnInfoData* pColData = taosArrayGet(pBlock->pDataBlock, i);
    SColumnInfoData* pDstCol = taosArrayGet(pDst->pDataBlock, i);

    for (int32_t j = startIndex; j < (startIndex + rowCount); ++j) {
567 568
      bool isNull = false;
      if (pBlock->pBlockAgg == NULL) {
569
        isNull = colDataIsNull_s(pColData, j);
570 571 572
      } else {
        isNull = colDataIsNull(pColData, pBlock->info.rows, j, pBlock->pBlockAgg[i]);
      }
573

574
      if (isNull) {
575
        colDataSetNULL(pDstCol, j - startIndex);
576 577
      } else {
        char* p = colDataGetData(pColData, j);
578
        colDataSetVal(pDstCol, j - startIndex, p, false);
579
      }
580 581 582 583 584 585 586
    }
  }

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

H
Haojun Liao 已提交
587 588
/**
 *
589 590 591 592 593
 * +------------------+---------------------------------------------+
 * |the number of rows|                    column #1                |
 * |    (4 bytes)     |------------+-----------------------+--------+
 * |                  | null bitmap| column length(4bytes) | values |
 * +------------------+------------+-----------------------+--------+
H
Haojun Liao 已提交
594 595 596 597
 * @param buf
 * @param pBlock
 * @return
 */
598
int32_t blockDataToBuf(char* buf, const SSDataBlock* pBlock) {
H
Haojun Liao 已提交
599
  // write the number of rows
L
Liu Jicong 已提交
600
  *(uint32_t*)buf = pBlock->info.rows;
H
Haojun Liao 已提交
601

L
Liu Jicong 已提交
602
  size_t  numOfCols = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
603 604 605 606
  int32_t numOfRows = pBlock->info.rows;

  char* pStart = buf + sizeof(uint32_t);

L
Liu Jicong 已提交
607
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
608 609 610 611 612 613 614 615 616
    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);
    }

617
    uint32_t dataSize = colDataGetLength(pCol, numOfRows);
618

L
Liu Jicong 已提交
619
    *(int32_t*)pStart = dataSize;
620 621
    pStart += sizeof(int32_t);

D
dapan1121 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
    if (pCol->reassigned && IS_VAR_DATA_TYPE(pCol->info.type)) {
      for (int32_t row = 0; row < numOfRows; ++row) {
        char* pColData = pCol->pData + pCol->varmeta.offset[row];
        int32_t colSize = 0;
        if (pCol->info.type == TSDB_DATA_TYPE_JSON) {
          colSize = getJsonValueLen(pColData);
        } else {
          colSize = varDataTLen(pColData);
        }
        memcpy(pStart, pColData, colSize);
        pStart += colSize;
      }
    } else {
      memcpy(pStart, pCol->pData, dataSize);
      pStart += dataSize;
H
Haojun Liao 已提交
637
    }
H
Haojun Liao 已提交
638 639 640 641 642
  }

  return 0;
}

643
int32_t blockDataFromBuf(SSDataBlock* pBlock, const char* buf) {
L
Liu Jicong 已提交
644
  int32_t numOfRows = *(int32_t*)buf;
645
  blockDataEnsureCapacity(pBlock, numOfRows);
646

647
  pBlock->info.rows = numOfRows;
L
Liu Jicong 已提交
648
  size_t      numOfCols = taosArrayGetSize(pBlock->pDataBlock);
649 650
  const char* pStart = buf + sizeof(uint32_t);

L
Liu Jicong 已提交
651
  for (int32_t i = 0; i < numOfCols; ++i) {
652 653 654
    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, i);

    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
H
Haojun Liao 已提交
655
      size_t metaSize = pBlock->info.rows * sizeof(int32_t);
C
Cary Xu 已提交
656
      char*  tmp = taosMemoryRealloc(pCol->varmeta.offset, metaSize);  // preview calloc is too small
wmmhello's avatar
wmmhello 已提交
657 658 659 660
      if (tmp == NULL) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      pCol->varmeta.offset = (int32_t*)tmp;
661 662 663 664 665 666 667
      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 已提交
668
    int32_t colLength = *(int32_t*)pStart;
669 670
    pStart += sizeof(int32_t);

671 672
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
      if (pCol->varmeta.allocLen < colLength) {
wafwerar's avatar
wafwerar 已提交
673
        char* tmp = taosMemoryRealloc(pCol->pData, colLength);
674 675 676 677 678 679 680 681 682
        if (tmp == NULL) {
          return TSDB_CODE_OUT_OF_MEMORY;
        }

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

      pCol->varmeta.length = colLength;
G
Ganlin Zhao 已提交
683 684 685
      if (pCol->varmeta.length > pCol->varmeta.allocLen) {
        return TSDB_CODE_FAILED;
      }
686 687 688 689 690
    }

    memcpy(pCol->pData, pStart, colLength);
    pStart += colLength;
  }
691 692

  return TSDB_CODE_SUCCESS;
693 694
}

695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
static bool colDataIsNNull(const SColumnInfoData* pColumnInfoData, int32_t startIndex,
                                          uint32_t nRows) {
  if (!pColumnInfoData->hasNull) {
    return false;
  }

  if (IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
    for (int32_t i = startIndex; i < nRows; ++i) {
      if (!colDataIsNull_var(pColumnInfoData, i)) {
        return false;
      }
    }
  } else {
    if (pColumnInfoData->nullbitmap == NULL) {
      return false;
    }

    for (int32_t i = startIndex; i < nRows; ++i) {
      if (!colDataIsNull_f(pColumnInfoData->nullbitmap, i)) {
        return false;
      }
    }
  }

  return true;
}

722
// todo remove this
H
Haojun Liao 已提交
723
int32_t blockDataFromBuf1(SSDataBlock* pBlock, const char* buf, size_t capacity) {
X
Xiaoyu Wang 已提交
724
  pBlock->info.rows = *(int32_t*)buf;
H
Haojun Liao 已提交
725
  pBlock->info.id.groupId = *(uint64_t*)(buf + sizeof(int32_t));
H
Haojun Liao 已提交
726

727 728
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);

729
  const char* pStart = buf + sizeof(uint32_t) + sizeof(uint64_t);
H
Haojun Liao 已提交
730 731 732

  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, i);
733
    pCol->hasNull = true;
H
Haojun Liao 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758

    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;
G
Ganlin Zhao 已提交
759 760 761
      if (pCol->varmeta.length > pCol->varmeta.allocLen) {
        return TSDB_CODE_FAILED;
      }
H
Haojun Liao 已提交
762 763
    }

764
    if (!colDataIsNNull(pCol, 0, pBlock->info.rows)) {
765 766 767
      memcpy(pCol->pData, pStart, colLength);
    }

768
    pStart += pCol->info.bytes * capacity;
H
Haojun Liao 已提交
769 770 771 772 773
  }

  return TSDB_CODE_SUCCESS;
}

774 775 776
size_t blockDataGetRowSize(SSDataBlock* pBlock) {
  if (pBlock->info.rowSize == 0) {
    size_t rowSize = 0;
H
Haojun Liao 已提交
777

778
    size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
L
Liu Jicong 已提交
779 780 781 782
    for (int32_t i = 0; i < numOfCols; ++i) {
      SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, i);
      rowSize += pColInfo->info.bytes;
    }
783 784

    pBlock->info.rowSize = rowSize;
H
Haojun Liao 已提交
785 786
  }

787
  return pBlock->info.rowSize;
H
Haojun Liao 已提交
788 789
}

H
Haojun Liao 已提交
790 791 792 793 794
/**
 * @refitem blockDataToBuf for the meta size
 * @param pBlock
 * @return
 */
795
size_t blockDataGetSerialMetaSize(uint32_t numOfCols) {
796 797
  // | version | total length | total rows | total columns | flag seg| block group id | column schema
  // | each column length |
798 799
  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 已提交
800 801
}

X
Xiaoyu Wang 已提交
802
double blockDataGetSerialRowSize(const SSDataBlock* pBlock) {
H
Haojun Liao 已提交
803 804
  double rowSize = 0;

805
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
L
Liu Jicong 已提交
806
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
807 808 809 810 811 812
    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 已提交
813
      rowSize += 1 / 8.0;  // one bit for each record
H
Haojun Liao 已提交
814 815 816 817 818 819
    }
  }

  return rowSize;
}

H
Haojun Liao 已提交
820
typedef struct SSDataBlockSortHelper {
L
Liu Jicong 已提交
821 822
  SArray*      orderInfo;  // SArray<SBlockOrderInfo>
  SSDataBlock* pDataBlock;
H
Haojun Liao 已提交
823 824 825
} SSDataBlockSortHelper;

int32_t dataBlockCompar(const void* p1, const void* p2, const void* param) {
L
Liu Jicong 已提交
826
  const SSDataBlockSortHelper* pHelper = (const SSDataBlockSortHelper*)param;
H
Haojun Liao 已提交
827 828 829

  SSDataBlock* pDataBlock = pHelper->pDataBlock;

L
Liu Jicong 已提交
830 831
  int32_t left = *(int32_t*)p1;
  int32_t right = *(int32_t*)p2;
H
Haojun Liao 已提交
832 833

  SArray* pInfo = pHelper->orderInfo;
834

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

839
    if (pColInfoData->hasNull) {
840 841
      bool leftNull = colDataIsNull(pColInfoData, pDataBlock->info.rows, left, NULL);
      bool rightNull = colDataIsNull(pColInfoData, pDataBlock->info.rows, right, NULL);
842
      if (leftNull && rightNull) {
L
Liu Jicong 已提交
843
        continue;  // continue to next slot
844
      }
H
Haojun Liao 已提交
845

846
      if (rightNull) {
H
Haojun Liao 已提交
847
        return pOrder->nullFirst ? 1 : -1;
848
      }
H
Haojun Liao 已提交
849

850
      if (leftNull) {
H
Haojun Liao 已提交
851
        return pOrder->nullFirst ? -1 : 1;
852
      }
H
Haojun Liao 已提交
853 854
    }

L
Liu Jicong 已提交
855
    void* left1 = colDataGetData(pColInfoData, left);
856
    void* right1 = colDataGetData(pColInfoData, right);
wmmhello's avatar
wmmhello 已提交
857 858 859 860 861 862
    if (pColInfoData->info.type == TSDB_DATA_TYPE_JSON) {
      if (tTagIsJson(left1) || tTagIsJson(right1)) {
        terrno = TSDB_CODE_QRY_JSON_NOT_SUPPORT_ERROR;
        return 0;
      }
    }
863
    __compar_fn_t fn = getKeyComparFunc(pColInfoData->info.type, pOrder->order);
864

865 866 867 868 869
    int ret = fn(left1, right1);
    if (ret == 0) {
      continue;
    } else {
      return ret;
H
Haojun Liao 已提交
870 871 872 873 874 875
    }
  }

  return 0;
}

876
static int32_t blockDataAssign(SColumnInfoData* pCols, const SSDataBlock* pDataBlock, const int32_t* index) {
877

878 879
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
880 881 882 883
    SColumnInfoData* pDst = &pCols[i];
    SColumnInfoData* pSrc = taosArrayGet(pDataBlock->pDataBlock, i);

    if (IS_VAR_DATA_TYPE(pSrc->info.type)) {
884 885 886
      if (pSrc->varmeta.length != 0) {
        memcpy(pDst->pData, pSrc->pData, pSrc->varmeta.length);
      }
L
Liu Jicong 已提交
887
      pDst->varmeta.length = pSrc->varmeta.length;
H
Haojun Liao 已提交
888

L
Liu Jicong 已提交
889 890 891
      for (int32_t j = 0; j < pDataBlock->info.rows; ++j) {
        pDst->varmeta.offset[j] = pSrc->varmeta.offset[index[j]];
      }
H
Haojun Liao 已提交
892
    } else {
wmmhello's avatar
wmmhello 已提交
893 894
      for (int32_t j = 0; j < pDataBlock->info.rows; ++j) {
        if (colDataIsNull_f(pSrc->nullbitmap, index[j])) {
895
          colDataSetNull_f_s(pDst, j);
wmmhello's avatar
wmmhello 已提交
896
          continue;
H
Haojun Liao 已提交
897
        }
wmmhello's avatar
wmmhello 已提交
898
        memcpy(pDst->pData + j * pDst->info.bytes, pSrc->pData + index[j] * pDst->info.bytes, pDst->info.bytes);
H
Haojun Liao 已提交
899 900 901
      }
    }
  }
902

H
Haojun Liao 已提交
903
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
904 905 906
}

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

wafwerar's avatar
wafwerar 已提交
910
  SColumnInfoData* pCols = taosMemoryCalloc(numOfCols, sizeof(SColumnInfoData));
H
Haojun Liao 已提交
911 912 913 914
  if (pCols == NULL) {
    return NULL;
  }

L
Liu Jicong 已提交
915
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
916 917 918 919
    SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, i);
    pCols[i].info = pColInfoData->info;

    if (IS_VAR_DATA_TYPE(pCols[i].info.type)) {
wafwerar's avatar
wafwerar 已提交
920 921
      pCols[i].varmeta.offset = taosMemoryCalloc(rows, sizeof(int32_t));
      pCols[i].pData = taosMemoryCalloc(1, pColInfoData->varmeta.length);
H
Haojun Liao 已提交
922 923 924

      pCols[i].varmeta.length = pColInfoData->varmeta.length;
      pCols[i].varmeta.allocLen = pCols[i].varmeta.length;
H
Haojun Liao 已提交
925
    } else {
wafwerar's avatar
wafwerar 已提交
926 927
      pCols[i].nullbitmap = taosMemoryCalloc(1, BitmapLen(rows));
      pCols[i].pData = taosMemoryCalloc(rows, pCols[i].info.bytes);
H
Haojun Liao 已提交
928 929 930 931 932 933
    }
  }

  return pCols;
}

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

L
Liu Jicong 已提交
937
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
938 939 940 941
    SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, i);
    pColInfoData->info = pCols[i].info;

    if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
wafwerar's avatar
wafwerar 已提交
942
      taosMemoryFreeClear(pColInfoData->varmeta.offset);
H
Haojun Liao 已提交
943 944
      pColInfoData->varmeta = pCols[i].varmeta;
    } else {
wafwerar's avatar
wafwerar 已提交
945
      taosMemoryFreeClear(pColInfoData->nullbitmap);
H
Haojun Liao 已提交
946 947 948
      pColInfoData->nullbitmap = pCols[i].nullbitmap;
    }

wafwerar's avatar
wafwerar 已提交
949
    taosMemoryFreeClear(pColInfoData->pData);
H
Haojun Liao 已提交
950 951 952
    pColInfoData->pData = pCols[i].pData;
  }

wafwerar's avatar
wafwerar 已提交
953
  taosMemoryFreeClear(pCols);
H
Haojun Liao 已提交
954 955 956
}

static int32_t* createTupleIndex(size_t rows) {
wafwerar's avatar
wafwerar 已提交
957
  int32_t* index = taosMemoryCalloc(rows, sizeof(int32_t));
H
Haojun Liao 已提交
958 959 960 961
  if (index == NULL) {
    return NULL;
  }

L
Liu Jicong 已提交
962
  for (int32_t i = 0; i < rows; ++i) {
H
Haojun Liao 已提交
963 964 965 966 967 968
    index[i] = i;
  }

  return index;
}

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

H
Haojun Liao 已提交
971
int32_t blockDataSort(SSDataBlock* pDataBlock, SArray* pOrderInfo) {
H
Haojun Liao 已提交
972 973 974 975 976 977
  if (pDataBlock->info.rows <= 1) {
    return TSDB_CODE_SUCCESS;
  }

  // Allocate the additional buffer.
  uint32_t rows = pDataBlock->info.rows;
H
Haojun Liao 已提交
978 979 980 981 982 983 984

  bool sortColumnHasNull = false;
  bool varTypeSort = false;

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

H
Haojun Liao 已提交
985
    SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, pInfo->slotId);
H
Haojun Liao 已提交
986 987 988 989 990 991 992 993 994
    if (pColInfoData->hasNull) {
      sortColumnHasNull = true;
    }

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

995 996
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);

H
Haojun Liao 已提交
997
  if (taosArrayGetSize(pOrderInfo) == 1 && (!sortColumnHasNull)) {
998
    if (numOfCols == 1) {
H
Haojun Liao 已提交
999 1000 1001 1002 1003
      if (!varTypeSort) {
        SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, 0);
        SBlockOrderInfo* pOrder = taosArrayGet(pOrderInfo, 0);

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

1005
        __compar_fn_t fn = getKeyComparFunc(pColInfoData->info.type, pOrder->order);
wafwerar's avatar
wafwerar 已提交
1006
        taosSort(pColInfoData->pData, pDataBlock->info.rows, pColInfoData->info.bytes, fn);
H
Haojun Liao 已提交
1007 1008

        int64_t p1 = taosGetTimestampUs();
D
dapan1121 已提交
1009
        uDebug("blockDataSort easy cost:%" PRId64 ", rows:%" PRId64 "\n", p1 - p0, pDataBlock->info.rows);
H
Haojun Liao 已提交
1010 1011 1012 1013

        return TSDB_CODE_SUCCESS;
      } else {  // var data type
      }
1014
    } else if (numOfCols == 2) {
H
Haojun Liao 已提交
1015 1016 1017
    }
  }

H
Haojun Liao 已提交
1018 1019 1020 1021 1022 1023
  int32_t* index = createTupleIndex(rows);
  if (index == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

1024 1025
  int64_t p0 = taosGetTimestampUs();

H
Haojun Liao 已提交
1026
  SSDataBlockSortHelper helper = {.pDataBlock = pDataBlock, .orderInfo = pOrderInfo};
L
Liu Jicong 已提交
1027
  for (int32_t i = 0; i < taosArrayGetSize(helper.orderInfo); ++i) {
H
Haojun Liao 已提交
1028
    struct SBlockOrderInfo* pInfo = taosArrayGet(helper.orderInfo, i);
H
Haojun Liao 已提交
1029
    pInfo->pColData = taosArrayGet(pDataBlock->pDataBlock, pInfo->slotId);
H
Haojun Liao 已提交
1030 1031
  }

X
Xiaoyu Wang 已提交
1032
  terrno = 0;
H
Haojun Liao 已提交
1033
  taosqsort(index, rows, sizeof(int32_t), &helper, dataBlockCompar);
X
Xiaoyu Wang 已提交
1034
  if (terrno) return terrno;
H
Haojun Liao 已提交
1035

1036 1037
  int64_t p1 = taosGetTimestampUs();

H
Haojun Liao 已提交
1038 1039
  SColumnInfoData* pCols = createHelpColInfoData(pDataBlock);
  if (pCols == NULL) {
1040
    destroyTupleIndex(index);
H
Haojun Liao 已提交
1041 1042 1043 1044
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

1045 1046
  int64_t p2 = taosGetTimestampUs();

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

1049
  int64_t p3 = taosGetTimestampUs();
H
Haojun Liao 已提交
1050 1051

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

C
Cary Xu 已提交
1054 1055 1056
  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 已提交
1057
  destroyTupleIndex(index);
H
Haojun Liao 已提交
1058 1059

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1060
}
1061

1062
void blockDataCleanup(SSDataBlock* pDataBlock) {
H
Haojun Liao 已提交
1063
  blockDataEmpty(pDataBlock);
H
Haojun Liao 已提交
1064
  SDataBlockInfo* pInfo = &pDataBlock->info;
H
Haojun Liao 已提交
1065 1066
  pInfo->id.uid = 0;
  pInfo->id.groupId = 0;
H
Haojun Liao 已提交
1067
}
1068

H
Haojun Liao 已提交
1069 1070
void blockDataEmpty(SSDataBlock* pDataBlock) {
  SDataBlockInfo* pInfo = &pDataBlock->info;
D
dapan1121 已提交
1071
  if (pInfo->capacity == 0) {
1072 1073 1074
    return;
  }

1075 1076
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
1077
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
H
Haojun Liao 已提交
1078
    colInfoDataCleanup(p, pInfo->capacity);
1079
  }
H
Haojun Liao 已提交
1080 1081

  pInfo->rows = 0;
1082
  pInfo->dataLoad = 0;
H
Haojun Liao 已提交
1083 1084
  pInfo->window.ekey = 0;
  pInfo->window.skey = 0;
1085 1086
}

1087 1088 1089 1090 1091
/*
 * NOTE: the type of the input column may be TSDB_DATA_TYPE_NULL, which is used to denote
 * the all NULL value in this column. It is an internal representation of all NULL value column, and no visible to
 * any users. The length of TSDB_DATA_TYPE_NULL is 0, and it is an special case.
 */
L
Liu Jicong 已提交
1092 1093
static int32_t doEnsureCapacity(SColumnInfoData* pColumn, const SDataBlockInfo* pBlockInfo, uint32_t numOfRows,
                                bool clearPayload) {
G
Ganlin Zhao 已提交
1094
  if (numOfRows <= 0 || numOfRows <= pBlockInfo->capacity) {
X
Xiaoyu Wang 已提交
1095 1096 1097
    return TSDB_CODE_SUCCESS;
  }

1098 1099
  int32_t existedRows = pBlockInfo->rows;

D
dapan1121 已提交
1100
  if (IS_VAR_DATA_TYPE(pColumn->info.type)) {
wafwerar's avatar
wafwerar 已提交
1101
    char* tmp = taosMemoryRealloc(pColumn->varmeta.offset, sizeof(int32_t) * numOfRows);
D
dapan1121 已提交
1102 1103 1104
    if (tmp == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
1105

D
dapan1121 已提交
1106
    pColumn->varmeta.offset = (int32_t*)tmp;
1107
    memset(&pColumn->varmeta.offset[existedRows], 0, sizeof(int32_t) * (numOfRows - existedRows));
D
dapan1121 已提交
1108
  } else {
1109
    // prepare for the null bitmap
wafwerar's avatar
wafwerar 已提交
1110
    char* tmp = taosMemoryRealloc(pColumn->nullbitmap, BitmapLen(numOfRows));
D
dapan1121 已提交
1111 1112 1113
    if (tmp == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
1114

1115
    int32_t oldLen = BitmapLen(existedRows);
D
dapan1121 已提交
1116
    pColumn->nullbitmap = tmp;
1117
    memset(&pColumn->nullbitmap[oldLen], 0, BitmapLen(numOfRows) - oldLen);
G
Ganlin Zhao 已提交
1118 1119 1120
    if (pColumn->info.bytes == 0) {
      return TSDB_CODE_FAILED;
    }
1121

1122 1123
    // here we employ the aligned malloc function, to make sure that the address of allocated memory is aligned
    // to MALLOC_ALIGN_BYTES
1124
    tmp = taosMemoryMallocAlign(MALLOC_ALIGN_BYTES, numOfRows * pColumn->info.bytes);
D
dapan1121 已提交
1125 1126 1127
    if (tmp == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
L
Liu Jicong 已提交
1128

1129 1130 1131 1132 1133 1134
    // copy back the existed data
    if (pColumn->pData != NULL) {
      memcpy(tmp, pColumn->pData, existedRows * pColumn->info.bytes);
      taosMemoryFreeClear(pColumn->pData);
    }

D
dapan1121 已提交
1135
    pColumn->pData = tmp;
1136

1137
    // check if the allocated memory is aligned to the requried bytes.
1138
#if defined LINUX
G
Ganlin Zhao 已提交
1139 1140 1141
    if ((((uint64_t)pColumn->pData) & (MALLOC_ALIGN_BYTES - 1)) != 0x0) {
      return TSDB_CODE_FAILED;
    }
1142
#endif
H
Haojun Liao 已提交
1143

H
Haojun Liao 已提交
1144 1145 1146
    if (clearPayload) {
      memset(tmp + pColumn->info.bytes * existedRows, 0, pColumn->info.bytes * (numOfRows - existedRows));
    }
D
dapan1121 已提交
1147 1148 1149 1150 1151
  }

  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1152
void colInfoDataCleanup(SColumnInfoData* pColumn, uint32_t numOfRows) {
1153
  pColumn->hasNull = false;
H
Haojun Liao 已提交
1154

1155 1156
  if (IS_VAR_DATA_TYPE(pColumn->info.type)) {
    pColumn->varmeta.length = 0;
1157
    if (pColumn->varmeta.offset != NULL) {
H
Haojun Liao 已提交
1158 1159
      memset(pColumn->varmeta.offset, 0, sizeof(int32_t) * numOfRows);
    }
1160
  } else {
dengyihao's avatar
dengyihao 已提交
1161 1162 1163
    if (pColumn->nullbitmap != NULL) {
      memset(pColumn->nullbitmap, 0, BitmapLen(numOfRows));
    }
1164 1165 1166
  }
}

H
Haojun Liao 已提交
1167
int32_t colInfoDataEnsureCapacity(SColumnInfoData* pColumn, uint32_t numOfRows, bool clearPayload) {
1168
  SDataBlockInfo info = {0};
H
Haojun Liao 已提交
1169
  return doEnsureCapacity(pColumn, &info, numOfRows, clearPayload);
1170 1171
}

D
dapan1121 已提交
1172 1173
int32_t blockDataEnsureCapacity(SSDataBlock* pDataBlock, uint32_t numOfRows) {
  int32_t code = 0;
H
Haojun Liao 已提交
1174
  if (numOfRows == 0 || numOfRows <= pDataBlock->info.capacity) {
H
Haojun Liao 已提交
1175 1176
    return TSDB_CODE_SUCCESS;
  }
L
Liu Jicong 已提交
1177

1178 1179
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
D
dapan1121 已提交
1180
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
H
Haojun Liao 已提交
1181
    code = doEnsureCapacity(p, &pDataBlock->info, numOfRows, false);
D
dapan1121 已提交
1182 1183
    if (code) {
      return code;
1184 1185
    }
  }
H
Haojun Liao 已提交
1186

H
Haojun Liao 已提交
1187
  pDataBlock->info.capacity = numOfRows;
H
Haojun Liao 已提交
1188 1189 1190
  return TSDB_CODE_SUCCESS;
}

1191 1192 1193 1194 1195 1196 1197
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);
  }

H
Haojun Liao 已提交
1198
  pBlock->pDataBlock = taosArrayDestroy(pBlock->pDataBlock);
1199 1200 1201 1202
  taosMemoryFreeClear(pBlock->pBlockAgg);
  memset(&pBlock->info, 0, sizeof(SDataBlockInfo));
}

H
Haojun Liao 已提交
1203 1204 1205 1206 1207
void* blockDataDestroy(SSDataBlock* pBlock) {
  if (pBlock == NULL) {
    return NULL;
  }

1208
  blockDataFreeRes(pBlock);
wafwerar's avatar
wafwerar 已提交
1209
  taosMemoryFreeClear(pBlock);
H
Haojun Liao 已提交
1210
  return NULL;
D
dapan1121 已提交
1211
}
1212

1213
// todo remove it
L
Liu Jicong 已提交
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
int32_t assignOneDataBlock(SSDataBlock* dst, const SSDataBlock* src) {
  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 已提交
1235
    if (pSrc->pData == NULL && (!IS_VAR_DATA_TYPE(pSrc->info.type))) {
L
Liu Jicong 已提交
1236 1237 1238 1239 1240 1241
      continue;
    }

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

1242
  uint32_t cap = dst->info.capacity;
1243
  dst->info = src->info;
1244
  dst->info.capacity = cap;
L
Liu Jicong 已提交
1245 1246
  return 0;
}
1247

5
54liuyao 已提交
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
int32_t copyDataBlock(SSDataBlock* dst, const SSDataBlock* src) {
  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 已提交
1262

1263
  uint32_t cap = dst->info.capacity;
1264
  dst->info = src->info;
1265
  dst->info.capacity = cap;
5
54liuyao 已提交
1266 1267 1268
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1269 1270 1271
SSDataBlock* createSpecialDataBlock(EStreamType type) {
  SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
  pBlock->info.hasVarCol = false;
H
Haojun Liao 已提交
1272
  pBlock->info.id.groupId = 0;
L
Liu Jicong 已提交
1273 1274
  pBlock->info.rows = 0;
  pBlock->info.type = type;
1275
  pBlock->info.rowSize = sizeof(TSKEY) + sizeof(TSKEY) + sizeof(uint64_t) + sizeof(uint64_t) + sizeof(TSKEY) +
L
Liu Jicong 已提交
1276
                         sizeof(TSKEY) + VARSTR_HEADER_SIZE + TSDB_TABLE_NAME_LEN;
L
Liu Jicong 已提交
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294
  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);

1295 1296
  infoData.info.type = TSDB_DATA_TYPE_TIMESTAMP;
  infoData.info.bytes = sizeof(TSKEY);
L
Liu Jicong 已提交
1297 1298 1299 1300 1301
  // calculate start ts
  taosArrayPush(pBlock->pDataBlock, &infoData);
  // calculate end ts
  taosArrayPush(pBlock->pDataBlock, &infoData);

1302 1303
  // table name
  infoData.info.type = TSDB_DATA_TYPE_VARCHAR;
L
Liu Jicong 已提交
1304
  infoData.info.bytes = VARSTR_HEADER_SIZE + TSDB_TABLE_NAME_LEN;
1305 1306
  taosArrayPush(pBlock->pDataBlock, &infoData);

L
Liu Jicong 已提交
1307 1308 1309
  return pBlock;
}

1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
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);
1339
    colDataSetVal(pDst, 0, pData, isNull);
1340 1341 1342 1343 1344 1345 1346
  }

  pBlock->info.rows = 1;

  return pBlock;
}

1347
SSDataBlock* createOneDataBlock(const SSDataBlock* pDataBlock, bool copyData) {
C
Cary Xu 已提交
1348
  if (pDataBlock == NULL) {
1349 1350
    return NULL;
  }
1351

1352 1353 1354 1355
  SSDataBlock* pBlock = createDataBlock();
  pBlock->info = pDataBlock->info;
  pBlock->info.rows = 0;
  pBlock->info.capacity = 0;
1356
  pBlock->info.rowSize = 0;
1357
  pBlock->info.id = pDataBlock->info.id;
1358

1359
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
L
Liu Jicong 已提交
1360
  for (int32_t i = 0; i < numOfCols; ++i) {
1361
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
1362 1363
    SColumnInfoData  colInfo = {.hasNull = true, .info = p->info};
    blockDataAppendColInfo(pBlock, &colInfo);
1364 1365
  }

1366
  if (copyData) {
1367 1368 1369 1370 1371 1372 1373
    int32_t code = blockDataEnsureCapacity(pBlock, pDataBlock->info.rows);
    if (code != TSDB_CODE_SUCCESS) {
      terrno = code;
      blockDataDestroy(pBlock);
      return NULL;
    }

1374 1375 1376
    for (int32_t i = 0; i < numOfCols; ++i) {
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, i);
      SColumnInfoData* pSrc = taosArrayGet(pDataBlock->pDataBlock, i);
1377
      colDataAssign(pDst, pSrc, pDataBlock->info.rows, &pDataBlock->info);
1378 1379 1380 1381 1382 1383
    }

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

1384 1385 1386
  return pBlock;
}

1387 1388 1389 1390
SSDataBlock* createDataBlock() {
  SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
  if (pBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
1391
    return NULL;
1392 1393 1394 1395 1396 1397
  }

  pBlock->pDataBlock = taosArrayInit(4, sizeof(SColumnInfoData));
  if (pBlock->pDataBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    taosMemoryFree(pBlock);
wmmhello's avatar
wmmhello 已提交
1398
    return NULL;
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
  }

  return pBlock;
}

int32_t blockDataAppendColInfo(SSDataBlock* pBlock, SColumnInfoData* pColInfoData) {
  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 已提交
1419
  // todo disable it temporarily
L
Liu Jicong 已提交
1420
  //  ASSERT(pColInfoData->info.type != 0);
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
  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 已提交
1432
  col.info.type = type;
1433 1434 1435 1436 1437
  col.info.bytes = bytes;

  return col;
}

L
Liu Jicong 已提交
1438
SColumnInfoData* bdGetColumnInfoData(const SSDataBlock* pBlock, int32_t index) {
1439 1440 1441 1442 1443 1444 1445
  if (index >= taosArrayGetSize(pBlock->pDataBlock)) {
    return NULL;
  }

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

G
Ganlin Zhao 已提交
1446
size_t blockDataGetCapacityInRow(const SSDataBlock* pBlock, size_t pageSize, int32_t extraSize) {
1447
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
1448

G
Ganlin Zhao 已提交
1449
  int32_t payloadSize = pageSize - extraSize;
1450 1451
  int32_t rowSize = pBlock->info.rowSize;
  int32_t nRows = payloadSize / rowSize;
H
Haojun Liao 已提交
1452
  ASSERT(nRows >= 1);
1453

1454 1455
  int32_t numVarCols = 0;
  int32_t numFixCols = 0;
1456
  for (int32_t i = 0; i < numOfCols; ++i) {
1457 1458
    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, i);
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
      ++numVarCols;
    } else {
      ++numFixCols;
    }
  }

  // find the data payload whose size is greater than payloadSize
  int result = -1;
  int start = 1;
  int end = nRows;
  while (start <= end) {
    int mid = start + (end - start) / 2;
    //data size + var data type columns offset + fixed data type columns bitmap len 
    int midSize = rowSize * mid + numVarCols * sizeof(int32_t) * mid + numFixCols * BitmapLen(mid); 
    if (midSize > payloadSize) {
      result = mid;
      end = mid - 1;
1476
    } else {
1477
      start = mid + 1;
1478 1479 1480
    }
  }

1481 1482
  int32_t newRows = (result != -1) ? result - 1 : nRows;
  // the true value must be less than the value of nRows
1483
  ASSERT(newRows <= nRows && newRows >= 1);
1484 1485

  return newRows;
1486
}
H
Haojun Liao 已提交
1487

1488
void colDataDestroy(SColumnInfoData* pColData) {
1489 1490 1491 1492
  if (!pColData) {
    return;
  }

1493
  if (IS_VAR_DATA_TYPE(pColData->info.type)) {
wmmhello's avatar
wmmhello 已提交
1494
    taosMemoryFreeClear(pColData->varmeta.offset);
1495
  } else {
wmmhello's avatar
wmmhello 已提交
1496
    taosMemoryFreeClear(pColData->nullbitmap);
1497 1498
  }

wmmhello's avatar
wmmhello 已提交
1499
  taosMemoryFreeClear(pColData->pData);
1500 1501
}

H
Haojun Liao 已提交
1502 1503 1504 1505
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 已提交
1506 1507
  if (n % 8 == 0) {
    memmove(nullBitmap, nullBitmap + n / 8, newLen);
H
Haojun Liao 已提交
1508
  } else {
1509
    int32_t  tail = n % 8;
1510
    int32_t  i = 0;
C
Cary Xu 已提交
1511
    uint8_t* p = (uint8_t*)nullBitmap;
H
Haojun Liao 已提交
1512

1513 1514 1515 1516 1517 1518 1519 1520 1521
    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 已提交
1522

1523
        i += 1;
H
Haojun Liao 已提交
1524
      }
1525
    } else if (n > 8) {
1526
      int32_t remain = (total % 8 != 0 && total % 8 <= tail) ? 1 : 0;
1527
      int32_t gap = len - newLen - remain;
1528
      while (i < newLen) {
1529 1530 1531
        uint8_t v = p[i + gap];
        p[i] = (v << tail);

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

1537 1538
        i += 1;
      }
H
Haojun Liao 已提交
1539 1540 1541 1542
    }
  }
}

X
Xiaoyu Wang 已提交
1543
static int32_t colDataMoveVarData(SColumnInfoData* pColInfoData, size_t start, size_t end) {
wmmhello's avatar
wmmhello 已提交
1544 1545 1546
  int32_t dataOffset = -1;
  int32_t dataLen = 0;
  int32_t beigin = start;
X
Xiaoyu Wang 已提交
1547
  while (beigin < end) {
wmmhello's avatar
wmmhello 已提交
1548
    int32_t offset = pColInfoData->varmeta.offset[beigin];
X
Xiaoyu Wang 已提交
1549
    if (offset == -1) {
wmmhello's avatar
wmmhello 已提交
1550 1551 1552
      beigin++;
      continue;
    }
X
Xiaoyu Wang 已提交
1553
    if (start != 0) {
wmmhello's avatar
wmmhello 已提交
1554 1555
      pColInfoData->varmeta.offset[beigin] = dataLen;
    }
X
Xiaoyu Wang 已提交
1556 1557
    char* data = pColInfoData->pData + offset;
    if (dataOffset == -1) dataOffset = offset;  // mark the begin of data
wmmhello's avatar
wmmhello 已提交
1558 1559 1560 1561 1562 1563 1564 1565
    int32_t type = pColInfoData->info.type;
    if (type == TSDB_DATA_TYPE_JSON) {
      dataLen += getJsonValueLen(data);
    } else {
      dataLen += varDataTLen(data);
    }
    beigin++;
  }
1566

X
Xiaoyu Wang 已提交
1567
  if (dataOffset > 0) {
wmmhello's avatar
wmmhello 已提交
1568 1569
    memmove(pColInfoData->pData, pColInfoData->pData + dataOffset, dataLen);
  }
1570 1571

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

H
Haojun Liao 已提交
1575 1576
static void colDataTrimFirstNRows(SColumnInfoData* pColInfoData, size_t n, size_t total) {
  if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
D
dapan1121 已提交
1577 1578
    // pColInfoData->varmeta.length = colDataMoveVarData(pColInfoData, n, total);
    memmove(pColInfoData->varmeta.offset, &pColInfoData->varmeta.offset[n], (total - n) * sizeof(int32_t));
H
Haojun Liao 已提交
1579 1580

    // clear the offset value of the unused entries.
1581
    memset(&pColInfoData->varmeta.offset[total - n], 0, n);
H
Haojun Liao 已提交
1582 1583 1584 1585 1586 1587 1588
  } else {
    int32_t bytes = pColInfoData->info.bytes;
    memmove(pColInfoData->pData, ((char*)pColInfoData->pData + n * bytes), (total - n) * bytes);
    doShiftBitmap(pColInfoData->nullbitmap, n, total);
  }
}

1589
int32_t blockDataTrimFirstRows(SSDataBlock* pBlock, size_t n) {
H
Haojun Liao 已提交
1590 1591 1592 1593 1594
  if (n == 0) {
    return TSDB_CODE_SUCCESS;
  }

  if (pBlock->info.rows <= n) {
H
Haojun Liao 已提交
1595
    blockDataEmpty(pBlock);
H
Haojun Liao 已提交
1596
  } else {
1597 1598
    size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
1599 1600 1601 1602 1603 1604 1605 1606 1607
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
      colDataTrimFirstNRows(pColInfoData, n, pBlock->info.rows);
    }

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

wmmhello's avatar
wmmhello 已提交
1608 1609
static void colDataKeepFirstNRows(SColumnInfoData* pColInfoData, size_t n, size_t total) {
  if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
D
dapan1121 已提交
1610
    // pColInfoData->varmeta.length = colDataMoveVarData(pColInfoData, 0, n);
wmmhello's avatar
wmmhello 已提交
1611 1612 1613 1614 1615 1616
    memset(&pColInfoData->varmeta.offset[n], 0, total - n);
  }
}

int32_t blockDataKeepFirstNRows(SSDataBlock* pBlock, size_t n) {
  if (n == 0) {
H
Haojun Liao 已提交
1617
    blockDataEmpty(pBlock);
wmmhello's avatar
wmmhello 已提交
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
    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 已提交
1635
int32_t tEncodeDataBlock(void** buf, const SSDataBlock* pBlock) {
H
Haojun Liao 已提交
1636
  int64_t tbUid = pBlock->info.id.uid;
1637
  int16_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
1638
  int16_t hasVarCol = pBlock->info.hasVarCol;
D
dapan1121 已提交
1639
  int64_t rows = pBlock->info.rows;
H
Haojun Liao 已提交
1640 1641 1642 1643 1644 1645
  int32_t sz = taosArrayGetSize(pBlock->pDataBlock);

  int32_t tlen = 0;
  tlen += taosEncodeFixedI64(buf, tbUid);
  tlen += taosEncodeFixedI16(buf, numOfCols);
  tlen += taosEncodeFixedI16(buf, hasVarCol);
D
dapan1121 已提交
1646
  tlen += taosEncodeFixedI64(buf, rows);
H
Haojun Liao 已提交
1647 1648 1649 1650
  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);
1651
    tlen += taosEncodeFixedI8(buf, pColData->info.type);
H
Haojun Liao 已提交
1652
    tlen += taosEncodeFixedI32(buf, pColData->info.bytes);
S
slzhou@taodata.com 已提交
1653
    tlen += taosEncodeFixedBool(buf, pColData->hasNull);
H
Haojun Liao 已提交
1654 1655 1656 1657 1658 1659 1660 1661

    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 已提交
1662
    tlen += taosEncodeFixedI32(buf, len);
H
Haojun Liao 已提交
1663

D
dapan1121 已提交
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
    if (pColData->reassigned && IS_VAR_DATA_TYPE(pColData->info.type)) {
      for (int32_t row = 0; row < rows; ++row) {
        char* pData = pColData->pData + pColData->varmeta.offset[row];
        int32_t colSize = 0;
        if (pColData->info.type == TSDB_DATA_TYPE_JSON) {
          colSize = getJsonValueLen(pData);
        } else {
          colSize = varDataTLen(pData);
        }
        tlen += taosEncodeBinary(buf, pData, colSize);
      }
    } else {
      tlen += taosEncodeBinary(buf, pColData->pData, len);
    }
H
Haojun Liao 已提交
1678 1679 1680 1681 1682 1683 1684
  }
  return tlen;
}

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

1685 1686
  int16_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);

H
Haojun Liao 已提交
1687
  buf = taosDecodeFixedU64(buf, &pBlock->info.id.uid);
1688
  buf = taosDecodeFixedI16(buf, &numOfCols);
H
Haojun Liao 已提交
1689
  buf = taosDecodeFixedI16(buf, &pBlock->info.hasVarCol);
D
dapan1121 已提交
1690
  buf = taosDecodeFixedI64(buf, &pBlock->info.rows);
H
Haojun Liao 已提交
1691 1692 1693 1694 1695
  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);
1696
    buf = taosDecodeFixedI8(buf, &data.info.type);
H
Haojun Liao 已提交
1697
    buf = taosDecodeFixedI32(buf, &data.info.bytes);
S
slzhou@taodata.com 已提交
1698
    buf = taosDecodeFixedBool(buf, &data.hasNull);
H
Haojun Liao 已提交
1699 1700 1701 1702 1703 1704 1705 1706 1707 1708

    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);
1709 1710 1711 1712
    if (IS_VAR_DATA_TYPE(data.info.type)) {
      data.varmeta.length = len;
      data.varmeta.allocLen = len;
    }
S
slzhou 已提交
1713
    taosArrayPush(pBlock->pDataBlock, &data);
H
Haojun Liao 已提交
1714 1715
  }
  return (void*)buf;
L
Liu Jicong 已提交
1716
}
L
Liu Jicong 已提交
1717

L
Liu Jicong 已提交
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
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;
    }
  }
1750
  struct tm ptm = {0};
1751
  if (taosLocalTime(&tt, &ptm, buf) == NULL) {
1752 1753
    return buf;
  }
L
Liu Jicong 已提交
1754
  size_t pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
L
Liu Jicong 已提交
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765

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

5
54liuyao 已提交
1767 1768
// for debug
char* dumpBlockData(SSDataBlock* pDataBlock, const char* flag, char** pDataBuf) {
1769
  int32_t size = 2048*1024;
5
54liuyao 已提交
1770
  *pDataBuf = taosMemoryCalloc(size, 1);
1771 1772
  char*   dumpBuf = *pDataBuf;
  char    pBuf[128] = {0};
5
54liuyao 已提交
1773 1774 1775
  int32_t colNum = taosArrayGetSize(pDataBlock->pDataBlock);
  int32_t rows = pDataBlock->info.rows;
  int32_t len = 0;
S
Shengliang Guan 已提交
1776 1777
  len += snprintf(dumpBuf + len, size - len,
                  "===stream===%s|block type %d|child id %d|group id:%" PRIu64 "|uid:%" PRId64
D
dapan1121 已提交
1778
                  "|rows:%" PRId64 "|version:%" PRIu64 "|cal start:%" PRIu64 "|cal end:%" PRIu64 "|tbl:%s\n",
H
Haojun Liao 已提交
1779
                  flag, (int32_t)pDataBlock->info.type, pDataBlock->info.childId, pDataBlock->info.id.groupId,
L
Liu Jicong 已提交
1780
                  pDataBlock->info.id.uid, pDataBlock->info.rows, pDataBlock->info.version,
X
Xiaoyu Wang 已提交
1781
                  pDataBlock->info.calWin.skey, pDataBlock->info.calWin.ekey, pDataBlock->info.parTbName);
S
Shengliang Guan 已提交
1782
  if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1783

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

5
54liuyao 已提交
1788 1789
    for (int32_t k = 0; k < colNum; k++) {
      SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, k);
5
54liuyao 已提交
1790
      if (colDataIsNull(pColInfoData, rows, j, NULL) || !pColInfoData->pData) {
5
54liuyao 已提交
1791
        len += snprintf(dumpBuf + len, size - len, " %15s |", "NULL");
L
Liu Jicong 已提交
1792
        if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1793 1794
        continue;
      }
5
54liuyao 已提交
1795 1796

      void* var = colDataGetData(pColInfoData, j);
5
54liuyao 已提交
1797 1798
      switch (pColInfoData->info.type) {
        case TSDB_DATA_TYPE_TIMESTAMP:
5
54liuyao 已提交
1799
          memset(pBuf, 0, sizeof(pBuf));
5
54liuyao 已提交
1800
          formatTimestamp(pBuf, *(uint64_t*)var, pColInfoData->info.precision);
5
54liuyao 已提交
1801
          len += snprintf(dumpBuf + len, size - len, " %25s |", pBuf);
L
Liu Jicong 已提交
1802
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1803
          break;
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
        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 已提交
1820 1821
        case TSDB_DATA_TYPE_INT:
          len += snprintf(dumpBuf + len, size - len, " %15d |", *(int32_t*)var);
L
Liu Jicong 已提交
1822
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1823 1824 1825
          break;
        case TSDB_DATA_TYPE_UINT:
          len += snprintf(dumpBuf + len, size - len, " %15u |", *(uint32_t*)var);
L
Liu Jicong 已提交
1826
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1827 1828
          break;
        case TSDB_DATA_TYPE_BIGINT:
1829
          len += snprintf(dumpBuf + len, size - len, " %15" PRId64 " |", *(int64_t*)var);
L
Liu Jicong 已提交
1830
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1831 1832
          break;
        case TSDB_DATA_TYPE_UBIGINT:
1833
          len += snprintf(dumpBuf + len, size - len, " %15" PRIu64 " |", *(uint64_t*)var);
L
Liu Jicong 已提交
1834
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1835 1836 1837
          break;
        case TSDB_DATA_TYPE_FLOAT:
          len += snprintf(dumpBuf + len, size - len, " %15f |", *(float*)var);
L
Liu Jicong 已提交
1838
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1839 1840
          break;
        case TSDB_DATA_TYPE_DOUBLE:
5
54liuyao 已提交
1841 1842
          len += snprintf(dumpBuf + len, size - len, " %15f |", *(double*)var);
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1843
          break;
5
54liuyao 已提交
1844 1845 1846 1847
        case TSDB_DATA_TYPE_BOOL:
          len += snprintf(dumpBuf + len, size - len, " %15d |", *(bool*)var);
          if (len >= size - 1) return dumpBuf;
          break;
D
Dingle Zhang 已提交
1848 1849
        case TSDB_DATA_TYPE_VARCHAR:
        case TSDB_DATA_TYPE_GEOMETRY: {
5
54liuyao 已提交
1850
          memset(pBuf, 0, sizeof(pBuf));
L
Liu Jicong 已提交
1851
          char*   pData = colDataGetVarData(pColInfoData, j);
5
54liuyao 已提交
1852
          int32_t dataSize = TMIN(sizeof(pBuf), varDataLen(pData));
5
54liuyao 已提交
1853
          dataSize = TMIN(dataSize, 50);
5
54liuyao 已提交
1854
          memcpy(pBuf, varDataVal(pData), dataSize);
5
54liuyao 已提交
1855 1856
          len += snprintf(dumpBuf + len, size - len, " %15s |", pBuf);
          if (len >= size - 1) return dumpBuf;
L
Liu Jicong 已提交
1857
        } break;
5
54liuyao 已提交
1858
        case TSDB_DATA_TYPE_NCHAR: {
L
Liu Jicong 已提交
1859
          char*   pData = colDataGetVarData(pColInfoData, j);
5
54liuyao 已提交
1860 1861
          int32_t dataSize = TMIN(sizeof(pBuf), varDataLen(pData));
          memset(pBuf, 0, sizeof(pBuf));
C
Cary Xu 已提交
1862
          (void)taosUcs4ToMbs((TdUcs4*)varDataVal(pData), dataSize, pBuf);
5
54liuyao 已提交
1863 1864
          len += snprintf(dumpBuf + len, size - len, " %15s |", pBuf);
          if (len >= size - 1) return dumpBuf;
L
Liu Jicong 已提交
1865
        } break;
5
54liuyao 已提交
1866 1867
      }
    }
L
liuyao 已提交
1868
    len += snprintf(dumpBuf + len, size - len, "%d\n", j);
L
Liu Jicong 已提交
1869
    if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
1870 1871 1872
  }
  len += snprintf(dumpBuf + len, size - len, "%s |end\n", flag);
  return dumpBuf;
L
Liu Jicong 已提交
1873 1874
}

1875
int32_t buildSubmitReqFromDataBlock(SSubmitReq2** ppReq, const SSDataBlock* pDataBlock, const STSchema* pTSchema,
K
kailixu 已提交
1876
                                    int64_t uid, int32_t vgId, tb_uid_t suid) {
1877
  SSubmitReq2* pReq = *ppReq;
1878 1879 1880 1881
  SArray*      pVals = NULL;
  int32_t      numOfBlks = 0;
  int32_t      sz = 1;

K
kailixu 已提交
1882 1883
  terrno = TSDB_CODE_SUCCESS;

1884 1885 1886 1887 1888
  if (NULL == pReq) {
    if (!(pReq = taosMemoryMalloc(sizeof(SSubmitReq2)))) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      goto _end;
    }
1889

1890 1891 1892
    if (!(pReq->aSubmitTbData = taosArrayInit(1, sizeof(SSubmitTbData)))) {
      goto _end;
    }
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902
  }

  for (int32_t i = 0; i < sz; ++i) {
    int32_t colNum = taosArrayGetSize(pDataBlock->pDataBlock);
    int32_t rows = pDataBlock->info.rows;

    if (colNum <= 1) {  // invalid if only with TS col
      continue;
    }

K
kailixu 已提交
1903 1904 1905
    // the rsma result should has the same column number with schema.
    ASSERT(colNum == pTSchema->numOfCols);

K
kailixu 已提交
1906
    SSubmitTbData tbData = {0};
1907

K
kailixu 已提交
1908
    if (!(tbData.aRowP = taosArrayInit(rows, sizeof(SRow*)))) {
1909
      goto _end;
1910
    }
K
kailixu 已提交
1911
    tbData.suid = suid;
1912
    tbData.uid = uid;
K
kailixu 已提交
1913
    tbData.sver = pTSchema->version;
1914 1915

    if (!pVals && !(pVals = taosArrayInit(colNum, sizeof(SColVal)))) {
K
kailixu 已提交
1916
      taosArrayDestroy(tbData.aRowP);
1917
      goto _end;
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
    }

    for (int32_t j = 0; j < rows; ++j) {  // iterate by row

      taosArrayClear(pVals);

      bool    isStartKey = false;
      int32_t offset = 0;
      for (int32_t k = 0; k < colNum; ++k) {  // iterate by column
        SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, k);
1928
        const STColumn*  pCol = &pTSchema->columns[k];
1929 1930 1931 1932 1933 1934 1935
        void*            var = POINTER_SHIFT(pColInfoData->pData, j * pColInfoData->info.bytes);

        switch (pColInfoData->info.type) {
          case TSDB_DATA_TYPE_TIMESTAMP:
            ASSERT(pColInfoData->info.type == pCol->type);
            if (!isStartKey) {
              isStartKey = true;
1936 1937
              ASSERT(PRIMARYKEY_TIMESTAMP_COL_ID == pCol->colId);
              SColVal cv = COL_VAL_VALUE(pCol->colId, pCol->type, (SValue){.val = *(TSKEY*)var});
1938 1939
              taosArrayPush(pVals, &cv);
            } else if (colDataIsNull_s(pColInfoData, j)) {
1940
              SColVal cv = COL_VAL_NULL(pCol->colId, pCol->type);
1941 1942
              taosArrayPush(pVals, &cv);
            } else {
1943
              SColVal cv = COL_VAL_VALUE(pCol->colId, pCol->type, (SValue){.val = *(int64_t*)var});
1944 1945 1946 1947 1948 1949 1950
              taosArrayPush(pVals, &cv);
            }
            break;
          case TSDB_DATA_TYPE_NCHAR:
          case TSDB_DATA_TYPE_VARCHAR: {  // TSDB_DATA_TYPE_BINARY
            ASSERT(pColInfoData->info.type == pCol->type);
            if (colDataIsNull_s(pColInfoData, j)) {
1951
              SColVal cv = COL_VAL_NULL(pCol->colId, pCol->type);
1952 1953
              taosArrayPush(pVals, &cv);
            } else {
K
kailixu 已提交
1954
              void*   data = colDataGetVarData(pColInfoData, j);
1955
              SValue  sv = (SValue){.nData = varDataLen(data), .pData = varDataVal(data)};  // address copy, no value
1956
              SColVal cv = COL_VAL_VALUE(pCol->colId, pCol->type, sv);
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
              taosArrayPush(pVals, &cv);
            }
            break;
          }
          case TSDB_DATA_TYPE_VARBINARY:
          case TSDB_DATA_TYPE_DECIMAL:
          case TSDB_DATA_TYPE_BLOB:
          case TSDB_DATA_TYPE_JSON:
          case TSDB_DATA_TYPE_MEDIUMBLOB:
            uError("the column type %" PRIi16 " is defined but not implemented yet", pColInfoData->info.type);
            ASSERT(0);
            break;
          default:
            if (pColInfoData->info.type < TSDB_DATA_TYPE_MAX && pColInfoData->info.type > TSDB_DATA_TYPE_NULL) {
              if (colDataIsNull_s(pColInfoData, j)) {
1972
                SColVal cv = COL_VAL_NULL(pCol->colId, pCol->type);  // should use pCol->type
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002
                taosArrayPush(pVals, &cv);
              } else {
                SValue sv;
                if (pCol->type == pColInfoData->info.type) {
                  memcpy(&sv.val, var, tDataTypes[pCol->type].bytes);
                } else {
                  /**
                   *  1. sum/avg would convert to int64_t/uint64_t/double during aggregation
                   *  2. below conversion may lead to overflow or loss, the app should select the right data type.
                   */
                  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);
                  }
                  memcpy(&sv.val, tv, tDataTypes[pCol->type].bytes);
                }
2003
                SColVal cv = COL_VAL_VALUE(pCol->colId, pColInfoData->info.type, sv);
2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
                taosArrayPush(pVals, &cv);
              }
            } else {
              uError("the column type %" PRIi16 " is undefined\n", pColInfoData->info.type);
              ASSERT(0);
            }
            break;
        }
      }
      SRow* pRow = NULL;
2014
      if ((terrno = tRowBuild(pVals, pTSchema, &pRow)) < 0) {
2015
        tDestroySubmitTbData(&tbData, TSDB_MSG_FLG_ENCODE);
2016
        goto _end;
2017
      }
2018
      ASSERT(pRow);
K
kailixu 已提交
2019
      taosArrayPush(tbData.aRowP, &pRow);
2020
    }
2021

K
kailixu 已提交
2022
    taosArrayPush(pReq->aSubmitTbData, &tbData);
2023 2024
  }
_end:
2025
  taosArrayDestroy(pVals);
2026
  if (terrno != 0) {
2027
    *ppReq = NULL;
H
Haojun Liao 已提交
2028
    if (pReq) {
2029
      tDestroySubmitReq(pReq, TSDB_MSG_FLG_ENCODE);
H
Haojun Liao 已提交
2030 2031 2032
      taosMemoryFreeClear(pReq);
    }

2033 2034
    return TSDB_CODE_FAILED;
  }
2035
  *ppReq = pReq;
2036 2037
  return TSDB_CODE_SUCCESS;
}
L
Liu Jicong 已提交
2038

L
Liu Jicong 已提交
2039
char* buildCtbNameByGroupId(const char* stbFullName, uint64_t groupId) {
L
liuyao 已提交
2040 2041 2042 2043 2044 2045 2046
  char* pBuf = taosMemoryCalloc(1, TSDB_TABLE_NAME_LEN + 1);
  if (!pBuf) {
    return NULL;
  }
  int32_t code = buildCtbNameByGroupIdImpl(stbFullName, groupId, pBuf);
  if (code != TSDB_CODE_SUCCESS) {
    taosMemoryFree(pBuf);
G
Ganlin Zhao 已提交
2047 2048
    return NULL;
  }
L
liuyao 已提交
2049 2050 2051 2052 2053 2054 2055
  return pBuf;
}

int32_t buildCtbNameByGroupIdImpl(const char* stbFullName, uint64_t groupId, char* cname) {
  if (stbFullName[0] == 0) {
    return TSDB_CODE_FAILED;
  }
G
Ganlin Zhao 已提交
2056

L
Liu Jicong 已提交
2057
  SArray* tags = taosArrayInit(0, sizeof(SSmlKv));
L
Liu Jicong 已提交
2058
  if (tags == NULL) {
L
liuyao 已提交
2059
    return TSDB_CODE_FAILED;
L
Liu Jicong 已提交
2060 2061 2062 2063
  }

  if (cname == NULL) {
    taosArrayDestroy(tags);
L
liuyao 已提交
2064
    return TSDB_CODE_FAILED;
L
Liu Jicong 已提交
2065 2066
  }

L
Liu Jicong 已提交
2067 2068 2069 2070
  SSmlKv pTag = {.key = "group_id",
                 .keyLen = sizeof("group_id") - 1,
                 .type = TSDB_DATA_TYPE_UBIGINT,
                 .u = groupId,
2071
                 .length = sizeof(uint64_t)};
2072 2073 2074 2075
  taosArrayPush(tags, &pTag);

  RandTableName rname = {
      .tags = tags,
L
Liu Jicong 已提交
2076 2077 2078
      .stbFullName = stbFullName,
      .stbFullNameLen = strlen(stbFullName),
      .ctbShortName = cname,
2079 2080 2081 2082 2083 2084
  };

  buildChildTableName(&rname);

  taosArrayDestroy(tags);

G
Ganlin Zhao 已提交
2085
  if ((rname.ctbShortName && rname.ctbShortName[0]) == 0) {
L
liuyao 已提交
2086
    return TSDB_CODE_FAILED;
G
Ganlin Zhao 已提交
2087
  }
L
liuyao 已提交
2088
  return TSDB_CODE_SUCCESS;
2089 2090
}

H
Haojun Liao 已提交
2091 2092 2093
int32_t blockEncode(const SSDataBlock* pBlock, char* data, int32_t numOfCols) {
  int32_t dataLen = 0;

2094
  // todo extract method
2095 2096 2097 2098
  int32_t* version = (int32_t*)data;
  *version = 1;
  data += sizeof(int32_t);

2099 2100 2101
  int32_t* actualLen = (int32_t*)data;
  data += sizeof(int32_t);

2102 2103 2104
  int32_t* rows = (int32_t*)data;
  *rows = pBlock->info.rows;
  data += sizeof(int32_t);
H
Haojun Liao 已提交
2105
  ASSERT(*rows > 0);
2106 2107 2108 2109 2110

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

2111 2112 2113
  // flag segment.
  // the inital bit is for column info
  int32_t* flagSegment = (int32_t*)data;
L
Liu Jicong 已提交
2114
  *flagSegment = (1 << 31);
2115

2116 2117
  data += sizeof(int32_t);

2118 2119 2120
  uint64_t* groupId = (uint64_t*)data;
  data += sizeof(uint64_t);

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

2124 2125
    *((int8_t*)data) = pColInfoData->info.type;
    data += sizeof(int8_t);
2126

L
Liu Jicong 已提交
2127
    *((int32_t*)data) = pColInfoData->info.bytes;
2128 2129 2130
    data += sizeof(int32_t);
  }

2131 2132 2133
  int32_t* colSizes = (int32_t*)data;
  data += numOfCols * sizeof(int32_t);

H
Haojun Liao 已提交
2134
  dataLen = blockDataGetSerialMetaSize(numOfCols);
2135 2136 2137 2138 2139 2140

  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
2141
    size_t metaSize = 0;
2142
    if (IS_VAR_DATA_TYPE(pColRes->info.type)) {
2143
      metaSize = numOfRows * sizeof(int32_t);
2144 2145
      memcpy(data, pColRes->varmeta.offset, metaSize);
    } else {
2146 2147
      metaSize = BitmapLen(numOfRows);
      memcpy(data, pColRes->nullbitmap, metaSize);
2148 2149
    }

2150
    data += metaSize;
H
Haojun Liao 已提交
2151
    dataLen += metaSize;
2152

D
dapan1121 已提交
2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
     if (pColRes->reassigned && IS_VAR_DATA_TYPE(pColRes->info.type)) {
        colSizes[col] = 0;
        for (int32_t row = 0; row < numOfRows; ++row) {
          char* pColData = pColRes->pData + pColRes->varmeta.offset[row];
          int32_t colSize = 0;
          if (pColRes->info.type == TSDB_DATA_TYPE_JSON) {
            colSize = getJsonValueLen(pColData);
          } else {
            colSize = varDataTLen(pColData);
          }
          colSizes[col] += colSize;
          dataLen += colSize;
          memmove(data, pColData, colSize);
          data += colSize;
        }
    } else {
      colSizes[col] = colDataGetLength(pColRes, numOfRows);
      dataLen += colSizes[col];
      if (pColRes->pData != NULL) {
        memmove(data, pColRes->pData, colSizes[col]);
      }
      data += colSizes[col];
2175
    }
2176

2177
    colSizes[col] = htonl(colSizes[col]);
2178
//    uError("blockEncode col bytes:%d, type:%d, size:%d, htonl size:%d", pColRes->info.bytes, pColRes->info.type, htonl(colSizes[col]), colSizes[col]);
2179 2180
  }

H
Haojun Liao 已提交
2181
  *actualLen = dataLen;
H
Haojun Liao 已提交
2182
  *groupId = pBlock->info.id.groupId;
H
Haojun Liao 已提交
2183 2184
  ASSERT(dataLen > 0);
  return dataLen;
2185 2186
}

2187
const char* blockDecode(SSDataBlock* pBlock, const char* pData) {
2188 2189
  const char* pStart = pData;

L
Liu Jicong 已提交
2190
  int32_t version = *(int32_t*)pStart;
2191 2192 2193
  pStart += sizeof(int32_t);
  ASSERT(version == 1);

2194
  // total length sizeof(int32_t)
2195 2196 2197
  int32_t dataLen = *(int32_t*)pStart;
  pStart += sizeof(int32_t);

2198
  // total rows sizeof(int32_t)
L
Liu Jicong 已提交
2199
  int32_t numOfRows = *(int32_t*)pStart;
2200 2201 2202 2203 2204 2205 2206
  pStart += sizeof(int32_t);

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

  // has column info segment
2207 2208
  int32_t flagSeg = *(int32_t*)pStart;
  int32_t hasColumnInfo = (flagSeg >> 31);
2209 2210 2211
  pStart += sizeof(int32_t);

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

2215
  if (pBlock->pDataBlock == NULL) {
2216
    pBlock->pDataBlock = taosArrayInit_s(sizeof(SColumnInfoData), numOfCols);
2217 2218
  }

L
Liu Jicong 已提交
2219
  for (int32_t i = 0; i < numOfCols; ++i) {
2220
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
麦壳饼's avatar
麦壳饼 已提交
2221
    pColInfoData->info.type = *(int8_t*)pStart;
2222
    pStart += sizeof(int8_t);
2223 2224 2225

    pColInfoData->info.bytes = *(int32_t*)pStart;
    pStart += sizeof(int32_t);
2226 2227 2228 2229

    if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
      pBlock->info.hasVarCol = true;
    }
2230 2231 2232 2233
  }

  blockDataEnsureCapacity(pBlock, numOfRows);

2234 2235 2236 2237
  int32_t* colLen = (int32_t*)pStart;
  pStart += sizeof(int32_t) * numOfCols;

  for (int32_t i = 0; i < numOfCols; ++i) {
2238
    colLen[i] = htonl(colLen[i]);
2239 2240 2241 2242 2243 2244 2245
    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;

2246 2247 2248 2249 2250 2251 2252 2253
      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];
2254
      }
2255 2256

      pColInfoData->varmeta.length = colLen[i];
2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272
    } 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];
  }

2273
  pBlock->info.dataLoad = 1;
2274
  pBlock->info.rows = numOfRows;
2275 2276
  ASSERT(pStart - pData == dataLen);
  return pStart;
L
Liu Jicong 已提交
2277
}
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423

void trimDataBlock(SSDataBlock* pBlock, int32_t totalRows, const bool* pBoolList) {
//  int32_t totalRows = pBlock->info.rows;
  int32_t bmLen = BitmapLen(totalRows);
  char*   pBitmap = NULL;
  int32_t maxRows = 0;

  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
    SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, i);
    // it is a reserved column for scalar function, and no data in this column yet.
    if (pDst->pData == NULL) {
      continue;
    }

    int32_t numOfRows = 0;
    if (IS_VAR_DATA_TYPE(pDst->info.type)) {
      int32_t j = 0;
      pDst->varmeta.length = 0;

      while (j < totalRows) {
        if (pBoolList[j] == 0) {
          j += 1;
          continue;
        }

        if (colDataIsNull_var(pDst, j)) {
          colDataSetNull_var(pDst, numOfRows);
        } else {
          // fix address sanitizer error. p1 may point to memory that will change during realloc of colDataSetVal, first copy it to p2
          char* p1 = colDataGetVarData(pDst, j);
          int32_t len = 0;
          if (pDst->info.type == TSDB_DATA_TYPE_JSON) {
            len = getJsonValueLen(p1);
          } else {
            len = varDataTLen(p1);
          }
          char* p2 = taosMemoryMalloc(len);
          memcpy(p2, p1, len);
          colDataSetVal(pDst, numOfRows, p2, false);
          taosMemoryFree(p2);
        }
        numOfRows += 1;
        j += 1;
      }

      if (maxRows < numOfRows) {
        maxRows = numOfRows;
      }
    } else {
      if (pBitmap == NULL) {
        pBitmap = taosMemoryCalloc(1, bmLen);
      }

      memcpy(pBitmap, pDst->nullbitmap, bmLen);
      memset(pDst->nullbitmap, 0, bmLen);

      int32_t j = 0;

      switch (pDst->info.type) {
        case TSDB_DATA_TYPE_BIGINT:
        case TSDB_DATA_TYPE_UBIGINT:
        case TSDB_DATA_TYPE_DOUBLE:
        case TSDB_DATA_TYPE_TIMESTAMP:
          while (j < totalRows) {
            if (pBoolList[j] == 0) {
              j += 1;
              continue;
            }

            if (colDataIsNull_f(pBitmap, j)) {
              colDataSetNull_f(pDst->nullbitmap, numOfRows);
            } else {
              ((int64_t*)pDst->pData)[numOfRows] = ((int64_t*)pDst->pData)[j];
            }
            numOfRows += 1;
            j += 1;
          }
          break;
        case TSDB_DATA_TYPE_FLOAT:
        case TSDB_DATA_TYPE_INT:
        case TSDB_DATA_TYPE_UINT:
          while (j < totalRows) {
            if (pBoolList[j] == 0) {
              j += 1;
              continue;
            }
            if (colDataIsNull_f(pBitmap, j)) {
              colDataSetNull_f(pDst->nullbitmap, numOfRows);
            } else {
              ((int32_t*)pDst->pData)[numOfRows] = ((int32_t*)pDst->pData)[j];
            }
            numOfRows += 1;
            j += 1;
          }
          break;
        case TSDB_DATA_TYPE_SMALLINT:
        case TSDB_DATA_TYPE_USMALLINT:
          while (j < totalRows) {
            if (pBoolList[j] == 0) {
              j += 1;
              continue;
            }
            if (colDataIsNull_f(pBitmap, j)) {
              colDataSetNull_f(pDst->nullbitmap, numOfRows);
            } else {
              ((int16_t*)pDst->pData)[numOfRows] = ((int16_t*)pDst->pData)[j];
            }
            numOfRows += 1;
            j += 1;
          }
          break;
        case TSDB_DATA_TYPE_BOOL:
        case TSDB_DATA_TYPE_TINYINT:
        case TSDB_DATA_TYPE_UTINYINT:
          while (j < totalRows) {
            if (pBoolList[j] == 0) {
              j += 1;
              continue;
            }
            if (colDataIsNull_f(pBitmap, j)) {
              colDataSetNull_f(pDst->nullbitmap, numOfRows);
            } else {
              ((int8_t*)pDst->pData)[numOfRows] = ((int8_t*)pDst->pData)[j];
            }
            numOfRows += 1;
            j += 1;
          }
          break;
      }
    }

    if (maxRows < numOfRows) {
      maxRows = numOfRows;
    }
  }

  pBlock->info.rows = maxRows;
  if (pBitmap != NULL) {
    taosMemoryFree(pBitmap);
  }
}

int32_t blockGetEncodeSize(const SSDataBlock* pBlock) {
  return blockDataGetSerialMetaSize(taosArrayGetSize(pBlock->pDataBlock)) + blockDataGetSize(pBlock);
}