tdatablock.c 75.3 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
    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 {
S
slzhou 已提交
635 636 637 638
      if (dataSize != 0) {
        // ubsan reports error if pCol->pData==NULL && dataSize==0
        memcpy(pStart, pCol->pData, dataSize);
      }
D
dapan1121 已提交
639
      pStart += dataSize;
H
Haojun Liao 已提交
640
    }
H
Haojun Liao 已提交
641 642 643 644 645
  }

  return 0;
}

646
int32_t blockDataFromBuf(SSDataBlock* pBlock, const char* buf) {
L
Liu Jicong 已提交
647
  int32_t numOfRows = *(int32_t*)buf;
648
  blockDataEnsureCapacity(pBlock, numOfRows);
649

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

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

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

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

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

      pCol->varmeta.length = colLength;
G
Ganlin Zhao 已提交
686 687 688
      if (pCol->varmeta.length > pCol->varmeta.allocLen) {
        return TSDB_CODE_FAILED;
      }
689
    }
S
slzhou 已提交
690 691 692 693
    if (colLength != 0) {
      // ubsan reports error if colLength==0 && pCol->pData == 0
      memcpy(pCol->pData, pStart, colLength);
    }
694 695
    pStart += colLength;
  }
696 697

  return TSDB_CODE_SUCCESS;
698 699
}

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
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;
}

727
// todo remove this
H
Haojun Liao 已提交
728
int32_t blockDataFromBuf1(SSDataBlock* pBlock, const char* buf, size_t capacity) {
X
Xiaoyu Wang 已提交
729
  pBlock->info.rows = *(int32_t*)buf;
H
Haojun Liao 已提交
730
  pBlock->info.id.groupId = *(uint64_t*)(buf + sizeof(int32_t));
H
Haojun Liao 已提交
731

732 733
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);

734
  const char* pStart = buf + sizeof(uint32_t) + sizeof(uint64_t);
H
Haojun Liao 已提交
735 736 737

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

    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 已提交
764 765 766
      if (pCol->varmeta.length > pCol->varmeta.allocLen) {
        return TSDB_CODE_FAILED;
      }
H
Haojun Liao 已提交
767 768
    }

769
    if (!colDataIsNNull(pCol, 0, pBlock->info.rows)) {
770 771 772
      memcpy(pCol->pData, pStart, colLength);
    }

773
    pStart += pCol->info.bytes * capacity;
H
Haojun Liao 已提交
774 775 776 777 778
  }

  return TSDB_CODE_SUCCESS;
}

779 780 781
size_t blockDataGetRowSize(SSDataBlock* pBlock) {
  if (pBlock->info.rowSize == 0) {
    size_t rowSize = 0;
H
Haojun Liao 已提交
782

783
    size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
L
Liu Jicong 已提交
784 785 786 787
    for (int32_t i = 0; i < numOfCols; ++i) {
      SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, i);
      rowSize += pColInfo->info.bytes;
    }
788 789

    pBlock->info.rowSize = rowSize;
H
Haojun Liao 已提交
790 791
  }

792
  return pBlock->info.rowSize;
H
Haojun Liao 已提交
793 794
}

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

X
Xiaoyu Wang 已提交
807
double blockDataGetSerialRowSize(const SSDataBlock* pBlock) {
H
Haojun Liao 已提交
808 809
  double rowSize = 0;

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

  return rowSize;
}

H
Haojun Liao 已提交
825
typedef struct SSDataBlockSortHelper {
L
Liu Jicong 已提交
826 827
  SArray*      orderInfo;  // SArray<SBlockOrderInfo>
  SSDataBlock* pDataBlock;
H
Haojun Liao 已提交
828 829 830
} SSDataBlockSortHelper;

int32_t dataBlockCompar(const void* p1, const void* p2, const void* param) {
L
Liu Jicong 已提交
831
  const SSDataBlockSortHelper* pHelper = (const SSDataBlockSortHelper*)param;
H
Haojun Liao 已提交
832 833 834

  SSDataBlock* pDataBlock = pHelper->pDataBlock;

L
Liu Jicong 已提交
835 836
  int32_t left = *(int32_t*)p1;
  int32_t right = *(int32_t*)p2;
H
Haojun Liao 已提交
837 838

  SArray* pInfo = pHelper->orderInfo;
839

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

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

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

855
      if (leftNull) {
H
Haojun Liao 已提交
856
        return pOrder->nullFirst ? -1 : 1;
857
      }
H
Haojun Liao 已提交
858 859
    }

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

870 871 872 873 874
    int ret = fn(left1, right1);
    if (ret == 0) {
      continue;
    } else {
      return ret;
H
Haojun Liao 已提交
875 876 877 878 879 880
    }
  }

  return 0;
}

881
static int32_t blockDataAssign(SColumnInfoData* pCols, const SSDataBlock* pDataBlock, const int32_t* index) {
882

883 884
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
885 886 887 888
    SColumnInfoData* pDst = &pCols[i];
    SColumnInfoData* pSrc = taosArrayGet(pDataBlock->pDataBlock, i);

    if (IS_VAR_DATA_TYPE(pSrc->info.type)) {
889 890 891
      if (pSrc->varmeta.length != 0) {
        memcpy(pDst->pData, pSrc->pData, pSrc->varmeta.length);
      }
L
Liu Jicong 已提交
892
      pDst->varmeta.length = pSrc->varmeta.length;
H
Haojun Liao 已提交
893

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

H
Haojun Liao 已提交
908
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
909 910 911
}

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

wafwerar's avatar
wafwerar 已提交
915
  SColumnInfoData* pCols = taosMemoryCalloc(numOfCols, sizeof(SColumnInfoData));
H
Haojun Liao 已提交
916 917 918 919
  if (pCols == NULL) {
    return NULL;
  }

L
Liu Jicong 已提交
920
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
921 922 923 924
    SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, i);
    pCols[i].info = pColInfoData->info;

    if (IS_VAR_DATA_TYPE(pCols[i].info.type)) {
wafwerar's avatar
wafwerar 已提交
925 926
      pCols[i].varmeta.offset = taosMemoryCalloc(rows, sizeof(int32_t));
      pCols[i].pData = taosMemoryCalloc(1, pColInfoData->varmeta.length);
H
Haojun Liao 已提交
927 928 929

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

  return pCols;
}

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

L
Liu Jicong 已提交
942
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
943 944 945 946
    SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, i);
    pColInfoData->info = pCols[i].info;

    if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
wafwerar's avatar
wafwerar 已提交
947
      taosMemoryFreeClear(pColInfoData->varmeta.offset);
H
Haojun Liao 已提交
948 949
      pColInfoData->varmeta = pCols[i].varmeta;
    } else {
wafwerar's avatar
wafwerar 已提交
950
      taosMemoryFreeClear(pColInfoData->nullbitmap);
H
Haojun Liao 已提交
951 952 953
      pColInfoData->nullbitmap = pCols[i].nullbitmap;
    }

wafwerar's avatar
wafwerar 已提交
954
    taosMemoryFreeClear(pColInfoData->pData);
H
Haojun Liao 已提交
955 956 957
    pColInfoData->pData = pCols[i].pData;
  }

wafwerar's avatar
wafwerar 已提交
958
  taosMemoryFreeClear(pCols);
H
Haojun Liao 已提交
959 960 961
}

static int32_t* createTupleIndex(size_t rows) {
wafwerar's avatar
wafwerar 已提交
962
  int32_t* index = taosMemoryCalloc(rows, sizeof(int32_t));
H
Haojun Liao 已提交
963 964 965 966
  if (index == NULL) {
    return NULL;
  }

L
Liu Jicong 已提交
967
  for (int32_t i = 0; i < rows; ++i) {
H
Haojun Liao 已提交
968 969 970 971 972 973
    index[i] = i;
  }

  return index;
}

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

H
Haojun Liao 已提交
976
int32_t blockDataSort(SSDataBlock* pDataBlock, SArray* pOrderInfo) {
H
Haojun Liao 已提交
977 978 979 980 981 982
  if (pDataBlock->info.rows <= 1) {
    return TSDB_CODE_SUCCESS;
  }

  // Allocate the additional buffer.
  uint32_t rows = pDataBlock->info.rows;
H
Haojun Liao 已提交
983 984 985 986 987 988 989

  bool sortColumnHasNull = false;
  bool varTypeSort = false;

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

H
Haojun Liao 已提交
990
    SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, pInfo->slotId);
H
Haojun Liao 已提交
991 992 993 994 995 996 997 998 999
    if (pColInfoData->hasNull) {
      sortColumnHasNull = true;
    }

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

1000 1001
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);

H
Haojun Liao 已提交
1002
  if (taosArrayGetSize(pOrderInfo) == 1 && (!sortColumnHasNull)) {
1003
    if (numOfCols == 1) {
H
Haojun Liao 已提交
1004 1005 1006 1007 1008
      if (!varTypeSort) {
        SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, 0);
        SBlockOrderInfo* pOrder = taosArrayGet(pOrderInfo, 0);

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

1010
        __compar_fn_t fn = getKeyComparFunc(pColInfoData->info.type, pOrder->order);
wafwerar's avatar
wafwerar 已提交
1011
        taosSort(pColInfoData->pData, pDataBlock->info.rows, pColInfoData->info.bytes, fn);
H
Haojun Liao 已提交
1012 1013

        int64_t p1 = taosGetTimestampUs();
D
dapan1121 已提交
1014
        uDebug("blockDataSort easy cost:%" PRId64 ", rows:%" PRId64 "\n", p1 - p0, pDataBlock->info.rows);
H
Haojun Liao 已提交
1015 1016 1017 1018

        return TSDB_CODE_SUCCESS;
      } else {  // var data type
      }
1019
    } else if (numOfCols == 2) {
H
Haojun Liao 已提交
1020 1021 1022
    }
  }

H
Haojun Liao 已提交
1023 1024 1025 1026 1027 1028
  int32_t* index = createTupleIndex(rows);
  if (index == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

1029 1030
  int64_t p0 = taosGetTimestampUs();

H
Haojun Liao 已提交
1031
  SSDataBlockSortHelper helper = {.pDataBlock = pDataBlock, .orderInfo = pOrderInfo};
L
Liu Jicong 已提交
1032
  for (int32_t i = 0; i < taosArrayGetSize(helper.orderInfo); ++i) {
H
Haojun Liao 已提交
1033
    struct SBlockOrderInfo* pInfo = taosArrayGet(helper.orderInfo, i);
H
Haojun Liao 已提交
1034
    pInfo->pColData = taosArrayGet(pDataBlock->pDataBlock, pInfo->slotId);
H
Haojun Liao 已提交
1035 1036
  }

X
Xiaoyu Wang 已提交
1037
  terrno = 0;
H
Haojun Liao 已提交
1038
  taosqsort(index, rows, sizeof(int32_t), &helper, dataBlockCompar);
X
Xiaoyu Wang 已提交
1039
  if (terrno) return terrno;
H
Haojun Liao 已提交
1040

1041 1042
  int64_t p1 = taosGetTimestampUs();

H
Haojun Liao 已提交
1043 1044
  SColumnInfoData* pCols = createHelpColInfoData(pDataBlock);
  if (pCols == NULL) {
1045
    destroyTupleIndex(index);
H
Haojun Liao 已提交
1046 1047 1048 1049
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

1050 1051
  int64_t p2 = taosGetTimestampUs();

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

1054
  int64_t p3 = taosGetTimestampUs();
H
Haojun Liao 已提交
1055 1056

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

C
Cary Xu 已提交
1059 1060 1061
  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 已提交
1062
  destroyTupleIndex(index);
H
Haojun Liao 已提交
1063 1064

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1065
}
1066

1067
void blockDataCleanup(SSDataBlock* pDataBlock) {
H
Haojun Liao 已提交
1068
  blockDataEmpty(pDataBlock);
H
Haojun Liao 已提交
1069
  SDataBlockInfo* pInfo = &pDataBlock->info;
H
Haojun Liao 已提交
1070 1071
  pInfo->id.uid = 0;
  pInfo->id.groupId = 0;
H
Haojun Liao 已提交
1072
}
1073

H
Haojun Liao 已提交
1074 1075
void blockDataEmpty(SSDataBlock* pDataBlock) {
  SDataBlockInfo* pInfo = &pDataBlock->info;
D
dapan1121 已提交
1076
  if (pInfo->capacity == 0) {
1077 1078 1079
    return;
  }

1080 1081
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
1082
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
H
Haojun Liao 已提交
1083
    colInfoDataCleanup(p, pInfo->capacity);
1084
  }
H
Haojun Liao 已提交
1085 1086

  pInfo->rows = 0;
1087
  pInfo->dataLoad = 0;
H
Haojun Liao 已提交
1088 1089
  pInfo->window.ekey = 0;
  pInfo->window.skey = 0;
1090 1091
}

1092 1093 1094 1095 1096
/*
 * 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 已提交
1097 1098
static int32_t doEnsureCapacity(SColumnInfoData* pColumn, const SDataBlockInfo* pBlockInfo, uint32_t numOfRows,
                                bool clearPayload) {
G
Ganlin Zhao 已提交
1099
  if (numOfRows <= 0 || numOfRows <= pBlockInfo->capacity) {
X
Xiaoyu Wang 已提交
1100 1101 1102
    return TSDB_CODE_SUCCESS;
  }

1103 1104
  int32_t existedRows = pBlockInfo->rows;

D
dapan1121 已提交
1105
  if (IS_VAR_DATA_TYPE(pColumn->info.type)) {
wafwerar's avatar
wafwerar 已提交
1106
    char* tmp = taosMemoryRealloc(pColumn->varmeta.offset, sizeof(int32_t) * numOfRows);
D
dapan1121 已提交
1107 1108 1109
    if (tmp == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
1110

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

1120
    int32_t oldLen = BitmapLen(existedRows);
D
dapan1121 已提交
1121
    pColumn->nullbitmap = tmp;
1122
    memset(&pColumn->nullbitmap[oldLen], 0, BitmapLen(numOfRows) - oldLen);
G
Ganlin Zhao 已提交
1123 1124 1125
    if (pColumn->info.bytes == 0) {
      return TSDB_CODE_FAILED;
    }
1126

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

1134 1135 1136 1137 1138 1139
    // copy back the existed data
    if (pColumn->pData != NULL) {
      memcpy(tmp, pColumn->pData, existedRows * pColumn->info.bytes);
      taosMemoryFreeClear(pColumn->pData);
    }

D
dapan1121 已提交
1140
    pColumn->pData = tmp;
1141

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

H
Haojun Liao 已提交
1149 1150 1151
    if (clearPayload) {
      memset(tmp + pColumn->info.bytes * existedRows, 0, pColumn->info.bytes * (numOfRows - existedRows));
    }
D
dapan1121 已提交
1152 1153 1154 1155 1156
  }

  return TSDB_CODE_SUCCESS;
}

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

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

H
Haojun Liao 已提交
1172
int32_t colInfoDataEnsureCapacity(SColumnInfoData* pColumn, uint32_t numOfRows, bool clearPayload) {
1173
  SDataBlockInfo info = {0};
H
Haojun Liao 已提交
1174
  return doEnsureCapacity(pColumn, &info, numOfRows, clearPayload);
1175 1176
}

D
dapan1121 已提交
1177 1178
int32_t blockDataEnsureCapacity(SSDataBlock* pDataBlock, uint32_t numOfRows) {
  int32_t code = 0;
H
Haojun Liao 已提交
1179
  if (numOfRows == 0 || numOfRows <= pDataBlock->info.capacity) {
H
Haojun Liao 已提交
1180 1181
    return TSDB_CODE_SUCCESS;
  }
L
Liu Jicong 已提交
1182

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

H
Haojun Liao 已提交
1192
  pDataBlock->info.capacity = numOfRows;
H
Haojun Liao 已提交
1193 1194 1195
  return TSDB_CODE_SUCCESS;
}

1196 1197 1198 1199 1200 1201 1202
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 已提交
1203
  pBlock->pDataBlock = taosArrayDestroy(pBlock->pDataBlock);
1204 1205 1206 1207
  taosMemoryFreeClear(pBlock->pBlockAgg);
  memset(&pBlock->info, 0, sizeof(SDataBlockInfo));
}

H
Haojun Liao 已提交
1208 1209 1210 1211 1212
void* blockDataDestroy(SSDataBlock* pBlock) {
  if (pBlock == NULL) {
    return NULL;
  }

1213
  blockDataFreeRes(pBlock);
wafwerar's avatar
wafwerar 已提交
1214
  taosMemoryFreeClear(pBlock);
H
Haojun Liao 已提交
1215
  return NULL;
D
dapan1121 已提交
1216
}
1217

1218
// todo remove it
L
Liu Jicong 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
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 已提交
1240
    if (pSrc->pData == NULL && (!IS_VAR_DATA_TYPE(pSrc->info.type))) {
L
Liu Jicong 已提交
1241 1242 1243 1244 1245 1246
      continue;
    }

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

1247
  uint32_t cap = dst->info.capacity;
1248
  dst->info = src->info;
1249
  dst->info.capacity = cap;
L
Liu Jicong 已提交
1250 1251
  return 0;
}
1252

5
54liuyao 已提交
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
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 已提交
1267

1268
  uint32_t cap = dst->info.capacity;
1269
  dst->info = src->info;
1270
  dst->info.capacity = cap;
5
54liuyao 已提交
1271 1272 1273
  return TSDB_CODE_SUCCESS;
}

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

1300 1301
  infoData.info.type = TSDB_DATA_TYPE_TIMESTAMP;
  infoData.info.bytes = sizeof(TSKEY);
L
Liu Jicong 已提交
1302 1303 1304 1305 1306
  // calculate start ts
  taosArrayPush(pBlock->pDataBlock, &infoData);
  // calculate end ts
  taosArrayPush(pBlock->pDataBlock, &infoData);

1307 1308
  // table name
  infoData.info.type = TSDB_DATA_TYPE_VARCHAR;
L
Liu Jicong 已提交
1309
  infoData.info.bytes = VARSTR_HEADER_SIZE + TSDB_TABLE_NAME_LEN;
1310 1311
  taosArrayPush(pBlock->pDataBlock, &infoData);

L
Liu Jicong 已提交
1312 1313 1314
  return pBlock;
}

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

  pBlock->info.rows = 1;

  return pBlock;
}

1352
SSDataBlock* createOneDataBlock(const SSDataBlock* pDataBlock, bool copyData) {
C
Cary Xu 已提交
1353
  if (pDataBlock == NULL) {
1354 1355
    return NULL;
  }
1356

1357 1358 1359 1360
  SSDataBlock* pBlock = createDataBlock();
  pBlock->info = pDataBlock->info;
  pBlock->info.rows = 0;
  pBlock->info.capacity = 0;
1361
  pBlock->info.rowSize = 0;
1362
  pBlock->info.id = pDataBlock->info.id;
1363

1364
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
L
Liu Jicong 已提交
1365
  for (int32_t i = 0; i < numOfCols; ++i) {
1366
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
1367 1368
    SColumnInfoData  colInfo = {.hasNull = true, .info = p->info};
    blockDataAppendColInfo(pBlock, &colInfo);
1369 1370
  }

1371
  if (copyData) {
1372 1373 1374 1375 1376 1377 1378
    int32_t code = blockDataEnsureCapacity(pBlock, pDataBlock->info.rows);
    if (code != TSDB_CODE_SUCCESS) {
      terrno = code;
      blockDataDestroy(pBlock);
      return NULL;
    }

1379 1380 1381
    for (int32_t i = 0; i < numOfCols; ++i) {
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, i);
      SColumnInfoData* pSrc = taosArrayGet(pDataBlock->pDataBlock, i);
1382
      colDataAssign(pDst, pSrc, pDataBlock->info.rows, &pDataBlock->info);
1383 1384 1385 1386 1387 1388
    }

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

1389 1390 1391
  return pBlock;
}

1392 1393 1394 1395
SSDataBlock* createDataBlock() {
  SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
  if (pBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
1396
    return NULL;
1397 1398 1399 1400 1401 1402
  }

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

  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 已提交
1424
  // todo disable it temporarily
L
Liu Jicong 已提交
1425
  //  ASSERT(pColInfoData->info.type != 0);
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
  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 已提交
1437
  col.info.type = type;
1438 1439 1440 1441 1442
  col.info.bytes = bytes;

  return col;
}

L
Liu Jicong 已提交
1443
SColumnInfoData* bdGetColumnInfoData(const SSDataBlock* pBlock, int32_t index) {
1444 1445 1446 1447 1448 1449 1450
  if (index >= taosArrayGetSize(pBlock->pDataBlock)) {
    return NULL;
  }

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

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

G
Ganlin Zhao 已提交
1454
  int32_t payloadSize = pageSize - extraSize;
1455 1456
  int32_t rowSize = pBlock->info.rowSize;
  int32_t nRows = payloadSize / rowSize;
H
Haojun Liao 已提交
1457
  ASSERT(nRows >= 1);
1458

1459 1460
  int32_t numVarCols = 0;
  int32_t numFixCols = 0;
1461
  for (int32_t i = 0; i < numOfCols; ++i) {
1462 1463
    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, i);
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
      ++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;
1481
    } else {
1482
      start = mid + 1;
1483 1484 1485
    }
  }

1486 1487
  int32_t newRows = (result != -1) ? result - 1 : nRows;
  // the true value must be less than the value of nRows
1488
  ASSERT(newRows <= nRows && newRows >= 1);
1489 1490

  return newRows;
1491
}
H
Haojun Liao 已提交
1492

1493
void colDataDestroy(SColumnInfoData* pColData) {
1494 1495 1496 1497
  if (!pColData) {
    return;
  }

1498
  if (IS_VAR_DATA_TYPE(pColData->info.type)) {
wmmhello's avatar
wmmhello 已提交
1499
    taosMemoryFreeClear(pColData->varmeta.offset);
1500
  } else {
wmmhello's avatar
wmmhello 已提交
1501
    taosMemoryFreeClear(pColData->nullbitmap);
1502 1503
  }

wmmhello's avatar
wmmhello 已提交
1504
  taosMemoryFreeClear(pColData->pData);
1505 1506
}

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

1518 1519 1520 1521 1522 1523 1524 1525 1526
    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 已提交
1527

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

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

1542 1543
        i += 1;
      }
H
Haojun Liao 已提交
1544 1545 1546 1547
    }
  }
}

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

X
Xiaoyu Wang 已提交
1572
  if (dataOffset > 0) {
wmmhello's avatar
wmmhello 已提交
1573 1574
    memmove(pColInfoData->pData, pColInfoData->pData + dataOffset, dataLen);
  }
1575 1576

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

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

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

1594
int32_t blockDataTrimFirstRows(SSDataBlock* pBlock, size_t n) {
H
Haojun Liao 已提交
1595 1596 1597 1598 1599
  if (n == 0) {
    return TSDB_CODE_SUCCESS;
  }

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

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

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

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

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

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

D
dapan1121 已提交
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
    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 已提交
1683 1684 1685 1686 1687 1688 1689
  }
  return tlen;
}

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

1690 1691
  int16_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);

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

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

L
Liu Jicong 已提交
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 1750 1751 1752 1753 1754
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;
    }
  }
1755
  struct tm ptm = {0};
1756
  if (taosLocalTime(&tt, &ptm, buf) == NULL) {
1757 1758
    return buf;
  }
L
Liu Jicong 已提交
1759
  size_t pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
L
Liu Jicong 已提交
1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770

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

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

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

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

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

1880 1881 1882
int32_t buildSubmitReqFromDataBlock(SSubmitReq2** ppReq, const SSDataBlock* pDataBlock, const STSchema* pTSchema,
                                    int64_t uid, int32_t vgId, tb_uid_t suid) {
  SSubmitReq2* pReq = *ppReq;
1883 1884 1885 1886
  SArray*      pVals = NULL;
  int32_t      numOfBlks = 0;
  int32_t      sz = 1;

K
kailixu 已提交
1887 1888
  terrno = TSDB_CODE_SUCCESS;

1889 1890 1891 1892 1893
  if (NULL == pReq) {
    if (!(pReq = taosMemoryMalloc(sizeof(SSubmitReq2)))) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      goto _end;
    }
1894

1895 1896 1897
    if (!(pReq->aSubmitTbData = taosArrayInit(1, sizeof(SSubmitTbData)))) {
      goto _end;
    }
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
  }

  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 已提交
1908 1909 1910
    // the rsma result should has the same column number with schema.
    ASSERT(colNum == pTSchema->numOfCols);

K
kailixu 已提交
1911
    SSubmitTbData tbData = {0};
1912

K
kailixu 已提交
1913
    if (!(tbData.aRowP = taosArrayInit(rows, sizeof(SRow*)))) {
1914
      goto _end;
1915
    }
K
kailixu 已提交
1916
    tbData.suid = suid;
1917
    tbData.uid = uid;
K
kailixu 已提交
1918
    tbData.sver = pTSchema->version;
1919 1920

    if (!pVals && !(pVals = taosArrayInit(colNum, sizeof(SColVal)))) {
K
kailixu 已提交
1921
      taosArrayDestroy(tbData.aRowP);
1922
      goto _end;
1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
    }

    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);
1933
        const STColumn*  pCol = &pTSchema->columns[k];
1934 1935 1936 1937 1938 1939 1940
        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;
1941 1942
              ASSERT(PRIMARYKEY_TIMESTAMP_COL_ID == pCol->colId);
              SColVal cv = COL_VAL_VALUE(pCol->colId, pCol->type, (SValue){.val = *(TSKEY*)var});
1943 1944
              taosArrayPush(pVals, &cv);
            } else if (colDataIsNull_s(pColInfoData, j)) {
1945
              SColVal cv = COL_VAL_NULL(pCol->colId, pCol->type);
1946 1947
              taosArrayPush(pVals, &cv);
            } else {
1948
              SColVal cv = COL_VAL_VALUE(pCol->colId, pCol->type, (SValue){.val = *(int64_t*)var});
1949 1950 1951 1952 1953 1954 1955
              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)) {
1956
              SColVal cv = COL_VAL_NULL(pCol->colId, pCol->type);
1957 1958
              taosArrayPush(pVals, &cv);
            } else {
K
kailixu 已提交
1959
              void*   data = colDataGetVarData(pColInfoData, j);
1960
              SValue  sv = (SValue){.nData = varDataLen(data), .pData = varDataVal(data)};  // address copy, no value
1961
              SColVal cv = COL_VAL_VALUE(pCol->colId, pCol->type, sv);
1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
              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)) {
1977
                SColVal cv = COL_VAL_NULL(pCol->colId, pCol->type);  // should use pCol->type
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 2003 2004 2005 2006 2007
                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);
                }
2008
                SColVal cv = COL_VAL_VALUE(pCol->colId, pColInfoData->info.type, sv);
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018
                taosArrayPush(pVals, &cv);
              }
            } else {
              uError("the column type %" PRIi16 " is undefined\n", pColInfoData->info.type);
              ASSERT(0);
            }
            break;
        }
      }
      SRow* pRow = NULL;
2019
      if ((terrno = tRowBuild(pVals, pTSchema, &pRow)) < 0) {
2020
        tDestroySubmitTbData(&tbData, TSDB_MSG_FLG_ENCODE);
2021
        goto _end;
2022
      }
2023
      ASSERT(pRow);
K
kailixu 已提交
2024
      taosArrayPush(tbData.aRowP, &pRow);
2025
    }
2026

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

2038 2039
    return TSDB_CODE_FAILED;
  }
2040
  *ppReq = pReq;
2041 2042
  return TSDB_CODE_SUCCESS;
}
L
Liu Jicong 已提交
2043

L
Liu Jicong 已提交
2044
char* buildCtbNameByGroupId(const char* stbFullName, uint64_t groupId) {
L
liuyao 已提交
2045 2046 2047 2048 2049 2050 2051
  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 已提交
2052 2053
    return NULL;
  }
L
liuyao 已提交
2054 2055 2056 2057 2058 2059 2060
  return pBuf;
}

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

L
Liu Jicong 已提交
2062
  SArray* tags = taosArrayInit(0, sizeof(SSmlKv));
L
Liu Jicong 已提交
2063
  if (tags == NULL) {
L
liuyao 已提交
2064
    return TSDB_CODE_FAILED;
L
Liu Jicong 已提交
2065 2066 2067 2068
  }

  if (cname == NULL) {
    taosArrayDestroy(tags);
L
liuyao 已提交
2069
    return TSDB_CODE_FAILED;
L
Liu Jicong 已提交
2070 2071
  }

L
Liu Jicong 已提交
2072 2073 2074 2075
  SSmlKv pTag = {.key = "group_id",
                 .keyLen = sizeof("group_id") - 1,
                 .type = TSDB_DATA_TYPE_UBIGINT,
                 .u = groupId,
2076
                 .length = sizeof(uint64_t)};
2077 2078 2079 2080
  taosArrayPush(tags, &pTag);

  RandTableName rname = {
      .tags = tags,
L
Liu Jicong 已提交
2081 2082 2083
      .stbFullName = stbFullName,
      .stbFullNameLen = strlen(stbFullName),
      .ctbShortName = cname,
2084 2085 2086 2087 2088 2089
  };

  buildChildTableName(&rname);

  taosArrayDestroy(tags);

G
Ganlin Zhao 已提交
2090
  if ((rname.ctbShortName && rname.ctbShortName[0]) == 0) {
L
liuyao 已提交
2091
    return TSDB_CODE_FAILED;
G
Ganlin Zhao 已提交
2092
  }
L
liuyao 已提交
2093
  return TSDB_CODE_SUCCESS;
2094 2095
}

H
Haojun Liao 已提交
2096 2097 2098
int32_t blockEncode(const SSDataBlock* pBlock, char* data, int32_t numOfCols) {
  int32_t dataLen = 0;

2099
  // todo extract method
2100 2101 2102 2103
  int32_t* version = (int32_t*)data;
  *version = 1;
  data += sizeof(int32_t);

2104 2105 2106
  int32_t* actualLen = (int32_t*)data;
  data += sizeof(int32_t);

2107 2108 2109
  int32_t* rows = (int32_t*)data;
  *rows = pBlock->info.rows;
  data += sizeof(int32_t);
H
Haojun Liao 已提交
2110
  ASSERT(*rows > 0);
2111 2112 2113 2114 2115

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

2116 2117 2118
  // flag segment.
  // the inital bit is for column info
  int32_t* flagSegment = (int32_t*)data;
L
Liu Jicong 已提交
2119
  *flagSegment = (1 << 31);
2120

2121 2122
  data += sizeof(int32_t);

2123 2124 2125
  uint64_t* groupId = (uint64_t*)data;
  data += sizeof(uint64_t);

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

2129 2130
    *((int8_t*)data) = pColInfoData->info.type;
    data += sizeof(int8_t);
2131

L
Liu Jicong 已提交
2132
    *((int32_t*)data) = pColInfoData->info.bytes;
2133 2134 2135
    data += sizeof(int32_t);
  }

2136 2137 2138
  int32_t* colSizes = (int32_t*)data;
  data += numOfCols * sizeof(int32_t);

H
Haojun Liao 已提交
2139
  dataLen = blockDataGetSerialMetaSize(numOfCols);
2140 2141 2142 2143 2144 2145

  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
2146
    size_t metaSize = 0;
2147
    if (IS_VAR_DATA_TYPE(pColRes->info.type)) {
2148
      metaSize = numOfRows * sizeof(int32_t);
2149 2150
      memcpy(data, pColRes->varmeta.offset, metaSize);
    } else {
2151 2152
      metaSize = BitmapLen(numOfRows);
      memcpy(data, pColRes->nullbitmap, metaSize);
2153 2154
    }

2155
    data += metaSize;
H
Haojun Liao 已提交
2156
    dataLen += metaSize;
2157

D
dapan1121 已提交
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179
     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];
2180
    }
2181

2182
    colSizes[col] = htonl(colSizes[col]);
2183
//    uError("blockEncode col bytes:%d, type:%d, size:%d, htonl size:%d", pColRes->info.bytes, pColRes->info.type, htonl(colSizes[col]), colSizes[col]);
2184 2185
  }

H
Haojun Liao 已提交
2186
  *actualLen = dataLen;
H
Haojun Liao 已提交
2187
  *groupId = pBlock->info.id.groupId;
H
Haojun Liao 已提交
2188 2189
  ASSERT(dataLen > 0);
  return dataLen;
2190 2191
}

2192
const char* blockDecode(SSDataBlock* pBlock, const char* pData) {
2193 2194
  const char* pStart = pData;

L
Liu Jicong 已提交
2195
  int32_t version = *(int32_t*)pStart;
2196 2197 2198
  pStart += sizeof(int32_t);
  ASSERT(version == 1);

2199
  // total length sizeof(int32_t)
2200 2201 2202
  int32_t dataLen = *(int32_t*)pStart;
  pStart += sizeof(int32_t);

2203
  // total rows sizeof(int32_t)
L
Liu Jicong 已提交
2204
  int32_t numOfRows = *(int32_t*)pStart;
2205 2206 2207 2208 2209 2210 2211
  pStart += sizeof(int32_t);

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

  // has column info segment
2212 2213
  int32_t flagSeg = *(int32_t*)pStart;
  int32_t hasColumnInfo = (flagSeg >> 31);
2214 2215 2216
  pStart += sizeof(int32_t);

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

2220
  if (pBlock->pDataBlock == NULL) {
2221
    pBlock->pDataBlock = taosArrayInit_s(sizeof(SColumnInfoData), numOfCols);
2222 2223
  }

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

    pColInfoData->info.bytes = *(int32_t*)pStart;
    pStart += sizeof(int32_t);
2231 2232 2233 2234

    if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
      pBlock->info.hasVarCol = true;
    }
2235 2236 2237 2238
  }

  blockDataEnsureCapacity(pBlock, numOfRows);

2239 2240 2241 2242
  int32_t* colLen = (int32_t*)pStart;
  pStart += sizeof(int32_t) * numOfCols;

  for (int32_t i = 0; i < numOfCols; ++i) {
2243
    colLen[i] = htonl(colLen[i]);
2244 2245 2246 2247 2248 2249 2250
    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;

2251 2252 2253 2254 2255 2256 2257 2258
      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];
2259
      }
2260 2261

      pColInfoData->varmeta.length = colLen[i];
2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
    } 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];
  }

2278
  pBlock->info.dataLoad = 1;
2279
  pBlock->info.rows = numOfRows;
2280 2281
  ASSERT(pStart - pData == dataLen);
  return pStart;
L
Liu Jicong 已提交
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 2424 2425 2426 2427 2428

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