tdatablock.c 75.4 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
  pDst->info.rowSize = 0;
553 554
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
L
Liu Jicong 已提交
555
    SColumnInfoData  colInfo = {0};
556 557
    SColumnInfoData* pSrcCol = taosArrayGet(pBlock->pDataBlock, i);
    colInfo.info = pSrcCol->info;
558
    blockDataAppendColInfo(pDst, &colInfo);
559 560
  }

561 562 563
  blockDataEnsureCapacity(pDst, rowCount);

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

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

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

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

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

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

  char* pStart = buf + sizeof(uint32_t);

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

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

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

D
dapan1121 已提交
623 624 625 626 627 628 629 630 631 632 633 634 635
    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 已提交
636 637 638 639
      if (dataSize != 0) {
        // ubsan reports error if pCol->pData==NULL && dataSize==0
        memcpy(pStart, pCol->pData, dataSize);
      }
D
dapan1121 已提交
640
      pStart += dataSize;
H
Haojun Liao 已提交
641
    }
H
Haojun Liao 已提交
642 643 644 645 646
  }

  return 0;
}

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

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

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

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

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

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

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

  return TSDB_CODE_SUCCESS;
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 727
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;
}

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

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

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

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

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

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

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

  return TSDB_CODE_SUCCESS;
}

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

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

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

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

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

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

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

  return rowSize;
}

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

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

  SSDataBlock* pDataBlock = pHelper->pDataBlock;

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

  SArray* pInfo = pHelper->orderInfo;
840

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

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

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

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

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

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

  return 0;
}

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

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

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

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

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

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

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

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

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

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

  return pCols;
}

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

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

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

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

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

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

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

  return index;
}

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

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

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

  bool sortColumnHasNull = false;
  bool varTypeSort = false;

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

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

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

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

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

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

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

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

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

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

1030 1031
  int64_t p0 = taosGetTimestampUs();

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

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

1042 1043
  int64_t p1 = taosGetTimestampUs();

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

1051 1052
  int64_t p2 = taosGetTimestampUs();

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

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

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

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

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

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

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

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

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

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

1104 1105
  int32_t existedRows = pBlockInfo->rows;

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

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

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

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

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

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

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

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

  return TSDB_CODE_SUCCESS;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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 1344
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);
1345
    colDataSetVal(pDst, 0, pData, isNull);
1346 1347 1348 1349 1350 1351 1352
  }

  pBlock->info.rows = 1;

  return pBlock;
}

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

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

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

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

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

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

1390 1391 1392
  return pBlock;
}

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

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

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

  return col;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

K
kailixu 已提交
1888 1889
  terrno = TSDB_CODE_SUCCESS;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  buildChildTableName(&rname);

  taosArrayDestroy(tags);

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

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

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

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

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

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

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

2122 2123
  data += sizeof(int32_t);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  blockDataEnsureCapacity(pBlock, numOfRows);

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

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

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

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

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

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