tdatablock.c 85.7 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)) {
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
  }
}

H
Haojun Liao 已提交
50 51 52 53
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 {
54 55
    return ((pColumnInfoData->info.type == TSDB_DATA_TYPE_NULL) ? 0 : pColumnInfoData->info.bytes * numOfRows) +
           BitmapLen(numOfRows);
H
Haojun Liao 已提交
56 57 58
  }
}

H
Haojun Liao 已提交
59 60 61 62
void colDataTrim(SColumnInfoData* pColumnInfoData) {
  // TODO
}

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

81 82 83 84
int32_t colDataAppend(SColumnInfoData* pColumnInfoData, uint32_t rowIndex, const char* pData, bool isNull) {
  return colDataSetVal(pColumnInfoData, rowIndex, pData, isNull);
}

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

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

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

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

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

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

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

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

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

  return 0;
}

D
dapan1121 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155
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];
156
    pColumnInfoData->reassigned = true;
D
dapan1121 已提交
157 158 159 160 161 162 163 164 165
  } else {
    memcpy(pColumnInfoData->pData + pColumnInfoData->info.bytes * dstRowIdx, pData, pColumnInfoData->info.bytes);
    colDataClearNull_f(pColumnInfoData->nullbitmap, dstRowIdx);
  }

  return 0;
}


166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
int32_t colDataReserve(SColumnInfoData* pColumnInfoData, size_t newSize) {
  if (!IS_VAR_DATA_TYPE(pColumnInfoData->info.type)) {
    return TSDB_CODE_SUCCESS;
  }

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

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

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

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
188 189 190 191 192 193 194 195 196 197 198
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 已提交
199 200 201 202 203 204
  size_t start = 1;

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

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

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

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

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

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
229 230
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      *capacity = finalNumOfRows;
H
Haojun Liao 已提交
361 362
    }

363 364
    doBitmapMerge(pColumnInfoData, numOfRow1, pSource, numOfRow2);

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

  return numOfRow1 + numOfRow2;
}

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

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

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

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

407 408
  pColumnInfoData->hasNull = pSource->hasNull;
  pColumnInfoData->info = pSource->info;
409 410 411
  return 0;
}

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

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

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

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

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

430 431
  int32_t index = (tsColumnIndex == -1) ? 0 : tsColumnIndex;

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

437 438 439 440 441 442
  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);

443 444 445
  return 0;
}

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

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

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

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

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

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

H
Haojun Liao 已提交
481 482
  int32_t bitmapChar = 1;

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

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

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

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

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

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

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

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

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

537 538 539 540 541
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;
  }

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

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

558 559 560
  blockDataEnsureCapacity(pDst, rowCount);

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

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

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

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

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

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

  char* pStart = buf + sizeof(uint32_t);

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

615
    uint32_t dataSize = colDataGetLength(pCol, numOfRows);
616

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

620 621 622 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 {
      memcpy(pStart, pCol->pData, dataSize);
      pStart += dataSize;
    }    
H
Haojun Liao 已提交
636 637 638 639 640
  }

  return 0;
}

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

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

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

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

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

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

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

    memcpy(pCol->pData, pStart, colLength);
    pStart += colLength;
  }
689 690

  return TSDB_CODE_SUCCESS;
691 692
}

693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
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;
}

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

725 726
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);

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

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

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

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

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

  return TSDB_CODE_SUCCESS;
}

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

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

    pBlock->info.rowSize = rowSize;
H
Haojun Liao 已提交
783 784
  }

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

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

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

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

  return rowSize;
}

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

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

  SSDataBlock* pDataBlock = pHelper->pDataBlock;

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

  SArray* pInfo = pHelper->orderInfo;
832

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

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

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

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

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

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

  return 0;
}

L
Liu Jicong 已提交
874 875
static int32_t doAssignOneTuple(SColumnInfoData* pDstCols, int32_t numOfRows, const SSDataBlock* pSrcBlock,
                                int32_t tupleIndex) {
H
Haojun Liao 已提交
876
  int32_t code = 0;
L
Liu Jicong 已提交
877
  size_t  numOfCols = taosArrayGetSize(pSrcBlock->pDataBlock);
H
Haojun Liao 已提交
878 879 880 881 882

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

883
    if (pSrc->hasNull && colDataIsNull(pSrc, pSrcBlock->info.rows, tupleIndex, pSrcBlock->pBlockAgg[i])) {
884
      code = colDataSetVal(pDst, numOfRows, NULL, true);
H
Haojun Liao 已提交
885 886 887
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
H
Haojun Liao 已提交
888
    } else {
889
      char* p = colDataGetData(pSrc, tupleIndex);
890
      code = colDataSetVal(pDst, numOfRows, p, false);
H
Haojun Liao 已提交
891 892 893
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
H
Haojun Liao 已提交
894 895
    }
  }
896 897

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
898 899
}

900
static int32_t blockDataAssign(SColumnInfoData* pCols, const SSDataBlock* pDataBlock, const int32_t* index) {
H
Haojun Liao 已提交
901
#if 0
H
Haojun Liao 已提交
902
  for (int32_t i = 0; i < pDataBlock->info.rows; ++i) {
H
Haojun Liao 已提交
903 904 905 906
    int32_t code = doAssignOneTuple(pCols, i, pDataBlock, index[i]);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
H
Haojun Liao 已提交
907
  }
H
Haojun Liao 已提交
908
#else
909 910
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
911 912 913 914
    SColumnInfoData* pDst = &pCols[i];
    SColumnInfoData* pSrc = taosArrayGet(pDataBlock->pDataBlock, i);

    if (IS_VAR_DATA_TYPE(pSrc->info.type)) {
915 916 917
      if (pSrc->varmeta.length != 0) {
        memcpy(pDst->pData, pSrc->pData, pSrc->varmeta.length);
      }
L
Liu Jicong 已提交
918
      pDst->varmeta.length = pSrc->varmeta.length;
H
Haojun Liao 已提交
919

L
Liu Jicong 已提交
920 921 922
      for (int32_t j = 0; j < pDataBlock->info.rows; ++j) {
        pDst->varmeta.offset[j] = pSrc->varmeta.offset[index[j]];
      }
H
Haojun Liao 已提交
923
    } else {
wmmhello's avatar
wmmhello 已提交
924 925
      for (int32_t j = 0; j < pDataBlock->info.rows; ++j) {
        if (colDataIsNull_f(pSrc->nullbitmap, index[j])) {
926
          colDataSetNull_f_s(pDst, j);
wmmhello's avatar
wmmhello 已提交
927
          continue;
H
Haojun Liao 已提交
928
        }
wmmhello's avatar
wmmhello 已提交
929
        memcpy(pDst->pData + j * pDst->info.bytes, pSrc->pData + index[j] * pDst->info.bytes, pDst->info.bytes);
H
Haojun Liao 已提交
930 931 932 933
      }
    }
  }
#endif
H
Haojun Liao 已提交
934
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
935 936 937
}

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

wafwerar's avatar
wafwerar 已提交
941
  SColumnInfoData* pCols = taosMemoryCalloc(numOfCols, sizeof(SColumnInfoData));
H
Haojun Liao 已提交
942 943 944 945
  if (pCols == NULL) {
    return NULL;
  }

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

    if (IS_VAR_DATA_TYPE(pCols[i].info.type)) {
wafwerar's avatar
wafwerar 已提交
951 952
      pCols[i].varmeta.offset = taosMemoryCalloc(rows, sizeof(int32_t));
      pCols[i].pData = taosMemoryCalloc(1, pColInfoData->varmeta.length);
H
Haojun Liao 已提交
953 954 955

      pCols[i].varmeta.length = pColInfoData->varmeta.length;
      pCols[i].varmeta.allocLen = pCols[i].varmeta.length;
H
Haojun Liao 已提交
956
    } else {
wafwerar's avatar
wafwerar 已提交
957 958
      pCols[i].nullbitmap = taosMemoryCalloc(1, BitmapLen(rows));
      pCols[i].pData = taosMemoryCalloc(rows, pCols[i].info.bytes);
H
Haojun Liao 已提交
959 960 961 962 963 964
    }
  }

  return pCols;
}

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

L
Liu Jicong 已提交
968
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
969 970 971 972
    SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, i);
    pColInfoData->info = pCols[i].info;

    if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
wafwerar's avatar
wafwerar 已提交
973
      taosMemoryFreeClear(pColInfoData->varmeta.offset);
H
Haojun Liao 已提交
974 975
      pColInfoData->varmeta = pCols[i].varmeta;
    } else {
wafwerar's avatar
wafwerar 已提交
976
      taosMemoryFreeClear(pColInfoData->nullbitmap);
H
Haojun Liao 已提交
977 978 979
      pColInfoData->nullbitmap = pCols[i].nullbitmap;
    }

wafwerar's avatar
wafwerar 已提交
980
    taosMemoryFreeClear(pColInfoData->pData);
H
Haojun Liao 已提交
981 982 983
    pColInfoData->pData = pCols[i].pData;
  }

wafwerar's avatar
wafwerar 已提交
984
  taosMemoryFreeClear(pCols);
H
Haojun Liao 已提交
985 986 987
}

static int32_t* createTupleIndex(size_t rows) {
wafwerar's avatar
wafwerar 已提交
988
  int32_t* index = taosMemoryCalloc(rows, sizeof(int32_t));
H
Haojun Liao 已提交
989 990 991 992
  if (index == NULL) {
    return NULL;
  }

L
Liu Jicong 已提交
993
  for (int32_t i = 0; i < rows; ++i) {
H
Haojun Liao 已提交
994 995 996 997 998 999
    index[i] = i;
  }

  return index;
}

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

H
Haojun Liao 已提交
1002
int32_t blockDataSort(SSDataBlock* pDataBlock, SArray* pOrderInfo) {
H
Haojun Liao 已提交
1003 1004 1005 1006 1007 1008
  if (pDataBlock->info.rows <= 1) {
    return TSDB_CODE_SUCCESS;
  }

  // Allocate the additional buffer.
  uint32_t rows = pDataBlock->info.rows;
H
Haojun Liao 已提交
1009 1010 1011 1012 1013 1014 1015

  bool sortColumnHasNull = false;
  bool varTypeSort = false;

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

H
Haojun Liao 已提交
1016
    SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, pInfo->slotId);
H
Haojun Liao 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025
    if (pColInfoData->hasNull) {
      sortColumnHasNull = true;
    }

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

1026 1027
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);

H
Haojun Liao 已提交
1028
  if (taosArrayGetSize(pOrderInfo) == 1 && (!sortColumnHasNull)) {
1029
    if (numOfCols == 1) {
H
Haojun Liao 已提交
1030 1031 1032 1033 1034
      if (!varTypeSort) {
        SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, 0);
        SBlockOrderInfo* pOrder = taosArrayGet(pOrderInfo, 0);

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

1036
        __compar_fn_t fn = getKeyComparFunc(pColInfoData->info.type, pOrder->order);
wafwerar's avatar
wafwerar 已提交
1037
        taosSort(pColInfoData->pData, pDataBlock->info.rows, pColInfoData->info.bytes, fn);
H
Haojun Liao 已提交
1038 1039

        int64_t p1 = taosGetTimestampUs();
D
dapan1121 已提交
1040
        uDebug("blockDataSort easy cost:%" PRId64 ", rows:%" PRId64 "\n", p1 - p0, pDataBlock->info.rows);
H
Haojun Liao 已提交
1041 1042 1043 1044

        return TSDB_CODE_SUCCESS;
      } else {  // var data type
      }
1045
    } else if (numOfCols == 2) {
H
Haojun Liao 已提交
1046 1047 1048
    }
  }

H
Haojun Liao 已提交
1049 1050 1051 1052 1053 1054
  int32_t* index = createTupleIndex(rows);
  if (index == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

1055 1056
  int64_t p0 = taosGetTimestampUs();

H
Haojun Liao 已提交
1057
  SSDataBlockSortHelper helper = {.pDataBlock = pDataBlock, .orderInfo = pOrderInfo};
L
Liu Jicong 已提交
1058
  for (int32_t i = 0; i < taosArrayGetSize(helper.orderInfo); ++i) {
H
Haojun Liao 已提交
1059
    struct SBlockOrderInfo* pInfo = taosArrayGet(helper.orderInfo, i);
H
Haojun Liao 已提交
1060
    pInfo->pColData = taosArrayGet(pDataBlock->pDataBlock, pInfo->slotId);
H
Haojun Liao 已提交
1061 1062
  }

X
Xiaoyu Wang 已提交
1063
  terrno = 0;
H
Haojun Liao 已提交
1064
  taosqsort(index, rows, sizeof(int32_t), &helper, dataBlockCompar);
X
Xiaoyu Wang 已提交
1065
  if (terrno) return terrno;
H
Haojun Liao 已提交
1066

1067 1068
  int64_t p1 = taosGetTimestampUs();

H
Haojun Liao 已提交
1069 1070
  SColumnInfoData* pCols = createHelpColInfoData(pDataBlock);
  if (pCols == NULL) {
1071
    destroyTupleIndex(index);
H
Haojun Liao 已提交
1072 1073 1074 1075
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

1076 1077
  int64_t p2 = taosGetTimestampUs();

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

1080
  int64_t p3 = taosGetTimestampUs();
H
Haojun Liao 已提交
1081 1082

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

C
Cary Xu 已提交
1085 1086 1087
  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 已提交
1088
  destroyTupleIndex(index);
H
Haojun Liao 已提交
1089 1090

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1091
}
1092

1093
#if 0
H
Haojun Liao 已提交
1094 1095
typedef struct SHelper {
  int32_t index;
L
Liu Jicong 已提交
1096 1097 1098 1099 1100
  union {
    char*   pData;
    int64_t i64;
    double  d64;
  };
H
Haojun Liao 已提交
1101 1102 1103 1104 1105 1106
} SHelper;

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

L
Liu Jicong 已提交
1107
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
1108
    SBlockOrderInfo* pInfo = taosArrayGet(pOrderInfo, i);
H
Haojun Liao 已提交
1109
    SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, pInfo->slotId);
H
Haojun Liao 已提交
1110 1111 1112 1113 1114 1115
    pInfo->pColData = pColInfo;
    sortValLengthPerRow += pColInfo->info.bytes;
  }

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

wafwerar's avatar
wafwerar 已提交
1116 1117
  char*    buf = taosMemoryCalloc(1, len);
  SHelper* phelper = taosMemoryCalloc(numOfRows, sizeof(SHelper));
L
Liu Jicong 已提交
1118
  for (int32_t i = 0; i < numOfRows; ++i) {
H
Haojun Liao 已提交
1119 1120 1121 1122 1123
    phelper[i].index = i;
    phelper[i].pData = buf + sortValLengthPerRow * i;
  }

  int32_t offset = 0;
L
Liu Jicong 已提交
1124
  for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
1125
    SBlockOrderInfo* pInfo = taosArrayGet(pOrderInfo, i);
L
Liu Jicong 已提交
1126 1127 1128 1129
    for (int32_t j = 0; j < numOfRows; ++j) {
      phelper[j].i64 = *(int32_t*)pInfo->pColData->pData + pInfo->pColData->info.bytes * j;
      //      memcpy(phelper[j].pData + offset, pInfo->pColData->pData + pInfo->pColData->info.bytes * j,
      //      pInfo->pColData->info.bytes);
H
Haojun Liao 已提交
1130 1131 1132 1133 1134
    }

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

H
Haojun Liao 已提交
1135
  taosMemoryFree(buf);
H
Haojun Liao 已提交
1136 1137 1138 1139
  return phelper;
}

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

L
Liu Jicong 已提交
1142 1143
  SHelper* left = (SHelper*)p1;
  SHelper* right = (SHelper*)p2;
H
Haojun Liao 已提交
1144 1145 1146 1147

  SArray* pInfo = pHelper->orderInfo;

  int32_t offset = 0;
L
Liu Jicong 已提交
1148 1149 1150 1151 1152 1153 1154
  int32_t leftx = *(int32_t*)left->pData;    //*(int32_t*)(left->pData + offset);
  int32_t rightx = *(int32_t*)right->pData;  //*(int32_t*)(right->pData + offset);

  if (leftx == rightx) {
    return 0;
  } else {
    return (leftx < rightx) ? -1 : 1;
1155
  }
H
Haojun Liao 已提交
1156 1157 1158 1159
  return 0;
}

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

H
Haojun Liao 已提交
1163
  SSDataBlockSortHelper helper = {.pDataBlock = pDataBlock, .orderInfo = pOrderInfo};
H
Haojun Liao 已提交
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173

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

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

L
Liu Jicong 已提交
1174
  int64_t          p1 = taosGetTimestampUs();
H
Haojun Liao 已提交
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
  SColumnInfoData* pCols = createHelpColInfoData(pDataBlock);
  if (pCols == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return terrno;
  }

  int64_t p2 = taosGetTimestampUs();

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

  int64_t p3 = taosGetTimestampUs();

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

L
Liu Jicong 已提交
1194 1195
  printf("sort:%" PRId64 ", create:%" PRId64 ", assign:%" PRId64 ", copyback:%" PRId64 ", rows:%d\n", p1 - p0, p2 - p1,
         p3 - p2, p4 - p3, rows);
H
Haojun Liao 已提交
1196
  //  destroyTupleIndex(index);
1197
  return 0;
H
Haojun Liao 已提交
1198
}
1199
#endif
H
Haojun Liao 已提交
1200

1201
void blockDataCleanup(SSDataBlock* pDataBlock) {
H
Haojun Liao 已提交
1202
  blockDataEmpty(pDataBlock);
H
Haojun Liao 已提交
1203
  SDataBlockInfo* pInfo = &pDataBlock->info;
H
Haojun Liao 已提交
1204 1205
  pInfo->id.uid = 0;
  pInfo->id.groupId = 0;
H
Haojun Liao 已提交
1206
}
1207

H
Haojun Liao 已提交
1208 1209
void blockDataEmpty(SSDataBlock* pDataBlock) {
  SDataBlockInfo* pInfo = &pDataBlock->info;
D
dapan1121 已提交
1210
  if (pInfo->capacity == 0) {
1211 1212 1213
    return;
  }

1214 1215
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
1216
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
H
Haojun Liao 已提交
1217
    colInfoDataCleanup(p, pInfo->capacity);
1218
  }
H
Haojun Liao 已提交
1219 1220

  pInfo->rows = 0;
1221
  pInfo->dataLoad = 0;
H
Haojun Liao 已提交
1222 1223
  pInfo->window.ekey = 0;
  pInfo->window.skey = 0;
1224 1225
}

1226 1227 1228 1229 1230
/*
 * 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 已提交
1231 1232
static int32_t doEnsureCapacity(SColumnInfoData* pColumn, const SDataBlockInfo* pBlockInfo, uint32_t numOfRows,
                                bool clearPayload) {
G
Ganlin Zhao 已提交
1233
  if (numOfRows <= 0 || numOfRows <= pBlockInfo->capacity) {
X
Xiaoyu Wang 已提交
1234 1235 1236
    return TSDB_CODE_SUCCESS;
  }

1237 1238
  int32_t existedRows = pBlockInfo->rows;

D
dapan1121 已提交
1239
  if (IS_VAR_DATA_TYPE(pColumn->info.type)) {
wafwerar's avatar
wafwerar 已提交
1240
    char* tmp = taosMemoryRealloc(pColumn->varmeta.offset, sizeof(int32_t) * numOfRows);
D
dapan1121 已提交
1241 1242 1243
    if (tmp == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
1244

D
dapan1121 已提交
1245
    pColumn->varmeta.offset = (int32_t*)tmp;
1246
    memset(&pColumn->varmeta.offset[existedRows], 0, sizeof(int32_t) * (numOfRows - existedRows));
D
dapan1121 已提交
1247
  } else {
1248
    // prepare for the null bitmap
wafwerar's avatar
wafwerar 已提交
1249
    char* tmp = taosMemoryRealloc(pColumn->nullbitmap, BitmapLen(numOfRows));
D
dapan1121 已提交
1250 1251 1252
    if (tmp == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
1253

1254
    int32_t oldLen = BitmapLen(existedRows);
D
dapan1121 已提交
1255
    pColumn->nullbitmap = tmp;
1256
    memset(&pColumn->nullbitmap[oldLen], 0, BitmapLen(numOfRows) - oldLen);
G
Ganlin Zhao 已提交
1257 1258 1259
    if (pColumn->info.bytes == 0) {
      return TSDB_CODE_FAILED;
    }
1260

1261 1262
    // here we employ the aligned malloc function, to make sure that the address of allocated memory is aligned
    // to MALLOC_ALIGN_BYTES
1263
    tmp = taosMemoryMallocAlign(MALLOC_ALIGN_BYTES, numOfRows * pColumn->info.bytes);
D
dapan1121 已提交
1264 1265 1266
    if (tmp == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
L
Liu Jicong 已提交
1267

1268 1269 1270 1271 1272 1273
    // copy back the existed data
    if (pColumn->pData != NULL) {
      memcpy(tmp, pColumn->pData, existedRows * pColumn->info.bytes);
      taosMemoryFreeClear(pColumn->pData);
    }

D
dapan1121 已提交
1274
    pColumn->pData = tmp;
1275

1276
    // check if the allocated memory is aligned to the requried bytes.
1277
#if defined LINUX
G
Ganlin Zhao 已提交
1278 1279 1280
    if ((((uint64_t)pColumn->pData) & (MALLOC_ALIGN_BYTES - 1)) != 0x0) {
      return TSDB_CODE_FAILED;
    }
1281
#endif
H
Haojun Liao 已提交
1282

H
Haojun Liao 已提交
1283 1284 1285
    if (clearPayload) {
      memset(tmp + pColumn->info.bytes * existedRows, 0, pColumn->info.bytes * (numOfRows - existedRows));
    }
D
dapan1121 已提交
1286 1287 1288 1289 1290
  }

  return TSDB_CODE_SUCCESS;
}

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

1294 1295
  if (IS_VAR_DATA_TYPE(pColumn->info.type)) {
    pColumn->varmeta.length = 0;
1296
    if (pColumn->varmeta.offset != NULL) {
H
Haojun Liao 已提交
1297 1298
      memset(pColumn->varmeta.offset, 0, sizeof(int32_t) * numOfRows);
    }
1299
  } else {
dengyihao's avatar
dengyihao 已提交
1300 1301 1302
    if (pColumn->nullbitmap != NULL) {
      memset(pColumn->nullbitmap, 0, BitmapLen(numOfRows));
    }
1303 1304 1305
  }
}

H
Haojun Liao 已提交
1306
int32_t colInfoDataEnsureCapacity(SColumnInfoData* pColumn, uint32_t numOfRows, bool clearPayload) {
1307
  SDataBlockInfo info = {0};
H
Haojun Liao 已提交
1308
  return doEnsureCapacity(pColumn, &info, numOfRows, clearPayload);
1309 1310
}

D
dapan1121 已提交
1311 1312
int32_t blockDataEnsureCapacity(SSDataBlock* pDataBlock, uint32_t numOfRows) {
  int32_t code = 0;
H
Haojun Liao 已提交
1313
  if (numOfRows == 0 || numOfRows <= pDataBlock->info.capacity) {
H
Haojun Liao 已提交
1314 1315
    return TSDB_CODE_SUCCESS;
  }
L
Liu Jicong 已提交
1316

1317 1318
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
  for (int32_t i = 0; i < numOfCols; ++i) {
D
dapan1121 已提交
1319
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
H
Haojun Liao 已提交
1320
    code = doEnsureCapacity(p, &pDataBlock->info, numOfRows, false);
D
dapan1121 已提交
1321 1322
    if (code) {
      return code;
1323 1324
    }
  }
H
Haojun Liao 已提交
1325

H
Haojun Liao 已提交
1326
  pDataBlock->info.capacity = numOfRows;
H
Haojun Liao 已提交
1327 1328 1329
  return TSDB_CODE_SUCCESS;
}

1330 1331 1332 1333 1334 1335 1336 1337
void blockDataFreeRes(SSDataBlock* pBlock) {
  int32_t numOfOutput = taosArrayGetSize(pBlock->pDataBlock);
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SColumnInfoData* pColInfoData = (SColumnInfoData*)taosArrayGet(pBlock->pDataBlock, i);
    colDataDestroy(pColInfoData);
  }

  taosArrayDestroy(pBlock->pDataBlock);
wmmhello's avatar
wmmhello 已提交
1338
  pBlock->pDataBlock = NULL;
1339 1340 1341 1342
  taosMemoryFreeClear(pBlock->pBlockAgg);
  memset(&pBlock->info, 0, sizeof(SDataBlockInfo));
}

H
Haojun Liao 已提交
1343 1344 1345 1346 1347
void* blockDataDestroy(SSDataBlock* pBlock) {
  if (pBlock == NULL) {
    return NULL;
  }

1348
  blockDataFreeRes(pBlock);
wafwerar's avatar
wafwerar 已提交
1349
  taosMemoryFreeClear(pBlock);
H
Haojun Liao 已提交
1350
  return NULL;
D
dapan1121 已提交
1351
}
1352

L
Liu Jicong 已提交
1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
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 已提交
1374
    if (pSrc->pData == NULL && (!IS_VAR_DATA_TYPE(pSrc->info.type))) {
L
Liu Jicong 已提交
1375 1376 1377 1378 1379 1380
      continue;
    }

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

1381
  uint32_t cap = dst->info.capacity;
1382
  dst->info = src->info;
1383
  dst->info.capacity = cap;
L
Liu Jicong 已提交
1384 1385
  return 0;
}
1386

5
54liuyao 已提交
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
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 已提交
1401

1402
  uint32_t cap = dst->info.capacity;
1403
  dst->info = src->info;
1404
  dst->info.capacity = cap;
5
54liuyao 已提交
1405 1406 1407
  return TSDB_CODE_SUCCESS;
}

L
Liu Jicong 已提交
1408 1409 1410
SSDataBlock* createSpecialDataBlock(EStreamType type) {
  SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
  pBlock->info.hasVarCol = false;
H
Haojun Liao 已提交
1411
  pBlock->info.id.groupId = 0;
L
Liu Jicong 已提交
1412 1413
  pBlock->info.rows = 0;
  pBlock->info.type = type;
1414
  pBlock->info.rowSize = sizeof(TSKEY) + sizeof(TSKEY) + sizeof(uint64_t) + sizeof(uint64_t) + sizeof(TSKEY) +
L
Liu Jicong 已提交
1415
                         sizeof(TSKEY) + VARSTR_HEADER_SIZE + TSDB_TABLE_NAME_LEN;
L
Liu Jicong 已提交
1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433
  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);

1434 1435
  infoData.info.type = TSDB_DATA_TYPE_TIMESTAMP;
  infoData.info.bytes = sizeof(TSKEY);
L
Liu Jicong 已提交
1436 1437 1438 1439 1440
  // calculate start ts
  taosArrayPush(pBlock->pDataBlock, &infoData);
  // calculate end ts
  taosArrayPush(pBlock->pDataBlock, &infoData);

1441 1442
  // table name
  infoData.info.type = TSDB_DATA_TYPE_VARCHAR;
L
Liu Jicong 已提交
1443
  infoData.info.bytes = VARSTR_HEADER_SIZE + TSDB_TABLE_NAME_LEN;
1444 1445
  taosArrayPush(pBlock->pDataBlock, &infoData);

L
Liu Jicong 已提交
1446 1447 1448
  return pBlock;
}

1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
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);
1478
    colDataSetVal(pDst, 0, pData, isNull);
1479 1480 1481 1482 1483 1484 1485
  }

  pBlock->info.rows = 1;

  return pBlock;
}

1486
SSDataBlock* createOneDataBlock(const SSDataBlock* pDataBlock, bool copyData) {
C
Cary Xu 已提交
1487
  if (pDataBlock == NULL) {
1488 1489
    return NULL;
  }
1490

1491 1492 1493 1494
  SSDataBlock* pBlock = createDataBlock();
  pBlock->info = pDataBlock->info;
  pBlock->info.rows = 0;
  pBlock->info.capacity = 0;
1495
  pBlock->info.rowSize = 0;
1496
  pBlock->info.id = pDataBlock->info.id;
1497

1498
  size_t numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
L
Liu Jicong 已提交
1499
  for (int32_t i = 0; i < numOfCols; ++i) {
1500
    SColumnInfoData* p = taosArrayGet(pDataBlock->pDataBlock, i);
1501 1502
    SColumnInfoData  colInfo = {.hasNull = true, .info = p->info};
    blockDataAppendColInfo(pBlock, &colInfo);
1503 1504
  }

1505
  if (copyData) {
1506 1507 1508 1509 1510 1511 1512
    int32_t code = blockDataEnsureCapacity(pBlock, pDataBlock->info.rows);
    if (code != TSDB_CODE_SUCCESS) {
      terrno = code;
      blockDataDestroy(pBlock);
      return NULL;
    }

1513 1514 1515
    for (int32_t i = 0; i < numOfCols; ++i) {
      SColumnInfoData* pDst = taosArrayGet(pBlock->pDataBlock, i);
      SColumnInfoData* pSrc = taosArrayGet(pDataBlock->pDataBlock, i);
1516
      colDataAssign(pDst, pSrc, pDataBlock->info.rows, &pDataBlock->info);
1517 1518 1519 1520 1521 1522
    }

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

1523 1524 1525
  return pBlock;
}

1526 1527 1528 1529
SSDataBlock* createDataBlock() {
  SSDataBlock* pBlock = taosMemoryCalloc(1, sizeof(SSDataBlock));
  if (pBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
1530
    return NULL;
1531 1532 1533 1534 1535 1536
  }

  pBlock->pDataBlock = taosArrayInit(4, sizeof(SColumnInfoData));
  if (pBlock->pDataBlock == NULL) {
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    taosMemoryFree(pBlock);
wmmhello's avatar
wmmhello 已提交
1537
    return NULL;
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557
  }

  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 已提交
1558
  // todo disable it temporarily
L
Liu Jicong 已提交
1559
  //  ASSERT(pColInfoData->info.type != 0);
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
  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 已提交
1571
  col.info.type = type;
1572 1573 1574 1575 1576
  col.info.bytes = bytes;

  return col;
}

L
Liu Jicong 已提交
1577
SColumnInfoData* bdGetColumnInfoData(const SSDataBlock* pBlock, int32_t index) {
1578 1579 1580 1581 1582 1583 1584
  if (index >= taosArrayGetSize(pBlock->pDataBlock)) {
    return NULL;
  }

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

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

G
Ganlin Zhao 已提交
1588
  int32_t payloadSize = pageSize - extraSize;
1589 1590
  int32_t rowSize = pBlock->info.rowSize;
  int32_t nRows = payloadSize / rowSize;
H
Haojun Liao 已提交
1591
  ASSERT(nRows >= 1);
1592

1593 1594
  int32_t numVarCols = 0;
  int32_t numFixCols = 0;
1595
  for (int32_t i = 0; i < numOfCols; ++i) {
1596 1597
    SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, i);
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
      ++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;
1615
    } else {
1616
      start = mid + 1;
1617 1618 1619
    }
  }

1620 1621
  int32_t newRows = (result != -1) ? result - 1 : nRows;
  // the true value must be less than the value of nRows
1622
  ASSERT(newRows <= nRows && newRows >= 1);
1623 1624

  return newRows;
1625
}
H
Haojun Liao 已提交
1626

1627
void colDataDestroy(SColumnInfoData* pColData) {
1628 1629 1630 1631
  if (!pColData) {
    return;
  }

1632
  if (IS_VAR_DATA_TYPE(pColData->info.type)) {
wmmhello's avatar
wmmhello 已提交
1633
    taosMemoryFreeClear(pColData->varmeta.offset);
1634
  } else {
wmmhello's avatar
wmmhello 已提交
1635
    taosMemoryFreeClear(pColData->nullbitmap);
1636 1637
  }

wmmhello's avatar
wmmhello 已提交
1638
  taosMemoryFreeClear(pColData->pData);
1639 1640
}

H
Haojun Liao 已提交
1641 1642 1643 1644
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 已提交
1645 1646
  if (n % 8 == 0) {
    memmove(nullBitmap, nullBitmap + n / 8, newLen);
H
Haojun Liao 已提交
1647
  } else {
1648
    int32_t  tail = n % 8;
1649
    int32_t  i = 0;
C
Cary Xu 已提交
1650
    uint8_t* p = (uint8_t*)nullBitmap;
H
Haojun Liao 已提交
1651

1652 1653 1654 1655 1656 1657 1658 1659 1660
    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 已提交
1661

1662
        i += 1;
H
Haojun Liao 已提交
1663
      }
1664
    } else if (n > 8) {
1665
      int32_t remain = (total % 8 != 0 && total % 8 <= tail) ? 1 : 0;
1666
      int32_t gap = len - newLen - remain;
1667
      while (i < newLen) {
1668 1669 1670
        uint8_t v = p[i + gap];
        p[i] = (v << tail);

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

1676 1677
        i += 1;
      }
H
Haojun Liao 已提交
1678 1679 1680 1681
    }
  }
}

X
Xiaoyu Wang 已提交
1682
static int32_t colDataMoveVarData(SColumnInfoData* pColInfoData, size_t start, size_t end) {
wmmhello's avatar
wmmhello 已提交
1683 1684 1685
  int32_t dataOffset = -1;
  int32_t dataLen = 0;
  int32_t beigin = start;
X
Xiaoyu Wang 已提交
1686
  while (beigin < end) {
wmmhello's avatar
wmmhello 已提交
1687
    int32_t offset = pColInfoData->varmeta.offset[beigin];
X
Xiaoyu Wang 已提交
1688
    if (offset == -1) {
wmmhello's avatar
wmmhello 已提交
1689 1690 1691
      beigin++;
      continue;
    }
X
Xiaoyu Wang 已提交
1692
    if (start != 0) {
wmmhello's avatar
wmmhello 已提交
1693 1694
      pColInfoData->varmeta.offset[beigin] = dataLen;
    }
X
Xiaoyu Wang 已提交
1695 1696
    char* data = pColInfoData->pData + offset;
    if (dataOffset == -1) dataOffset = offset;  // mark the begin of data
wmmhello's avatar
wmmhello 已提交
1697 1698 1699 1700 1701 1702 1703 1704
    int32_t type = pColInfoData->info.type;
    if (type == TSDB_DATA_TYPE_JSON) {
      dataLen += getJsonValueLen(data);
    } else {
      dataLen += varDataTLen(data);
    }
    beigin++;
  }
1705

X
Xiaoyu Wang 已提交
1706
  if (dataOffset > 0) {
wmmhello's avatar
wmmhello 已提交
1707 1708
    memmove(pColInfoData->pData, pColInfoData->pData + dataOffset, dataLen);
  }
1709 1710

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

H
Haojun Liao 已提交
1714 1715
static void colDataTrimFirstNRows(SColumnInfoData* pColInfoData, size_t n, size_t total) {
  if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
wmmhello's avatar
wmmhello 已提交
1716
    pColInfoData->varmeta.length = colDataMoveVarData(pColInfoData, n, total);
H
Haojun Liao 已提交
1717 1718

    // clear the offset value of the unused entries.
1719
    memset(&pColInfoData->varmeta.offset[total - n], 0, n);
H
Haojun Liao 已提交
1720 1721 1722 1723 1724 1725 1726
  } else {
    int32_t bytes = pColInfoData->info.bytes;
    memmove(pColInfoData->pData, ((char*)pColInfoData->pData + n * bytes), (total - n) * bytes);
    doShiftBitmap(pColInfoData->nullbitmap, n, total);
  }
}

1727
int32_t blockDataTrimFirstRows(SSDataBlock* pBlock, size_t n) {
H
Haojun Liao 已提交
1728 1729 1730 1731 1732
  if (n == 0) {
    return TSDB_CODE_SUCCESS;
  }

  if (pBlock->info.rows <= n) {
H
Haojun Liao 已提交
1733
    blockDataEmpty(pBlock);
H
Haojun Liao 已提交
1734
  } else {
1735 1736
    size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
    for (int32_t i = 0; i < numOfCols; ++i) {
H
Haojun Liao 已提交
1737 1738 1739 1740 1741 1742 1743 1744 1745
      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
      colDataTrimFirstNRows(pColInfoData, n, pBlock->info.rows);
    }

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

wmmhello's avatar
wmmhello 已提交
1746 1747
static void colDataKeepFirstNRows(SColumnInfoData* pColInfoData, size_t n, size_t total) {
  if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
wmmhello's avatar
wmmhello 已提交
1748
    pColInfoData->varmeta.length = colDataMoveVarData(pColInfoData, 0, n);
wmmhello's avatar
wmmhello 已提交
1749
    memset(&pColInfoData->varmeta.offset[n], 0, total - n);
H
Haojun Liao 已提交
1750
  } else {  // reset the bitmap value
1751 1752
    /*int32_t stopIndex = BitmapLen(n) * 8;
    for(int32_t i = n; i < stopIndex; ++i) {
H
Haojun Liao 已提交
1753 1754 1755 1756 1757
      colDataClearNull_f(pColInfoData->nullbitmap, i);
    }

    int32_t remain = BitmapLen(total) - BitmapLen(n);
    if (remain > 0) {
1758 1759
      memset(pColInfoData->nullbitmap+BitmapLen(n), 0, remain);
    }*/
wmmhello's avatar
wmmhello 已提交
1760 1761 1762 1763 1764
  }
}

int32_t blockDataKeepFirstNRows(SSDataBlock* pBlock, size_t n) {
  if (n == 0) {
H
Haojun Liao 已提交
1765
    blockDataEmpty(pBlock);
wmmhello's avatar
wmmhello 已提交
1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782
    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 已提交
1783
int32_t tEncodeDataBlock(void** buf, const SSDataBlock* pBlock) {
H
Haojun Liao 已提交
1784
  int64_t tbUid = pBlock->info.id.uid;
1785
  int16_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
H
Haojun Liao 已提交
1786
  int16_t hasVarCol = pBlock->info.hasVarCol;
D
dapan1121 已提交
1787
  int64_t rows = pBlock->info.rows;
H
Haojun Liao 已提交
1788 1789 1790 1791 1792 1793
  int32_t sz = taosArrayGetSize(pBlock->pDataBlock);

  int32_t tlen = 0;
  tlen += taosEncodeFixedI64(buf, tbUid);
  tlen += taosEncodeFixedI16(buf, numOfCols);
  tlen += taosEncodeFixedI16(buf, hasVarCol);
D
dapan1121 已提交
1794
  tlen += taosEncodeFixedI64(buf, rows);
H
Haojun Liao 已提交
1795 1796 1797 1798
  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);
1799
    tlen += taosEncodeFixedI8(buf, pColData->info.type);
H
Haojun Liao 已提交
1800
    tlen += taosEncodeFixedI32(buf, pColData->info.bytes);
S
slzhou@taodata.com 已提交
1801
    tlen += taosEncodeFixedBool(buf, pColData->hasNull);
H
Haojun Liao 已提交
1802 1803 1804 1805 1806 1807 1808 1809

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

1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
    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 已提交
1826 1827 1828 1829 1830 1831 1832
  }
  return tlen;
}

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

1833 1834
  int16_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);

H
Haojun Liao 已提交
1835
  buf = taosDecodeFixedU64(buf, &pBlock->info.id.uid);
1836
  buf = taosDecodeFixedI16(buf, &numOfCols);
H
Haojun Liao 已提交
1837
  buf = taosDecodeFixedI16(buf, &pBlock->info.hasVarCol);
D
dapan1121 已提交
1838
  buf = taosDecodeFixedI64(buf, &pBlock->info.rows);
H
Haojun Liao 已提交
1839 1840 1841 1842 1843
  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);
1844
    buf = taosDecodeFixedI8(buf, &data.info.type);
H
Haojun Liao 已提交
1845
    buf = taosDecodeFixedI32(buf, &data.info.bytes);
S
slzhou@taodata.com 已提交
1846
    buf = taosDecodeFixedBool(buf, &data.hasNull);
H
Haojun Liao 已提交
1847 1848 1849 1850 1851 1852 1853 1854 1855 1856

    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);
1857 1858 1859 1860
    if (IS_VAR_DATA_TYPE(data.info.type)) {
      data.varmeta.length = len;
      data.varmeta.allocLen = len;
    }
S
slzhou 已提交
1861
    taosArrayPush(pBlock->pDataBlock, &data);
H
Haojun Liao 已提交
1862 1863
  }
  return (void*)buf;
L
Liu Jicong 已提交
1864
}
L
Liu Jicong 已提交
1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878

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

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

  return tlen;
}

L
Liu Jicong 已提交
1879
void* tDecodeDataBlocks(const void* buf, SArray** blocks) {
L
Liu Jicong 已提交
1880 1881
  int32_t sz;
  buf = taosDecodeFixedI32(buf, &sz);
L
Liu Jicong 已提交
1882 1883

  *blocks = taosArrayInit(sz, sizeof(SSDataBlock));
L
Liu Jicong 已提交
1884 1885 1886
  for (int32_t i = 0; i < sz; i++) {
    SSDataBlock pBlock = {0};
    buf = tDecodeDataBlock(buf, &pBlock);
L
Liu Jicong 已提交
1887
    taosArrayPush(*blocks, &pBlock);
L
Liu Jicong 已提交
1888 1889 1890
  }
  return (void*)buf;
}
L
Liu Jicong 已提交
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923

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;
    }
  }
1924
  struct tm ptm = {0};
1925
  if (taosLocalTime(&tt, &ptm, buf) == NULL) {
1926 1927
    return buf;
  }
L
Liu Jicong 已提交
1928
  size_t pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
L
Liu Jicong 已提交
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939

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

1941
#if 0
1942
void blockDebugShowDataBlock(SSDataBlock* pBlock, const char* flag) {
S
slzhou 已提交
1943 1944
  SArray* dataBlocks = taosArrayInit(1, sizeof(SSDataBlock*));
  taosArrayPush(dataBlocks, &pBlock);
1945 1946 1947 1948
  blockDebugShowDataBlocks(dataBlocks, flag);
  taosArrayDestroy(dataBlocks);
}

S
slzhou 已提交
1949
void blockDebugShowDataBlocks(const SArray* dataBlocks, const char* flag) {
C
Cary Xu 已提交
1950
  char    pBuf[128] = {0};
L
Liu Jicong 已提交
1951 1952
  int32_t sz = taosArrayGetSize(dataBlocks);
  for (int32_t i = 0; i < sz; i++) {
1953
    SSDataBlock* pDataBlock = taosArrayGet(dataBlocks, i);
L
Liu Jicong 已提交
1954
    size_t       numOfCols = taosArrayGetSize(pDataBlock->pDataBlock);
1955

L
Liu Jicong 已提交
1956
    int32_t rows = pDataBlock->info.rows;
C
Cary Xu 已提交
1957 1958
    printf("%s |block ver %" PRIi64 " |block type %d |child id %d|group id %" PRIu64 "\n", flag,
           pDataBlock->info.version, (int32_t)pDataBlock->info.type, pDataBlock->info.childId,
H
Haojun Liao 已提交
1959
           pDataBlock->info.id.groupId);
L
Liu Jicong 已提交
1960
    for (int32_t j = 0; j < rows; j++) {
C
Cary Xu 已提交
1961
      printf("%s |", flag);
1962
      for (int32_t k = 0; k < numOfCols; k++) {
L
Liu Jicong 已提交
1963 1964
        SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, k);
        void*            var = POINTER_SHIFT(pColInfoData->pData, j * pColInfoData->info.bytes);
1965 1966 1967
        if (k == 0) {
          printf("cols:%d |", (int32_t)numOfCols);
        }
5
54liuyao 已提交
1968
        if (colDataIsNull(pColInfoData, rows, j, NULL)) {
5
54liuyao 已提交
1969 1970 1971
          printf(" %15s |", "NULL");
          continue;
        }
1972

L
Liu Jicong 已提交
1973 1974 1975 1976 1977
        switch (pColInfoData->info.type) {
          case TSDB_DATA_TYPE_TIMESTAMP:
            formatTimestamp(pBuf, *(uint64_t*)var, TSDB_TIME_PRECISION_MILLI);
            printf(" %25s |", pBuf);
            break;
C
Cary Xu 已提交
1978
          case TSDB_DATA_TYPE_BOOL:
1979 1980 1981 1982 1983 1984
            printf(" %15" PRIi8 " |", *(int8_t*)var);
            break;
          case TSDB_DATA_TYPE_TINYINT:
            printf(" %15" PRIi8 " |", *(int8_t*)var);
            break;
          case TSDB_DATA_TYPE_SMALLINT:
K
kailixu 已提交
1985
            printf(" %15" PRIi16 " |", *(int16_t*)var);
C
Cary Xu 已提交
1986
            break;
L
Liu Jicong 已提交
1987 1988 1989
          case TSDB_DATA_TYPE_INT:
            printf(" %15d |", *(int32_t*)var);
            break;
1990
          case TSDB_DATA_TYPE_UTINYINT:
K
kailixu 已提交
1991
            printf(" %15" PRIu8 " |", *(uint8_t*)var);
1992 1993
            break;
          case TSDB_DATA_TYPE_USMALLINT:
K
kailixu 已提交
1994
            printf(" %15" PRIu16 " |", *(uint16_t*)var);
1995
            break;
L
Liu Jicong 已提交
1996 1997 1998
          case TSDB_DATA_TYPE_UINT:
            printf(" %15u |", *(uint32_t*)var);
            break;
L
Liu Jicong 已提交
1999
          case TSDB_DATA_TYPE_BIGINT:
2000
            printf(" %15" PRId64 " |", *(int64_t*)var);
L
Liu Jicong 已提交
2001
            break;
L
Liu Jicong 已提交
2002
          case TSDB_DATA_TYPE_UBIGINT:
2003
            printf(" %15" PRIu64 " |", *(uint64_t*)var);
L
Liu Jicong 已提交
2004
            break;
C
Cary Xu 已提交
2005 2006 2007
          case TSDB_DATA_TYPE_FLOAT:
            printf(" %15f |", *(float*)var);
            break;
5
54liuyao 已提交
2008
          case TSDB_DATA_TYPE_DOUBLE:
C
Cary Xu 已提交
2009
            printf(" %15lf |", *(double*)var);
5
54liuyao 已提交
2010
            break;
D
Dingle Zhang 已提交
2011 2012
          case TSDB_DATA_TYPE_VARCHAR:
          case TSDB_DATA_TYPE_GEOMETRY: {
C
Cary Xu 已提交
2013
            char*   pData = colDataGetVarData(pColInfoData, j);
C
Cary Xu 已提交
2014 2015
            int32_t dataSize = TMIN(sizeof(pBuf) - 1, varDataLen(pData));
            memset(pBuf, 0, dataSize + 1);
C
Cary Xu 已提交
2016 2017 2018 2019 2020
            strncpy(pBuf, varDataVal(pData), dataSize);
            printf(" %15s |", pBuf);
          } break;
          case TSDB_DATA_TYPE_NCHAR: {
            char*   pData = colDataGetVarData(pColInfoData, j);
C
Cary Xu 已提交
2021
            int32_t dataSize = TMIN(sizeof(pBuf), varDataLen(pData));
C
Cary Xu 已提交
2022
            memset(pBuf, 0, dataSize);
C
Cary Xu 已提交
2023
            (void)taosUcs4ToMbs((TdUcs4*)varDataVal(pData), dataSize, pBuf);
C
Cary Xu 已提交
2024 2025 2026 2027
            printf(" %15s |", pBuf);
          } break;
          default:
            break;
L
Liu Jicong 已提交
2028 2029 2030 2031 2032
        }
      }
      printf("\n");
    }
  }
5
54liuyao 已提交
2033
}
2034 2035
#endif

5
54liuyao 已提交
2036 2037
// for debug
char* dumpBlockData(SSDataBlock* pDataBlock, const char* flag, char** pDataBuf) {
2038
  int32_t size = 2048*1024;
5
54liuyao 已提交
2039
  *pDataBuf = taosMemoryCalloc(size, 1);
2040 2041
  char*   dumpBuf = *pDataBuf;
  char    pBuf[128] = {0};
5
54liuyao 已提交
2042 2043 2044
  int32_t colNum = taosArrayGetSize(pDataBlock->pDataBlock);
  int32_t rows = pDataBlock->info.rows;
  int32_t len = 0;
S
Shengliang Guan 已提交
2045 2046
  len += snprintf(dumpBuf + len, size - len,
                  "===stream===%s|block type %d|child id %d|group id:%" PRIu64 "|uid:%" PRId64
D
dapan1121 已提交
2047
                  "|rows:%" PRId64 "|version:%" PRIu64 "|cal start:%" PRIu64 "|cal end:%" PRIu64 "|tbl:%s\n",
H
Haojun Liao 已提交
2048
                  flag, (int32_t)pDataBlock->info.type, pDataBlock->info.childId, pDataBlock->info.id.groupId,
L
Liu Jicong 已提交
2049
                  pDataBlock->info.id.uid, pDataBlock->info.rows, pDataBlock->info.version,
X
Xiaoyu Wang 已提交
2050
                  pDataBlock->info.calWin.skey, pDataBlock->info.calWin.ekey, pDataBlock->info.parTbName);
S
Shengliang Guan 已提交
2051
  if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2052

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

5
54liuyao 已提交
2057 2058
    for (int32_t k = 0; k < colNum; k++) {
      SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, k);
5
54liuyao 已提交
2059
      if (colDataIsNull(pColInfoData, rows, j, NULL) || !pColInfoData->pData) {
5
54liuyao 已提交
2060
        len += snprintf(dumpBuf + len, size - len, " %15s |", "NULL");
L
Liu Jicong 已提交
2061
        if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2062 2063
        continue;
      }
5
54liuyao 已提交
2064 2065

      void* var = colDataGetData(pColInfoData, j);
5
54liuyao 已提交
2066 2067
      switch (pColInfoData->info.type) {
        case TSDB_DATA_TYPE_TIMESTAMP:
5
54liuyao 已提交
2068
          memset(pBuf, 0, sizeof(pBuf));
5
54liuyao 已提交
2069
          formatTimestamp(pBuf, *(uint64_t*)var, pColInfoData->info.precision);
5
54liuyao 已提交
2070
          len += snprintf(dumpBuf + len, size - len, " %25s |", pBuf);
L
Liu Jicong 已提交
2071
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2072
          break;
2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
        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 已提交
2089 2090
        case TSDB_DATA_TYPE_INT:
          len += snprintf(dumpBuf + len, size - len, " %15d |", *(int32_t*)var);
L
Liu Jicong 已提交
2091
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2092 2093 2094
          break;
        case TSDB_DATA_TYPE_UINT:
          len += snprintf(dumpBuf + len, size - len, " %15u |", *(uint32_t*)var);
L
Liu Jicong 已提交
2095
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2096 2097
          break;
        case TSDB_DATA_TYPE_BIGINT:
2098
          len += snprintf(dumpBuf + len, size - len, " %15" PRId64 " |", *(int64_t*)var);
L
Liu Jicong 已提交
2099
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2100 2101
          break;
        case TSDB_DATA_TYPE_UBIGINT:
2102
          len += snprintf(dumpBuf + len, size - len, " %15" PRIu64 " |", *(uint64_t*)var);
L
Liu Jicong 已提交
2103
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2104 2105 2106
          break;
        case TSDB_DATA_TYPE_FLOAT:
          len += snprintf(dumpBuf + len, size - len, " %15f |", *(float*)var);
L
Liu Jicong 已提交
2107
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2108 2109
          break;
        case TSDB_DATA_TYPE_DOUBLE:
5
54liuyao 已提交
2110 2111
          len += snprintf(dumpBuf + len, size - len, " %15f |", *(double*)var);
          if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2112
          break;
5
54liuyao 已提交
2113 2114 2115 2116
        case TSDB_DATA_TYPE_BOOL:
          len += snprintf(dumpBuf + len, size - len, " %15d |", *(bool*)var);
          if (len >= size - 1) return dumpBuf;
          break;
D
Dingle Zhang 已提交
2117 2118
        case TSDB_DATA_TYPE_VARCHAR:
        case TSDB_DATA_TYPE_GEOMETRY: {
5
54liuyao 已提交
2119
          memset(pBuf, 0, sizeof(pBuf));
L
Liu Jicong 已提交
2120
          char*   pData = colDataGetVarData(pColInfoData, j);
5
54liuyao 已提交
2121
          int32_t dataSize = TMIN(sizeof(pBuf), varDataLen(pData));
5
54liuyao 已提交
2122
          dataSize = TMIN(dataSize, 50);
5
54liuyao 已提交
2123
          memcpy(pBuf, varDataVal(pData), dataSize);
5
54liuyao 已提交
2124 2125
          len += snprintf(dumpBuf + len, size - len, " %15s |", pBuf);
          if (len >= size - 1) return dumpBuf;
L
Liu Jicong 已提交
2126
        } break;
5
54liuyao 已提交
2127
        case TSDB_DATA_TYPE_NCHAR: {
L
Liu Jicong 已提交
2128
          char*   pData = colDataGetVarData(pColInfoData, j);
5
54liuyao 已提交
2129 2130
          int32_t dataSize = TMIN(sizeof(pBuf), varDataLen(pData));
          memset(pBuf, 0, sizeof(pBuf));
C
Cary Xu 已提交
2131
          (void)taosUcs4ToMbs((TdUcs4*)varDataVal(pData), dataSize, pBuf);
5
54liuyao 已提交
2132 2133
          len += snprintf(dumpBuf + len, size - len, " %15s |", pBuf);
          if (len >= size - 1) return dumpBuf;
L
Liu Jicong 已提交
2134
        } break;
5
54liuyao 已提交
2135 2136
      }
    }
L
liuyao 已提交
2137
    len += snprintf(dumpBuf + len, size - len, "%d\n", j);
L
Liu Jicong 已提交
2138
    if (len >= size - 1) return dumpBuf;
5
54liuyao 已提交
2139 2140 2141
  }
  len += snprintf(dumpBuf + len, size - len, "%s |end\n", flag);
  return dumpBuf;
L
Liu Jicong 已提交
2142 2143
}

C
Cary Xu 已提交
2144 2145 2146 2147
/**
 * @brief TODO: Assume that the final generated result it less than 3M
 *
 * @param pReq
C
Cary Xu 已提交
2148
 * @param pDataBlocks
C
Cary Xu 已提交
2149
 * @param vgId
C
Cary Xu 已提交
2150
 * @param suid
L
Liu Jicong 已提交
2151
 *
C
Cary Xu 已提交
2152
 */
2153
#if 0
K
kailixu 已提交
2154
int32_t buildSubmitReqFromDataBlock(SSubmitReq** pReq, const SSDataBlock* pDataBlock, STSchema* pTSchema, int32_t vgId,
2155
                                    tb_uid_t suid) {
K
kailixu 已提交
2156
  int32_t bufSize = sizeof(SSubmitReq);
C
Cary Xu 已提交
2157
  int32_t sz = 1;
C
Cary Xu 已提交
2158
  for (int32_t i = 0; i < sz; ++i) {
C
Cary Xu 已提交
2159
    const SDataBlockInfo* pBlkInfo = &pDataBlock->info;
2160

C
Cary Xu 已提交
2161 2162
    int32_t colNum = taosArrayGetSize(pDataBlock->pDataBlock);
    bufSize += pBlkInfo->rows * (TD_ROW_HEAD_LEN + pBlkInfo->rowSize + BitmapLen(colNum));
C
Cary Xu 已提交
2163 2164 2165 2166
    bufSize += sizeof(SSubmitBlk);
  }

  *pReq = taosMemoryCalloc(1, bufSize);
2167
  if (!(*pReq)) {
C
Cary Xu 已提交
2168 2169 2170
    terrno = TSDB_CODE_OUT_OF_MEMORY;
    return TSDB_CODE_FAILED;
  }
C
Cary Xu 已提交
2171 2172
  void* pDataBuf = *pReq;

2173
  int32_t     msgLen = sizeof(SSubmitReq);
C
Cary Xu 已提交
2174 2175
  int32_t     numOfBlks = 0;
  SRowBuilder rb = {0};
C
Cary Xu 已提交
2176
  tdSRowInit(&rb, pTSchema->version);
C
Cary Xu 已提交
2177 2178

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

2182 2183 2184 2185 2186
    if (colNum <= 1) {
      // invalid if only with TS col
      continue;
    }

2187
    if (rb.nCols != colNum) {
C
Cary Xu 已提交
2188 2189 2190 2191 2192
      tdSRowSetTpInfo(&rb, colNum, pTSchema->flen);
    }

    SSubmitBlk* pSubmitBlk = POINTER_SHIFT(pDataBuf, msgLen);
    pSubmitBlk->suid = suid;
H
Haojun Liao 已提交
2193
    pSubmitBlk->uid = pDataBlock->info.id.groupId;
C
Cary Xu 已提交
2194
    pSubmitBlk->numOfRows = rows;
C
Cary Xu 已提交
2195
    pSubmitBlk->sversion = pTSchema->version;
C
Cary Xu 已提交
2196 2197 2198

    msgLen += sizeof(SSubmitBlk);
    int32_t dataLen = 0;
L
Liu Jicong 已提交
2199
    for (int32_t j = 0; j < rows; ++j) {                               // iterate by row
C
Cary Xu 已提交
2200
      tdSRowResetBuf(&rb, POINTER_SHIFT(pDataBuf, msgLen + dataLen));  // set row buf
2201
      bool    isStartKey = false;
2202
      int32_t offset = 0;
C
Cary Xu 已提交
2203 2204
      for (int32_t k = 0; k < colNum; ++k) {  // iterate by column
        SColumnInfoData* pColInfoData = taosArrayGet(pDataBlock->pDataBlock, k);
2205 2206
        STColumn*        pCol = &pTSchema->columns[k];
        void*            var = POINTER_SHIFT(pColInfoData->pData, j * pColInfoData->info.bytes);
C
Cary Xu 已提交
2207 2208 2209 2210
        switch (pColInfoData->info.type) {
          case TSDB_DATA_TYPE_TIMESTAMP:
            if (!isStartKey) {
              isStartKey = true;
2211
              tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID, TSDB_DATA_TYPE_TIMESTAMP, TD_VTYPE_NORM, var, true,
2212
                                  offset, k);
2213
              continue; // offset should keep 0 for next column
2214

2215 2216 2217
            } else if (colDataIsNull_s(pColInfoData, j)) {
              tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, TSDB_DATA_TYPE_TIMESTAMP, TD_VTYPE_NULL, NULL,
                                  false, offset, k);
C
Cary Xu 已提交
2218
            } else {
2219 2220
              tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, TSDB_DATA_TYPE_TIMESTAMP, TD_VTYPE_NORM, var,
                                  true, offset, k);
C
Cary Xu 已提交
2221 2222
            }
            break;
2223
          case TSDB_DATA_TYPE_NCHAR:
D
Dingle Zhang 已提交
2224 2225
          case TSDB_DATA_TYPE_VARCHAR:  // TSDB_DATA_TYPE_BINARY
          case TSDB_DATA_TYPE_GEOMETRY: {
2226 2227 2228 2229 2230 2231 2232 2233
            if (colDataIsNull_s(pColInfoData, j)) {
              tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, pColInfoData->info.type, TD_VTYPE_NULL, NULL,
                                  false, offset, k);
            } else {
              void* data = colDataGetData(pColInfoData, j);
              tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, pColInfoData->info.type, TD_VTYPE_NORM, data,
                                  true, offset, k);
            }
C
Cary Xu 已提交
2234 2235 2236 2237 2238
            break;
          }
          case TSDB_DATA_TYPE_VARBINARY:
          case TSDB_DATA_TYPE_DECIMAL:
          case TSDB_DATA_TYPE_BLOB:
2239
          case TSDB_DATA_TYPE_JSON:
C
Cary Xu 已提交
2240
          case TSDB_DATA_TYPE_MEDIUMBLOB:
C
Cary Xu 已提交
2241
            uError("the column type %" PRIi16 " is defined but not implemented yet", pColInfoData->info.type);
C
Cary Xu 已提交
2242 2243 2244
            break;
          default:
            if (pColInfoData->info.type < TSDB_DATA_TYPE_MAX && pColInfoData->info.type > TSDB_DATA_TYPE_NULL) {
2245
              if (colDataIsNull_s(pColInfoData, j)) {
L
Liu Jicong 已提交
2246 2247
                tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, pCol->type, TD_VTYPE_NULL, NULL, false,
                                    offset, k);
2248
              } else if (pCol->type == pColInfoData->info.type) {
C
Cary Xu 已提交
2249 2250
                tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, pCol->type, TD_VTYPE_NORM, var, true, offset,
                                    k);
2251
              } else {
C
Cary Xu 已提交
2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271
                char tv[8] = {0};
                if (pColInfoData->info.type == TSDB_DATA_TYPE_FLOAT) {
                  float v = 0;
                  GET_TYPED_DATA(v, float, pColInfoData->info.type, var);
                  SET_TYPED_DATA(&tv, pCol->type, v);
                } else if (pColInfoData->info.type == TSDB_DATA_TYPE_DOUBLE) {
                  double v = 0;
                  GET_TYPED_DATA(v, double, pColInfoData->info.type, var);
                  SET_TYPED_DATA(&tv, pCol->type, v);
                } else if (IS_SIGNED_NUMERIC_TYPE(pColInfoData->info.type)) {
                  int64_t v = 0;
                  GET_TYPED_DATA(v, int64_t, pColInfoData->info.type, var);
                  SET_TYPED_DATA(&tv, pCol->type, v);
                } else {
                  uint64_t v = 0;
                  GET_TYPED_DATA(v, uint64_t, pColInfoData->info.type, var);
                  SET_TYPED_DATA(&tv, pCol->type, v);
                }
                tdAppendColValToRow(&rb, PRIMARYKEY_TIMESTAMP_COL_ID + k, pCol->type, TD_VTYPE_NORM, tv, true, offset,
                                    k);
2272
              }
C
Cary Xu 已提交
2273
            } else {
C
Cary Xu 已提交
2274
              uError("the column type %" PRIi16 " is undefined\n", pColInfoData->info.type);
C
Cary Xu 已提交
2275 2276 2277
            }
            break;
        }
2278
        offset += TYPE_BYTES[pCol->type];  // sum/avg would convert to int64_t/uint64_t/double during aggregation
C
Cary Xu 已提交
2279
      }
2280
      tdSRowEnd(&rb);
C
Cary Xu 已提交
2281
      dataLen += TD_ROW_LEN(rb.pBuf);
C
Cary Xu 已提交
2282 2283 2284
#ifdef TD_DEBUG_PRINT_ROW
      tdSRowPrint(rb.pBuf, pTSchema, __func__);
#endif
C
Cary Xu 已提交
2285
    }
C
Cary Xu 已提交
2286 2287 2288

    ++numOfBlks;

C
Cary Xu 已提交
2289 2290 2291 2292
    pSubmitBlk->dataLen = dataLen;
    msgLen += pSubmitBlk->dataLen;
  }

2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307
  if (numOfBlks > 0) {
    (*pReq)->length = msgLen;

    (*pReq)->header.vgId = htonl(vgId);
    (*pReq)->header.contLen = htonl(msgLen);
    (*pReq)->length = (*pReq)->header.contLen;
    (*pReq)->numOfBlocks = htonl(numOfBlks);
    SSubmitBlk* blk = (SSubmitBlk*)((*pReq) + 1);
    while (numOfBlks--) {
      int32_t dataLen = blk->dataLen;
      blk->uid = htobe64(blk->uid);
      blk->suid = htobe64(blk->suid);
      blk->sversion = htonl(blk->sversion);
      blk->dataLen = htonl(blk->dataLen);
      blk->schemaLen = htonl(blk->schemaLen);
2308
      blk->numOfRows = htonl(blk->numOfRows);
2309 2310 2311 2312 2313
      blk = (SSubmitBlk*)(blk->data + dataLen);
    }
  } else {
    // no valid rows
    taosMemoryFreeClear(*pReq);
C
Cary Xu 已提交
2314
  }
C
Cary Xu 已提交
2315 2316

  return TSDB_CODE_SUCCESS;
C
Cary Xu 已提交
2317
}
2318 2319
#endif

2320 2321 2322
int32_t buildSubmitReqFromDataBlock(SSubmitReq2** ppReq, const SSDataBlock* pDataBlock, const STSchema* pTSchema,
                                    int64_t uid, int32_t vgId, tb_uid_t suid) {
  SSubmitReq2* pReq = *ppReq;
2323 2324 2325 2326
  SArray*      pVals = NULL;
  int32_t      numOfBlks = 0;
  int32_t      sz = 1;

K
kailixu 已提交
2327 2328
  terrno = TSDB_CODE_SUCCESS;

2329 2330 2331 2332 2333
  if (NULL == pReq) {
    if (!(pReq = taosMemoryMalloc(sizeof(SSubmitReq2)))) {
      terrno = TSDB_CODE_OUT_OF_MEMORY;
      goto _end;
    }
2334

2335 2336 2337
    if (!(pReq->aSubmitTbData = taosArrayInit(1, sizeof(SSubmitTbData)))) {
      goto _end;
    }
2338 2339 2340 2341 2342 2343 2344 2345 2346 2347
  }

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

K
kailixu 已提交
2351
    SSubmitTbData tbData = {0};
2352

K
kailixu 已提交
2353
    if (!(tbData.aRowP = taosArrayInit(rows, sizeof(SRow*)))) {
2354
      goto _end;
2355
    }
K
kailixu 已提交
2356
    tbData.suid = suid;
2357
    tbData.uid = uid;
K
kailixu 已提交
2358
    tbData.sver = pTSchema->version;
2359 2360

    if (!pVals && !(pVals = taosArrayInit(colNum, sizeof(SColVal)))) {
K
kailixu 已提交
2361
      taosArrayDestroy(tbData.aRowP);
2362
      goto _end;
2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
    }

    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);
2373
        const STColumn*  pCol = &pTSchema->columns[k];
2374 2375 2376 2377 2378 2379 2380
        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;
2381 2382
              ASSERT(PRIMARYKEY_TIMESTAMP_COL_ID == pCol->colId);
              SColVal cv = COL_VAL_VALUE(pCol->colId, pCol->type, (SValue){.val = *(TSKEY*)var});
2383 2384
              taosArrayPush(pVals, &cv);
            } else if (colDataIsNull_s(pColInfoData, j)) {
2385
              SColVal cv = COL_VAL_NULL(pCol->colId, pCol->type);
2386 2387
              taosArrayPush(pVals, &cv);
            } else {
2388
              SColVal cv = COL_VAL_VALUE(pCol->colId, pCol->type, (SValue){.val = *(int64_t*)var});
2389 2390 2391 2392 2393 2394 2395
              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)) {
2396
              SColVal cv = COL_VAL_NULL(pCol->colId, pCol->type);
2397 2398
              taosArrayPush(pVals, &cv);
            } else {
K
kailixu 已提交
2399
              void*   data = colDataGetVarData(pColInfoData, j);
2400
              SValue  sv = (SValue){.nData = varDataLen(data), .pData = varDataVal(data)};  // address copy, no value
2401
              SColVal cv = COL_VAL_VALUE(pCol->colId, pCol->type, sv);
2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416
              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)) {
2417
                SColVal cv = COL_VAL_NULL(pCol->colId, pCol->type);  // should use pCol->type
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447
                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);
                }
2448
                SColVal cv = COL_VAL_VALUE(pCol->colId, pColInfoData->info.type, sv);
2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
                taosArrayPush(pVals, &cv);
              }
            } else {
              uError("the column type %" PRIi16 " is undefined\n", pColInfoData->info.type);
              ASSERT(0);
            }
            break;
        }
      }
      SRow* pRow = NULL;
2459
      if ((terrno = tRowBuild(pVals, pTSchema, &pRow)) < 0) {
2460
        tDestroySubmitTbData(&tbData, TSDB_MSG_FLG_ENCODE);
2461
        goto _end;
2462
      }
2463
      ASSERT(pRow);
K
kailixu 已提交
2464
      taosArrayPush(tbData.aRowP, &pRow);
2465
    }
2466

K
kailixu 已提交
2467
    taosArrayPush(pReq->aSubmitTbData, &tbData);
2468 2469
  }
_end:
2470
  taosArrayDestroy(pVals);
2471
  if (terrno != 0) {
2472
    *ppReq = NULL;
H
Haojun Liao 已提交
2473
    if (pReq) {
2474
      tDestroySubmitReq(pReq, TSDB_MSG_FLG_ENCODE);
H
Haojun Liao 已提交
2475 2476 2477
      taosMemoryFreeClear(pReq);
    }

2478 2479
    return TSDB_CODE_FAILED;
  }
2480
  *ppReq = pReq;
2481 2482
  return TSDB_CODE_SUCCESS;
}
L
Liu Jicong 已提交
2483

L
Liu Jicong 已提交
2484
char* buildCtbNameByGroupId(const char* stbFullName, uint64_t groupId) {
G
Ganlin Zhao 已提交
2485 2486 2487 2488
  if (stbFullName[0] == 0) {
    return NULL;
  }

L
Liu Jicong 已提交
2489
  SArray* tags = taosArrayInit(0, sizeof(SSmlKv));
L
Liu Jicong 已提交
2490 2491 2492 2493 2494 2495 2496 2497 2498 2499
  if (tags == NULL) {
    return NULL;
  }

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

L
Liu Jicong 已提交
2500 2501 2502 2503
  SSmlKv pTag = {.key = "group_id",
                 .keyLen = sizeof("group_id") - 1,
                 .type = TSDB_DATA_TYPE_UBIGINT,
                 .u = groupId,
2504
                 .length = sizeof(uint64_t)};
2505 2506 2507 2508
  taosArrayPush(tags, &pTag);

  RandTableName rname = {
      .tags = tags,
L
Liu Jicong 已提交
2509 2510 2511
      .stbFullName = stbFullName,
      .stbFullNameLen = strlen(stbFullName),
      .ctbShortName = cname,
2512 2513 2514 2515 2516 2517
  };

  buildChildTableName(&rname);

  taosArrayDestroy(tags);

G
Ganlin Zhao 已提交
2518 2519 2520
  if ((rname.ctbShortName && rname.ctbShortName[0]) == 0) {
    return NULL;
  }
L
Liu Jicong 已提交
2521
  return rname.ctbShortName;
2522 2523
}

H
Haojun Liao 已提交
2524 2525 2526
int32_t blockEncode(const SSDataBlock* pBlock, char* data, int32_t numOfCols) {
  int32_t dataLen = 0;

2527
  // todo extract method
2528 2529 2530 2531
  int32_t* version = (int32_t*)data;
  *version = 1;
  data += sizeof(int32_t);

2532 2533 2534
  int32_t* actualLen = (int32_t*)data;
  data += sizeof(int32_t);

2535 2536 2537
  int32_t* rows = (int32_t*)data;
  *rows = pBlock->info.rows;
  data += sizeof(int32_t);
H
Haojun Liao 已提交
2538
  ASSERT(*rows > 0);
2539 2540 2541 2542 2543

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

2544 2545 2546
  // flag segment.
  // the inital bit is for column info
  int32_t* flagSegment = (int32_t*)data;
L
Liu Jicong 已提交
2547
  *flagSegment = (1 << 31);
2548

2549 2550
  data += sizeof(int32_t);

2551 2552 2553
  uint64_t* groupId = (uint64_t*)data;
  data += sizeof(uint64_t);

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

2557 2558
    *((int8_t*)data) = pColInfoData->info.type;
    data += sizeof(int8_t);
2559

L
Liu Jicong 已提交
2560
    *((int32_t*)data) = pColInfoData->info.bytes;
2561 2562 2563
    data += sizeof(int32_t);
  }

2564 2565 2566
  int32_t* colSizes = (int32_t*)data;
  data += numOfCols * sizeof(int32_t);

H
Haojun Liao 已提交
2567
  dataLen = blockDataGetSerialMetaSize(numOfCols);
2568 2569 2570 2571 2572 2573

  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
2574
    size_t metaSize = 0;
2575
    if (IS_VAR_DATA_TYPE(pColRes->info.type)) {
2576
      metaSize = numOfRows * sizeof(int32_t);
2577 2578
      memcpy(data, pColRes->varmeta.offset, metaSize);
    } else {
2579 2580
      metaSize = BitmapLen(numOfRows);
      memcpy(data, pColRes->nullbitmap, metaSize);
2581 2582
    }

2583
    data += metaSize;
H
Haojun Liao 已提交
2584
    dataLen += metaSize;
2585

2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607
     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];
2608
    }
2609

2610
    colSizes[col] = htonl(colSizes[col]);
2611
//    uError("blockEncode col bytes:%d, type:%d, size:%d, htonl size:%d", pColRes->info.bytes, pColRes->info.type, htonl(colSizes[col]), colSizes[col]);
2612 2613
  }

H
Haojun Liao 已提交
2614
  *actualLen = dataLen;
H
Haojun Liao 已提交
2615
  *groupId = pBlock->info.id.groupId;
H
Haojun Liao 已提交
2616 2617
  ASSERT(dataLen > 0);
  return dataLen;
2618 2619
}

2620
const char* blockDecode(SSDataBlock* pBlock, const char* pData) {
2621 2622
  const char* pStart = pData;

L
Liu Jicong 已提交
2623
  int32_t version = *(int32_t*)pStart;
2624 2625 2626
  pStart += sizeof(int32_t);
  ASSERT(version == 1);

2627
  // total length sizeof(int32_t)
2628 2629 2630
  int32_t dataLen = *(int32_t*)pStart;
  pStart += sizeof(int32_t);

2631
  // total rows sizeof(int32_t)
L
Liu Jicong 已提交
2632
  int32_t numOfRows = *(int32_t*)pStart;
2633 2634 2635 2636 2637 2638 2639
  pStart += sizeof(int32_t);

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

  // has column info segment
2640 2641
  int32_t flagSeg = *(int32_t*)pStart;
  int32_t hasColumnInfo = (flagSeg >> 31);
2642 2643 2644
  pStart += sizeof(int32_t);

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

2648
  if (pBlock->pDataBlock == NULL) {
2649
    pBlock->pDataBlock = taosArrayInit_s(sizeof(SColumnInfoData), numOfCols);
2650 2651
  }

L
Liu Jicong 已提交
2652
  for (int32_t i = 0; i < numOfCols; ++i) {
2653
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
麦壳饼's avatar
麦壳饼 已提交
2654
    pColInfoData->info.type = *(int8_t*)pStart;
2655
    pStart += sizeof(int8_t);
2656 2657 2658

    pColInfoData->info.bytes = *(int32_t*)pStart;
    pStart += sizeof(int32_t);
2659 2660 2661 2662

    if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
      pBlock->info.hasVarCol = true;
    }
2663 2664 2665 2666
  }

  blockDataEnsureCapacity(pBlock, numOfRows);

2667 2668 2669 2670
  int32_t* colLen = (int32_t*)pStart;
  pStart += sizeof(int32_t) * numOfCols;

  for (int32_t i = 0; i < numOfCols; ++i) {
2671
    colLen[i] = htonl(colLen[i]);
2672 2673 2674 2675 2676 2677 2678
    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;

2679 2680 2681 2682 2683 2684 2685 2686
      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];
2687
      }
2688 2689

      pColInfoData->varmeta.length = colLen[i];
2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705
    } 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];
  }

2706
  pBlock->info.dataLoad = 1;
2707
  pBlock->info.rows = numOfRows;
2708 2709
  ASSERT(pStart - pData == dataLen);
  return pStart;
L
Liu Jicong 已提交
2710
}