builtinsimpl.c 64.3 KB
Newer Older
H
Haojun Liao 已提交
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/>.
 */

#include "builtinsimpl.h"
17
#include "cJSON.h"
18
#include "function.h"
19
#include "querynodes.h"
H
Haojun Liao 已提交
20 21
#include "taggfunction.h"
#include "tdatablock.h"
22
#include "tpercentile.h"
H
Haojun Liao 已提交
23

24
#define HISTOGRAM_MAX_BINS_NUM   100
25

G
Ganlin Zhao 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39
typedef struct SSumRes {
  union {
    int64_t  isum;
    uint64_t usum;
    double   dsum;
  };
} SSumRes;

typedef struct SAvgRes {
  double  result;
  SSumRes sum;
  int64_t count;
} SAvgRes;

40 41
typedef struct STopBotResItem {
  SVariant v;
42
  uint64_t uid;  // it is a table uid, used to extract tag data during building of the final result for the tag data
43
  struct {
44 45 46
    int32_t pageId;
    int32_t offset;
  } tuplePos;  // tuple data of this chosen row
47 48
} STopBotResItem;

G
Ganlin Zhao 已提交
49
typedef struct STopBotRes {
50
  STopBotResItem* pItems;
G
Ganlin Zhao 已提交
51 52 53 54 55
} STopBotRes;

typedef struct SStddevRes {
  double  result;
  int64_t count;
56 57 58 59 60 61 62 63
  union {
    double  quadraticDSum;
    int64_t quadraticISum;
  };
  union {
    double  dsum;
    int64_t isum;
  };
G
Ganlin Zhao 已提交
64 65 66 67
} SStddevRes;

typedef struct SPercentileInfo {
  double      result;
68
  tMemBucket* pMemBucket;
G
Ganlin Zhao 已提交
69 70 71 72 73 74 75
  int32_t     stage;
  double      minval;
  double      maxval;
  int64_t     numOfElems;
} SPercentileInfo;

typedef struct SDiffInfo {
76 77 78 79 80 81 82 83
  bool hasPrev;
  bool includeNull;
  bool ignoreNegative;
  bool firstOutput;
  union {
    int64_t i64;
    double  d64;
  } prev;
84 85

  int64_t prevTs;
G
Ganlin Zhao 已提交
86 87
} SDiffInfo;

G
Ganlin Zhao 已提交
88 89 90 91 92 93 94
typedef struct SSpreadInfo {
  double result;
  bool   hasResult;
  double min;
  double max;
} SSpreadInfo;

95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
typedef struct SHistoFuncBin {
  double lower;
  double upper;
  union {
    int64_t count;
    double  percentage;
  };
} SHistoFuncBin;

typedef struct SHistoFuncInfo {
  int32_t numOfBins;
  bool    normalized;
  SHistoFuncBin bins[];
} SHistoFuncInfo;

110 111 112 113 114 115 116
typedef enum {
  UNKNOWN_BIN = 0,
  USER_INPUT_BIN,
  LINEAR_BIN,
  LOG_BIN
} EHistoBinType;

117

118 119 120 121 122 123
#define SET_VAL(_info, numOfElem, res) \
  do {                                 \
    if ((numOfElem) <= 0) {            \
      break;                           \
    }                                  \
    (_info)->numOfRes = (res);         \
H
Haojun Liao 已提交
124 125
  } while (0)

G
Ganlin Zhao 已提交
126 127 128 129 130 131
#define GET_TS_LIST(x)    ((TSKEY*)((x)->ptsList))
#define GET_TS_DATA(x, y) (GET_TS_LIST(x)[(y)])

#define DO_UPDATE_TAG_COLUMNS_WITHOUT_TS(ctx)                      \
  do {                                                             \
    for (int32_t _i = 0; _i < (ctx)->tagInfo.numOfTagCols; ++_i) { \
132
      SqlFunctionCtx* __ctx = (ctx)->tagInfo.pTagCtxList[_i];      \
G
Ganlin Zhao 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
      __ctx->fpSet.process(__ctx);                                 \
    }                                                              \
  } while (0);

#define UPDATE_DATA(ctx, left, right, num, sign, _ts) \
  do {                                                \
    if (((left) < (right)) ^ (sign)) {                \
      (left) = (right);                               \
      DO_UPDATE_SUBSID_RES(ctx, _ts);                 \
      (num) += 1;                                     \
    }                                                 \
  } while (0)

#define LOOPCHECK_N(val, _col, ctx, _t, _nrow, _start, sign, num)        \
  do {                                                                   \
148
    _t* d = (_t*)((_col)->pData);                                        \
G
Ganlin Zhao 已提交
149 150 151 152 153 154 155 156 157
    for (int32_t i = (_start); i < (_nrow) + (_start); ++i) {            \
      if (((_col)->hasNull) && colDataIsNull_f((_col)->nullbitmap, i)) { \
        continue;                                                        \
      }                                                                  \
      TSKEY ts = (ctx)->ptsList != NULL ? GET_TS_DATA(ctx, i) : 0;       \
      UPDATE_DATA(ctx, val, d[i], num, sign, ts);                        \
    }                                                                    \
  } while (0)

158
bool functionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
H
Haojun Liao 已提交
159 160 161 162 163 164 165 166 167 168 169 170
  if (pResultInfo->initialized) {
    return false;
  }

  if (pCtx->pOutput != NULL) {
    memset(pCtx->pOutput, 0, (size_t)pCtx->resDataInfo.bytes);
  }

  initResultRowEntry(pResultInfo, pCtx->resDataInfo.interBufSize);
  return true;
}

171
int32_t functionFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
172
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
173
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
174

175
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
176 177
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
  /*cleanupResultRowEntry(pResInfo);*/
178 179 180 181 182

  char* in = GET_ROWCELL_INTERBUF(pResInfo);
  colDataAppend(pCol, pBlock->info.rows, in, pResInfo->isNullRes);

  return pResInfo->numOfRes;
H
Haojun Liao 已提交
183 184
}

185
int32_t functionFinalizeWithResultBuf(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, char* finalResult) {
186
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
187 188 189
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
190
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
191 192 193 194 195 196 197 198
  cleanupResultRowEntry(pResInfo);

  char* in = finalResult;
  colDataAppend(pCol, pBlock->info.rows, in, pResInfo->isNullRes);

  return pResInfo->numOfRes;
}

199 200 201
EFuncDataRequired countDataRequired(SFunctionNode* pFunc, STimeWindow* pTimeWindow) {
  SNode* pParam = nodesListGetNode(pFunc->pParameterList, 0);
  if (QUERY_NODE_COLUMN == nodeType(pParam) && PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)pParam)->colId) {
202
    return FUNC_DATA_REQUIRED_NOT_LOAD;
203
  }
204
  return FUNC_DATA_REQUIRED_STATIS_LOAD;
205
}
H
Haojun Liao 已提交
206 207 208 209 210 211 212 213 214 215

bool getCountFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(int64_t);
  return true;
}

/*
 * count function does need the finalize, if data is missing, the default value, which is 0, is used
 * count function does not use the pCtx->interResBuf to keep the intermediate buffer
 */
216
int32_t countFunction(SqlFunctionCtx* pCtx) {
H
Haojun Liao 已提交
217 218 219
  int32_t numOfElem = 0;

  /*
H
Haojun Liao 已提交
220 221 222
   * 1. column data missing (schema modified) causes pInputCol->hasNull == true. pInput->colDataAggIsSet == true;
   * 2. for general non-primary key columns, pInputCol->hasNull may be true or false, pInput->colDataAggIsSet == true;
   * 3. for primary key column, pInputCol->hasNull always be false, pInput->colDataAggIsSet == false;
H
Haojun Liao 已提交
223 224
   */
  SInputColumnInfoData* pInput = &pCtx->input;
225
  SColumnInfoData*      pInputCol = pInput->pData[0];
H
Haojun Liao 已提交
226 227 228 229 230 231 232 233 234 235 236 237
  if (pInput->colDataAggIsSet && pInput->totalRows == pInput->numOfRows) {
    numOfElem = pInput->numOfRows - pInput->pColumnDataAgg[0]->numOfNull;
    ASSERT(numOfElem >= 0);
  } else {
    if (pInputCol->hasNull) {
      for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
        if (colDataIsNull(pInputCol, pInput->totalRows, i, NULL)) {
          continue;
        }
        numOfElem += 1;
      }
    } else {
238 239
      // when counting on the primary time stamp column and no statistics data is presented, use the size value
      // directly.
H
Haojun Liao 已提交
240 241 242 243 244
      numOfElem = pInput->numOfRows;
    }
  }

  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
245 246
  char*                buf = GET_ROWCELL_INTERBUF(pResInfo);
  *((int64_t*)buf) += numOfElem;
H
Haojun Liao 已提交
247 248

  SET_VAL(pResInfo, numOfElem, 1);
wmmhello's avatar
wmmhello 已提交
249
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
250 251 252 253
}

#define LIST_ADD_N(_res, _col, _start, _rows, _t, numOfElem)             \
  do {                                                                   \
254
    _t* d = (_t*)(_col->pData);                                          \
H
Haojun Liao 已提交
255 256 257 258 259 260 261 262 263
    for (int32_t i = (_start); i < (_rows) + (_start); ++i) {            \
      if (((_col)->hasNull) && colDataIsNull_f((_col)->nullbitmap, i)) { \
        continue;                                                        \
      };                                                                 \
      (_res) += (d)[i];                                                  \
      (numOfElem)++;                                                     \
    }                                                                    \
  } while (0)

264
int32_t sumFunction(SqlFunctionCtx* pCtx) {
H
Haojun Liao 已提交
265 266 267 268
  int32_t numOfElem = 0;

  // Only the pre-computing information loaded and actual data does not loaded
  SInputColumnInfoData* pInput = &pCtx->input;
269 270
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
  int32_t               type = pInput->pData[0]->info.type;
H
Haojun Liao 已提交
271

272
  SSumRes* pSumRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
G
Ganlin Zhao 已提交
273

H
Haojun Liao 已提交
274 275 276 277 278
  if (pInput->colDataAggIsSet) {
    numOfElem = pInput->numOfRows - pAgg->numOfNull;
    ASSERT(numOfElem >= 0);

    if (IS_SIGNED_NUMERIC_TYPE(type)) {
279
      pSumRes->isum += pAgg->sum;
H
Haojun Liao 已提交
280
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
281
      pSumRes->usum += pAgg->sum;
H
Haojun Liao 已提交
282
    } else if (IS_FLOAT_TYPE(type)) {
283
      pSumRes->dsum += GET_DOUBLE_VAL((const char*)&(pAgg->sum));
H
Haojun Liao 已提交
284 285 286 287
    }
  } else {  // computing based on the true data block
    SColumnInfoData* pCol = pInput->pData[0];

288
    int32_t start = pInput->startRowIndex;
H
Haojun Liao 已提交
289 290
    int32_t numOfRows = pInput->numOfRows;

291 292
    if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
      if (type == TSDB_DATA_TYPE_TINYINT || type == TSDB_DATA_TYPE_BOOL) {
293 294 295 296 297 298 299
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int8_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_SMALLINT) {
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int16_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_INT) {
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int32_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_BIGINT) {
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int64_t, numOfElem);
H
Haojun Liao 已提交
300
      }
301 302 303 304 305 306 307 308 309
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
      if (type == TSDB_DATA_TYPE_UTINYINT) {
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint8_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_USMALLINT) {
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint16_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_UINT) {
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint32_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_UBIGINT) {
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint64_t, numOfElem);
H
Haojun Liao 已提交
310
      }
311 312 313 314
    } else if (type == TSDB_DATA_TYPE_DOUBLE) {
      LIST_ADD_N(pSumRes->dsum, pCol, start, numOfRows, double, numOfElem);
    } else if (type == TSDB_DATA_TYPE_FLOAT) {
      LIST_ADD_N(pSumRes->dsum, pCol, start, numOfRows, float, numOfElem);
H
Haojun Liao 已提交
315 316 317 318 319
    }
  }

  // data in the check operation are all null, not output
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
wmmhello's avatar
wmmhello 已提交
320
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
321 322
}

H
Haojun Liao 已提交
323
bool getSumFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
H
Haojun Liao 已提交
324 325 326 327
  pEnv->calcMemSize = sizeof(SSumRes);
  return true;
}

G
Ganlin Zhao 已提交
328 329 330 331 332
bool getAvgFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(double);
  return true;
}

333
bool avgFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
G
Ganlin Zhao 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

  SAvgRes* pRes = GET_ROWCELL_INTERBUF(pResultInfo);
  memset(pRes, 0, sizeof(SAvgRes));
  return true;
}

int32_t avgFunction(SqlFunctionCtx* pCtx) {
  int32_t numOfElem = 0;

  // Only the pre-computing information loaded and actual data does not loaded
  SInputColumnInfoData* pInput = &pCtx->input;
  int32_t               type = pInput->pData[0]->info.type;

  SAvgRes* pAvgRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

  // computing based on the true data block
  SColumnInfoData* pCol = pInput->pData[0];

  int32_t start = pInput->startRowIndex;
  int32_t numOfRows = pInput->numOfRows;

  switch (type) {
    case TSDB_DATA_TYPE_TINYINT: {
360 361 362 363
      int8_t* plist = (int8_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
G
Ganlin Zhao 已提交
364 365
        }

366 367 368
        numOfElem += 1;
        pAvgRes->count += 1;
        pAvgRes->sum.isum += plist[i];
G
Ganlin Zhao 已提交
369 370
      }

371 372 373 374
      break;
    }

    case TSDB_DATA_TYPE_SMALLINT: {
G
Ganlin Zhao 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
      int16_t* plist = (int16_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pAvgRes->count += 1;
        pAvgRes->sum.isum += plist[i];
      }
      break;
    }

    case TSDB_DATA_TYPE_INT: {
      int32_t* plist = (int32_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pAvgRes->count += 1;
        pAvgRes->sum.isum += plist[i];
      }

      break;
    }

    case TSDB_DATA_TYPE_BIGINT: {
      int64_t* plist = (int64_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pAvgRes->count += 1;
        pAvgRes->sum.isum += plist[i];
      }
      break;
    }

    case TSDB_DATA_TYPE_FLOAT: {
      float* plist = (float*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pAvgRes->count += 1;
        pAvgRes->sum.dsum += plist[i];
      }
      break;
    }

    case TSDB_DATA_TYPE_DOUBLE: {
      double* plist = (double*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pAvgRes->count += 1;
        pAvgRes->sum.dsum += plist[i];
      }
      break;
    }

    default:
      break;
  }

  // data in the check operation are all null, not output
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
454
int32_t avgFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
G
Ganlin Zhao 已提交
455
  SInputColumnInfoData* pInput = &pCtx->input;
456 457
  int32_t               type = pInput->pData[0]->info.type;
  SAvgRes*              pAvgRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
G
Ganlin Zhao 已提交
458
  if (IS_INTEGER_TYPE(type)) {
459
    pAvgRes->result = pAvgRes->sum.isum / ((double)pAvgRes->count);
G
Ganlin Zhao 已提交
460
  } else {
461
    pAvgRes->result = pAvgRes->sum.dsum / ((double)pAvgRes->count);
G
Ganlin Zhao 已提交
462
  }
463

H
Haojun Liao 已提交
464
  return functionFinalize(pCtx, pBlock);
G
Ganlin Zhao 已提交
465 466
}

467
EFuncDataRequired statisDataRequired(SFunctionNode* pFunc, STimeWindow* pTimeWindow) {
468 469 470
  return FUNC_DATA_REQUIRED_STATIS_LOAD;
}

471
bool maxFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
472 473 474 475 476
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

  char* buf = GET_ROWCELL_INTERBUF(pResultInfo);
477
  switch (pCtx->resDataInfo.type) {
478
    case TSDB_DATA_TYPE_INT:
479
      *((int32_t*)buf) = INT32_MIN;
480 481
      break;
    case TSDB_DATA_TYPE_UINT:
482
      *((uint32_t*)buf) = 0;
483 484
      break;
    case TSDB_DATA_TYPE_FLOAT:
485
      *((float*)buf) = -FLT_MAX;
486 487
      break;
    case TSDB_DATA_TYPE_DOUBLE:
488
      SET_DOUBLE_VAL(((double*)buf), -DBL_MAX);
489 490
      break;
    case TSDB_DATA_TYPE_BIGINT:
491
      *((int64_t*)buf) = INT64_MIN;
492 493
      break;
    case TSDB_DATA_TYPE_UBIGINT:
494
      *((uint64_t*)buf) = 0;
495 496
      break;
    case TSDB_DATA_TYPE_SMALLINT:
497
      *((int16_t*)buf) = INT16_MIN;
498 499
      break;
    case TSDB_DATA_TYPE_USMALLINT:
500
      *((uint16_t*)buf) = 0;
501 502
      break;
    case TSDB_DATA_TYPE_TINYINT:
503
      *((int8_t*)buf) = INT8_MIN;
504 505
      break;
    case TSDB_DATA_TYPE_UTINYINT:
506
      *((uint8_t*)buf) = 0;
507
      break;
508 509 510
    case TSDB_DATA_TYPE_BOOL:
      *((int8_t*)buf) = 0;
      break;
511 512 513 514 515 516
    default:
      assert(0);
  }
  return true;
}

517
bool minFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
518 519 520 521 522
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;  // not initialized since it has been initialized
  }

  char* buf = GET_ROWCELL_INTERBUF(pResultInfo);
523
  switch (pCtx->resDataInfo.type) {
524
    case TSDB_DATA_TYPE_TINYINT:
525
      *((int8_t*)buf) = INT8_MAX;
526 527
      break;
    case TSDB_DATA_TYPE_UTINYINT:
528
      *(uint8_t*)buf = UINT8_MAX;
529 530
      break;
    case TSDB_DATA_TYPE_SMALLINT:
531
      *((int16_t*)buf) = INT16_MAX;
532 533
      break;
    case TSDB_DATA_TYPE_USMALLINT:
534
      *((uint16_t*)buf) = UINT16_MAX;
535 536
      break;
    case TSDB_DATA_TYPE_INT:
537
      *((int32_t*)buf) = INT32_MAX;
538 539
      break;
    case TSDB_DATA_TYPE_UINT:
540
      *((uint32_t*)buf) = UINT32_MAX;
541 542
      break;
    case TSDB_DATA_TYPE_BIGINT:
543
      *((int64_t*)buf) = INT64_MAX;
544 545
      break;
    case TSDB_DATA_TYPE_UBIGINT:
546
      *((uint64_t*)buf) = UINT64_MAX;
547 548
      break;
    case TSDB_DATA_TYPE_FLOAT:
549
      *((float*)buf) = FLT_MAX;
550 551
      break;
    case TSDB_DATA_TYPE_DOUBLE:
552
      SET_DOUBLE_VAL(((double*)buf), DBL_MAX);
553
      break;
554 555 556
    case TSDB_DATA_TYPE_BOOL:
      *((int8_t*)buf) = 1;
      break;
557 558 559 560 561 562 563
    default:
      assert(0);
  }

  return true;
}

H
Haojun Liao 已提交
564
bool getMinmaxFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
565 566 567 568 569 570 571 572 573 574
  pEnv->calcMemSize = sizeof(int64_t);
  return true;
}

#define GET_TS_LIST(x)    ((TSKEY*)((x)->ptsList))
#define GET_TS_DATA(x, y) (GET_TS_LIST(x)[(y)])

#define DO_UPDATE_TAG_COLUMNS_WITHOUT_TS(ctx)                      \
  do {                                                             \
    for (int32_t _i = 0; _i < (ctx)->tagInfo.numOfTagCols; ++_i) { \
575
      SqlFunctionCtx* __ctx = (ctx)->tagInfo.pTagCtxList[_i];      \
H
Haojun Liao 已提交
576
      __ctx->fpSet.process(__ctx);                                 \
577 578 579
    }                                                              \
  } while (0);

580 581
#define DO_UPDATE_SUBSID_RES(ctx, ts)                          \
  do {                                                         \
582
    for (int32_t _i = 0; _i < (ctx)->subsidiaries.num; ++_i) { \
583 584 585 586 587 588 589
      SqlFunctionCtx* __ctx = (ctx)->subsidiaries.pCtx[_i];    \
      if (__ctx->functionId == FUNCTION_TS_DUMMY) {            \
        __ctx->tag.i = (ts);                                   \
        __ctx->tag.nType = TSDB_DATA_TYPE_BIGINT;              \
      }                                                        \
      __ctx->fpSet.process(__ctx);                             \
    }                                                          \
590 591 592
  } while (0)

#define UPDATE_DATA(ctx, left, right, num, sign, _ts) \
H
Haojun Liao 已提交
593 594 595 596 597 598
  do {                                                \
    if (((left) < (right)) ^ (sign)) {                \
      (left) = (right);                               \
      DO_UPDATE_SUBSID_RES(ctx, _ts);                 \
      (num) += 1;                                     \
    }                                                 \
599 600
  } while (0)

H
Haojun Liao 已提交
601
#define LOOPCHECK_N(val, _col, ctx, _t, _nrow, _start, sign, num)        \
602
  do {                                                                   \
603
    _t* d = (_t*)((_col)->pData);                                        \
604 605 606 607 608 609 610 611 612
    for (int32_t i = (_start); i < (_nrow) + (_start); ++i) {            \
      if (((_col)->hasNull) && colDataIsNull_f((_col)->nullbitmap, i)) { \
        continue;                                                        \
      }                                                                  \
      TSKEY ts = (ctx)->ptsList != NULL ? GET_TS_DATA(ctx, i) : 0;       \
      UPDATE_DATA(ctx, val, d[i], num, sign, ts);                        \
    }                                                                    \
  } while (0)

613
int32_t doMinMaxHelper(SqlFunctionCtx* pCtx, int32_t isMinFunc) {
614 615 616
  int32_t numOfElems = 0;

  SInputColumnInfoData* pInput = &pCtx->input;
617
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
618 619

  SColumnInfoData* pCol = pInput->pData[0];
620
  int32_t          type = pCol->info.type;
621 622

  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
623
  char*                buf = GET_ROWCELL_INTERBUF(pResInfo);
624 625 626 627 628 629 630 631 632 633 634 635 636 637

  // data in current data block are qualified to the query
  if (pInput->colDataAggIsSet) {
    numOfElems = pInput->numOfRows - pAgg->numOfNull;
    ASSERT(pInput->numOfRows == pInput->totalRows && numOfElems >= 0);

    if (numOfElems == 0) {
      return numOfElems;
    }

    void*   tval = NULL;
    int16_t index = 0;

    if (isMinFunc) {
638
      tval = &pInput->pColumnDataAgg[0]->min;
639 640
      index = pInput->pColumnDataAgg[0]->minIndex;
    } else {
641
      tval = &pInput->pColumnDataAgg[0]->max;
642 643 644
      index = pInput->pColumnDataAgg[0]->maxIndex;
    }

645
    // the index is the original position, not the relative position
646
    TSKEY key = (pCtx->ptsList != NULL) ? pCtx->ptsList[index] : TSKEY_INITIAL_VAL;
647 648

    if (IS_SIGNED_NUMERIC_TYPE(type)) {
649 650
      int64_t prev = 0;
      GET_TYPED_DATA(prev, int64_t, type, buf);
651

652 653
      int64_t val = GET_INT64_VAL(tval);
      if ((prev < val) ^ isMinFunc) {
654
        *(int64_t*)buf = val;
655 656
        for (int32_t i = 0; i < (pCtx)->subsidiaries.num; ++i) {
          SqlFunctionCtx* __ctx = pCtx->subsidiaries.pCtx[i];
657 658 659 660 661 662 663 664
          if (__ctx->functionId == FUNCTION_TS_DUMMY) {  // TODO refactor
            __ctx->tag.i = key;
            __ctx->tag.nType = TSDB_DATA_TYPE_BIGINT;
          }

          __ctx->fpSet.process(__ctx);
        }
      }
665
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
666 667 668
      uint64_t prev = 0;
      GET_TYPED_DATA(prev, uint64_t, type, buf);

669
      uint64_t val = GET_UINT64_VAL(tval);
H
Haojun Liao 已提交
670
      if ((prev < val) ^ isMinFunc) {
671
        *(uint64_t*)buf = val;
672 673
        for (int32_t i = 0; i < (pCtx)->subsidiaries.num; ++i) {
          SqlFunctionCtx* __ctx = pCtx->subsidiaries.pCtx[i];
H
Haojun Liao 已提交
674 675 676 677
          if (__ctx->functionId == FUNCTION_TS_DUMMY) {  // TODO refactor
            __ctx->tag.i = key;
            __ctx->tag.nType = TSDB_DATA_TYPE_BIGINT;
          }
678

H
Haojun Liao 已提交
679 680 681 682
          __ctx->fpSet.process(__ctx);
        }
      }
    } else if (type == TSDB_DATA_TYPE_DOUBLE) {
683 684
      double val = GET_DOUBLE_VAL(tval);
      UPDATE_DATA(pCtx, *(double*)buf, val, numOfElems, isMinFunc, key);
685
    } else if (type == TSDB_DATA_TYPE_FLOAT) {
686
      double val = GET_DOUBLE_VAL(tval);
687
      UPDATE_DATA(pCtx, *(float*)buf, val, numOfElems, isMinFunc, key);
688 689 690 691 692 693 694 695
    }

    return numOfElems;
  }

  int32_t start = pInput->startRowIndex;
  int32_t numOfRows = pInput->numOfRows;

696 697
  if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
    if (type == TSDB_DATA_TYPE_TINYINT || type == TSDB_DATA_TYPE_BOOL) {
698 699
      LOOPCHECK_N(*(int8_t*)buf, pCol, pCtx, int8_t, numOfRows, start, isMinFunc, numOfElems);
    } else if (type == TSDB_DATA_TYPE_SMALLINT) {
700
      LOOPCHECK_N(*(int16_t*)buf, pCol, pCtx, int16_t, numOfRows, start, isMinFunc, numOfElems);
701
    } else if (type == TSDB_DATA_TYPE_INT) {
702 703
      int32_t* pData = (int32_t*)pCol->pData;
      int32_t* val = (int32_t*)buf;
704

H
Haojun Liao 已提交
705
      for (int32_t i = start; i < start + numOfRows; ++i) {
706 707 708 709 710 711
        if ((pCol->hasNull) && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        if ((*val < pData[i]) ^ isMinFunc) {
          *val = pData[i];
712
          TSKEY ts = (pCtx->ptsList != NULL) ? GET_TS_DATA(pCtx, i) : 0;
713 714 715 716 717 718 719 720 721
          DO_UPDATE_SUBSID_RES(pCtx, ts);
        }

        numOfElems += 1;
      }

#if defined(_DEBUG_VIEW)
      qDebug("max value updated:%d", *retVal);
#endif
722
    } else if (type == TSDB_DATA_TYPE_BIGINT) {
723
      LOOPCHECK_N(*(int64_t*)buf, pCol, pCtx, int64_t, numOfRows, start, isMinFunc, numOfElems);
724
    }
725 726
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
    if (type == TSDB_DATA_TYPE_UTINYINT) {
727
      LOOPCHECK_N(*(uint8_t*)buf, pCol, pCtx, uint8_t, numOfRows, start, isMinFunc, numOfElems);
728
    } else if (type == TSDB_DATA_TYPE_USMALLINT) {
729
      LOOPCHECK_N(*(uint16_t*)buf, pCol, pCtx, uint16_t, numOfRows, start, isMinFunc, numOfElems);
730
    } else if (type == TSDB_DATA_TYPE_UINT) {
731
      LOOPCHECK_N(*(uint32_t*)buf, pCol, pCtx, uint32_t, numOfRows, start, isMinFunc, numOfElems);
732
    } else if (type == TSDB_DATA_TYPE_UBIGINT) {
733
      LOOPCHECK_N(*(uint64_t*)buf, pCol, pCtx, uint64_t, numOfRows, start, isMinFunc, numOfElems);
734
    }
735
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
736
    LOOPCHECK_N(*(double*)buf, pCol, pCtx, double, numOfRows, start, isMinFunc, numOfElems);
737
  } else if (type == TSDB_DATA_TYPE_FLOAT) {
738
    LOOPCHECK_N(*(float*)buf, pCol, pCtx, float, numOfRows, start, isMinFunc, numOfElems);
739 740 741
  }

  return numOfElems;
H
Haojun Liao 已提交
742
}
743

744
int32_t minFunction(SqlFunctionCtx* pCtx) {
745 746
  int32_t numOfElems = doMinMaxHelper(pCtx, 1);
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
wmmhello's avatar
wmmhello 已提交
747
  return TSDB_CODE_SUCCESS;
748 749
}

750
int32_t maxFunction(SqlFunctionCtx* pCtx) {
751 752
  int32_t numOfElems = doMinMaxHelper(pCtx, 0);
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
wmmhello's avatar
wmmhello 已提交
753
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
754 755 756 757 758 759 760
}

bool getStddevFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SStddevRes);
  return true;
}

761
bool stddevFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
H
Haojun Liao 已提交
762 763 764 765 766 767 768 769 770
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

  SStddevRes* pRes = GET_ROWCELL_INTERBUF(pResultInfo);
  memset(pRes, 0, sizeof(SStddevRes));
  return true;
}

H
Haojun Liao 已提交
771
int32_t stddevFunction(SqlFunctionCtx* pCtx) {
H
Haojun Liao 已提交
772 773 774 775
  int32_t numOfElem = 0;

  // Only the pre-computing information loaded and actual data does not loaded
  SInputColumnInfoData* pInput = &pCtx->input;
H
Haojun Liao 已提交
776
  int32_t               type = pInput->pData[0]->info.type;
H
Haojun Liao 已提交
777 778 779

  SStddevRes* pStddevRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

H
Haojun Liao 已提交
780 781
  // computing based on the true data block
  SColumnInfoData* pCol = pInput->pData[0];
H
Haojun Liao 已提交
782

H
Haojun Liao 已提交
783 784
  int32_t start = pInput->startRowIndex;
  int32_t numOfRows = pInput->numOfRows;
H
Haojun Liao 已提交
785

H
Haojun Liao 已提交
786 787
  switch (type) {
    case TSDB_DATA_TYPE_TINYINT: {
788 789 790 791
      int8_t* plist = (int8_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + start; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
H
Haojun Liao 已提交
792
        }
H
Haojun Liao 已提交
793

794 795 796 797
        numOfElem += 1;
        pStddevRes->count += 1;
        pStddevRes->isum += plist[i];
        pStddevRes->quadraticISum += plist[i] * plist[i];
H
Haojun Liao 已提交
798 799
      }

800 801 802 803
      break;
    }

    case TSDB_DATA_TYPE_SMALLINT: {
H
Haojun Liao 已提交
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
      int16_t* plist = (int16_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pStddevRes->count += 1;
        pStddevRes->isum += plist[i];
        pStddevRes->quadraticISum += plist[i] * plist[i];
      }
      break;
    }

    case TSDB_DATA_TYPE_INT: {
      int32_t* plist = (int32_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pStddevRes->count += 1;
        pStddevRes->isum += plist[i];
        pStddevRes->quadraticISum += plist[i] * plist[i];
      }

      break;
    }

    case TSDB_DATA_TYPE_BIGINT: {
      int64_t* plist = (int64_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pStddevRes->count += 1;
        pStddevRes->isum += plist[i];
        pStddevRes->quadraticISum += plist[i] * plist[i];
      }
      break;
    }

    case TSDB_DATA_TYPE_FLOAT: {
      float* plist = (float*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pStddevRes->count += 1;
G
Ganlin Zhao 已提交
858 859
        pStddevRes->dsum += plist[i];
        pStddevRes->quadraticDSum += plist[i] * plist[i];
H
Haojun Liao 已提交
860 861 862 863
      }
      break;
    }

H
Haojun Liao 已提交
864 865 866 867 868 869 870 871 872
    case TSDB_DATA_TYPE_DOUBLE: {
      double* plist = (double*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pStddevRes->count += 1;
G
Ganlin Zhao 已提交
873 874
        pStddevRes->dsum += plist[i];
        pStddevRes->quadraticDSum += plist[i] * plist[i];
H
Haojun Liao 已提交
875 876 877 878 879 880 881 882
      }
      break;
    }

    default:
      break;
  }

H
Haojun Liao 已提交
883 884
  // data in the check operation are all null, not output
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
wmmhello's avatar
wmmhello 已提交
885
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
886 887
}

H
Haojun Liao 已提交
888
int32_t stddevFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
G
Ganlin Zhao 已提交
889
  SInputColumnInfoData* pInput = &pCtx->input;
890 891 892
  int32_t               type = pInput->pData[0]->info.type;
  SStddevRes*           pStddevRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  double                avg;
G
Ganlin Zhao 已提交
893
  if (IS_INTEGER_TYPE(type)) {
894 895
    avg = pStddevRes->isum / ((double)pStddevRes->count);
    pStddevRes->result = sqrt(pStddevRes->quadraticISum / ((double)pStddevRes->count) - avg * avg);
G
Ganlin Zhao 已提交
896
  } else {
897 898
    avg = pStddevRes->dsum / ((double)pStddevRes->count);
    pStddevRes->result = sqrt(pStddevRes->quadraticDSum / ((double)pStddevRes->count) - avg * avg);
G
Ganlin Zhao 已提交
899
  }
900

901
  return functionFinalize(pCtx, pBlock);
H
Haojun Liao 已提交
902 903 904 905 906 907 908
}

bool getPercentileFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SPercentileInfo);
  return true;
}

909
bool percentileFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
H
Haojun Liao 已提交
910 911 912 913 914
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

  // in the first round, get the min-max value of all involved data
915
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
H
Haojun Liao 已提交
916 917 918 919 920
  SET_DOUBLE_VAL(&pInfo->minval, DBL_MAX);
  SET_DOUBLE_VAL(&pInfo->maxval, -DBL_MAX);
  pInfo->numOfElems = 0;

  return true;
H
Haojun Liao 已提交
921 922
}

923 924 925
int32_t percentileFunction(SqlFunctionCtx* pCtx) {
  int32_t              notNullElems = 0;
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
926 927

  SInputColumnInfoData* pInput = &pCtx->input;
928
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
H
Haojun Liao 已提交
929

930 931
  SColumnInfoData* pCol = pInput->pData[0];
  int32_t          type = pCol->info.type;
932

933
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
H
Haojun Liao 已提交
934 935
  if (pCtx->currentStage == REPEAT_SCAN && pInfo->stage == 0) {
    pInfo->stage += 1;
H
Haojun Liao 已提交
936

H
Haojun Liao 已提交
937 938 939
    // all data are null, set it completed
    if (pInfo->numOfElems == 0) {
      pResInfo->complete = true;
H
Haojun Liao 已提交
940
      return 0;
H
Haojun Liao 已提交
941 942 943 944 945 946 947
    } else {
      pInfo->pMemBucket = tMemBucketCreate(pCtx->inputBytes, pCtx->inputType, pInfo->minval, pInfo->maxval);
    }
  }

  // the first stage, only acquire the min/max value
  if (pInfo->stage == 0) {
948
    if (pCtx->input.colDataAggIsSet) {
H
Haojun Liao 已提交
949
      double tmin = 0.0, tmax = 0.0;
950 951 952 953 954 955 956 957 958
      if (IS_SIGNED_NUMERIC_TYPE(type)) {
        tmin = (double)GET_INT64_VAL(&pAgg->min);
        tmax = (double)GET_INT64_VAL(&pAgg->max);
      } else if (IS_FLOAT_TYPE(type)) {
        tmin = GET_DOUBLE_VAL(&pAgg->min);
        tmax = GET_DOUBLE_VAL(&pAgg->max);
      } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
        tmin = (double)GET_UINT64_VAL(&pAgg->min);
        tmax = (double)GET_UINT64_VAL(&pAgg->max);
H
Haojun Liao 已提交
959 960 961 962 963 964 965 966 967 968
      }

      if (GET_DOUBLE_VAL(&pInfo->minval) > tmin) {
        SET_DOUBLE_VAL(&pInfo->minval, tmin);
      }

      if (GET_DOUBLE_VAL(&pInfo->maxval) < tmax) {
        SET_DOUBLE_VAL(&pInfo->maxval, tmax);
      }

969
      pInfo->numOfElems += (pInput->numOfRows - pAgg->numOfNull);
H
Haojun Liao 已提交
970
    } else {
971 972 973 974
      // check the valid data one by one
      int32_t start = pInput->startRowIndex;
      for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
        if (colDataIsNull_f(pCol->nullbitmap, i)) {
H
Haojun Liao 已提交
975 976 977
          continue;
        }

978
        char* data = colDataGetData(pCol, i);
979

H
Haojun Liao 已提交
980 981 982 983 984 985 986 987 988 989 990 991 992 993
        double v = 0;
        GET_TYPED_DATA(v, double, pCtx->inputType, data);
        if (v < GET_DOUBLE_VAL(&pInfo->minval)) {
          SET_DOUBLE_VAL(&pInfo->minval, v);
        }

        if (v > GET_DOUBLE_VAL(&pInfo->maxval)) {
          SET_DOUBLE_VAL(&pInfo->maxval, v);
        }

        pInfo->numOfElems += 1;
      }
    }

H
Haojun Liao 已提交
994
    return 0;
H
Haojun Liao 已提交
995 996 997
  }

  // the second stage, calculate the true percentile value
998 999 1000
  int32_t start = pInput->startRowIndex;
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
    if (colDataIsNull_f(pCol->nullbitmap, i)) {
H
Haojun Liao 已提交
1001 1002 1003
      continue;
    }

1004
    char* data = colDataGetData(pCol, i);
1005

H
Haojun Liao 已提交
1006 1007 1008 1009
    notNullElems += 1;
    tMemBucketPut(pInfo->pMemBucket, data, 1);
  }

1010
  SET_VAL(pResInfo, notNullElems, 1);
wmmhello's avatar
wmmhello 已提交
1011
  return TSDB_CODE_SUCCESS;
1012 1013
}

1014
int32_t percentileFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1015
  SVariant* pVal = &pCtx->param[1].param;
1016
  double    v = pVal->nType == TSDB_DATA_TYPE_INT ? pVal->i : pVal->d;
H
Haojun Liao 已提交
1017

1018 1019
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  SPercentileInfo*     ppInfo = (SPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
1020

1021
  tMemBucket* pMemBucket = ppInfo->pMemBucket;
1022 1023 1024 1025 1026
  if (pMemBucket != NULL && pMemBucket->total > 0) {  // check for null
    SET_DOUBLE_VAL(&ppInfo->result, getPercentile(pMemBucket, v));
  }

  tMemBucketDestroy(pMemBucket);
1027
  return functionFinalize(pCtx, pBlock);
H
Haojun Liao 已提交
1028
}
H
Haojun Liao 已提交
1029

H
Haojun Liao 已提交
1030 1031
bool getFirstLastFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
  SColumnNode* pNode = nodesListGetNode(pFunc->pParameterList, 0);
1032
  pEnv->calcMemSize = pNode->node.resType.bytes + sizeof(int64_t);
H
Haojun Liao 已提交
1033 1034 1035
  return true;
}

1036 1037 1038 1039 1040
static FORCE_INLINE TSKEY getRowPTs(SColumnInfoData* pTsColInfo, int32_t rowIndex) {
  if (pTsColInfo == NULL) {
    return 0;
  }

1041
  return *(TSKEY*)colDataGetData(pTsColInfo, rowIndex);
1042 1043
}

1044 1045
// This ordinary first function does not care if current scan is ascending order or descending order scan
// the OPTIMIZED version of first function will only handle the ascending order scan
1046
int32_t firstFunction(SqlFunctionCtx* pCtx) {
H
Haojun Liao 已提交
1047 1048
  int32_t numOfElems = 0;

1049 1050
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  char*                buf = GET_ROWCELL_INTERBUF(pResInfo);
H
Haojun Liao 已提交
1051 1052

  SInputColumnInfoData* pInput = &pCtx->input;
1053
  SColumnInfoData*      pInputCol = pInput->pData[0];
H
Haojun Liao 已提交
1054

1055 1056
  int32_t bytes = pInputCol->info.bytes;

H
Haojun Liao 已提交
1057
  // All null data column, return directly.
H
Haojun Liao 已提交
1058
  if (pInput->colDataAggIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows)) {
H
Haojun Liao 已提交
1059
    ASSERT(pInputCol->hasNull == true);
H
Haojun Liao 已提交
1060
    return 0;
H
Haojun Liao 已提交
1061 1062
  }

1063
  SColumnDataAgg* pColAgg = (pInput->colDataAggIsSet) ? pInput->pColumnDataAgg[0] : NULL;
1064

1065 1066
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
1067

1068
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083

  if (blockDataOrder == TSDB_ORDER_ASC) {
    // filter according to current result firstly
    if (pResInfo->numOfRes > 0) {
      TSKEY ts = *(TSKEY*)(buf + bytes);
      if (ts < startKey) {
        return TSDB_CODE_SUCCESS;
      }
    }

    for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
        continue;
      }

1084 1085
      numOfElems++;

1086
      char* data = colDataGetData(pInputCol, i);
1087
      TSKEY cts = getRowPTs(pInput->pPTS, i);
1088

1089
      if (pResInfo->numOfRes == 0 || *(TSKEY*)(buf + bytes) > cts) {
1090 1091
        memcpy(buf, data, bytes);
        *(TSKEY*)(buf + bytes) = cts;
1092
        //        DO_UPDATE_TAG_COLUMNS(pCtx, ts);
1093 1094

        pResInfo->numOfRes = 1;
1095
        break;
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
      }
    }
  } else {
    // in case of descending order time stamp serial, which usually happens as the results of the nest query,
    // all data needs to be check.
    if (pResInfo->numOfRes > 0) {
      TSKEY ts = *(TSKEY*)(buf + bytes);
      if (ts < endKey) {
        return TSDB_CODE_SUCCESS;
      }
H
Haojun Liao 已提交
1106 1107
    }

1108 1109 1110 1111 1112
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
        continue;
      }

1113 1114
      numOfElems++;

1115
      char* data = colDataGetData(pInputCol, i);
1116
      TSKEY cts = getRowPTs(pInput->pPTS, i);
1117

1118
      if (pResInfo->numOfRes == 0 || *(TSKEY*)(buf + bytes) > cts) {
1119 1120
        memcpy(buf, data, bytes);
        *(TSKEY*)(buf + bytes) = cts;
1121
        //        DO_UPDATE_TAG_COLUMNS(pCtx, ts);
1122
        pResInfo->numOfRes = 1;
1123
        break;
1124 1125
      }
    }
H
Haojun Liao 已提交
1126 1127 1128
  }

  SET_VAL(pResInfo, numOfElems, 1);
wmmhello's avatar
wmmhello 已提交
1129
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1130 1131
}

1132
int32_t lastFunction(SqlFunctionCtx* pCtx) {
H
Haojun Liao 已提交
1133 1134
  int32_t numOfElems = 0;

1135 1136
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  char*                buf = GET_ROWCELL_INTERBUF(pResInfo);
H
Haojun Liao 已提交
1137 1138

  SInputColumnInfoData* pInput = &pCtx->input;
1139
  SColumnInfoData*      pInputCol = pInput->pData[0];
H
Haojun Liao 已提交
1140

1141 1142
  int32_t bytes = pInputCol->info.bytes;

H
Haojun Liao 已提交
1143
  // All null data column, return directly.
1144
  if (pInput->colDataAggIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows)) {
H
Haojun Liao 已提交
1145
    ASSERT(pInputCol->hasNull == true);
H
Haojun Liao 已提交
1146
    return 0;
H
Haojun Liao 已提交
1147 1148
  }

1149
  SColumnDataAgg* pColAgg = (pInput->colDataAggIsSet) ? pInput->pColumnDataAgg[0] : NULL;
1150 1151 1152 1153

  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);

1154
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
1155 1156

  if (blockDataOrder == TSDB_ORDER_ASC) {
H
Haojun Liao 已提交
1157
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
1158
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
H
Haojun Liao 已提交
1159 1160 1161 1162
        continue;
      }

      numOfElems++;
1163 1164 1165

      char* data = colDataGetData(pInputCol, i);
      TSKEY cts = getRowPTs(pInput->pPTS, i);
1166
      if (pResInfo->numOfRes == 0 || *(TSKEY*)(buf + bytes) < cts) {
1167 1168 1169 1170 1171
        memcpy(buf, data, bytes);
        *(TSKEY*)(buf + bytes) = cts;
        //        DO_UPDATE_TAG_COLUMNS(pCtx, ts);
        pResInfo->numOfRes = 1;
      }
H
Haojun Liao 已提交
1172 1173
      break;
    }
1174
  } else {  // descending order
H
Haojun Liao 已提交
1175
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
1176
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
H
Haojun Liao 已提交
1177 1178 1179
        continue;
      }

1180
      numOfElems++;
H
Haojun Liao 已提交
1181

1182 1183
      char* data = colDataGetData(pInputCol, i);
      TSKEY cts = getRowPTs(pInput->pPTS, i);
1184
      if (pResInfo->numOfRes == 0 || *(TSKEY*)(buf + bytes) < cts) {
1185 1186 1187
        memcpy(buf, data, bytes);
        *(TSKEY*)(buf + bytes) = cts;
        pResInfo->numOfRes = 1;
1188
        //        DO_UPDATE_TAG_COLUMNS(pCtx, ts);
H
Haojun Liao 已提交
1189 1190 1191 1192 1193 1194
      }
      break;
    }
  }

  SET_VAL(pResInfo, numOfElems, 1);
wmmhello's avatar
wmmhello 已提交
1195
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1196
}
H
Haojun Liao 已提交
1197

H
Haojun Liao 已提交
1198 1199 1200 1201 1202
bool getDiffFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SDiffInfo);
  return true;
}

1203
bool diffFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
H
Haojun Liao 已提交
1204 1205 1206 1207 1208
  if (!functionSetup(pCtx, pResInfo)) {
    return false;
  }

  SDiffInfo* pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
1209
  pDiffInfo->hasPrev = false;
H
Haojun Liao 已提交
1210
  pDiffInfo->prev.i64 = 0;
1211
  pDiffInfo->ignoreNegative = false;  // TODO set correct param
H
Haojun Liao 已提交
1212 1213
  pDiffInfo->includeNull = false;
  pDiffInfo->firstOutput = false;
H
Haojun Liao 已提交
1214 1215 1216
  return true;
}

1217 1218 1219
int32_t diffFunction(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
H
Haojun Liao 已提交
1220 1221

  SInputColumnInfoData* pInput = &pCtx->input;
1222
  SColumnInfoData*      pInputCol = pInput->pData[0];
H
Haojun Liao 已提交
1223

1224
  bool    isFirstBlock = (pDiffInfo->hasPrev == false);
H
Haojun Liao 已提交
1225 1226
  int32_t numOfElems = 0;

H
Haojun Liao 已提交
1227
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
1228
  TSKEY*           tsList = (int64_t*)pInput->pPTS->pData;
H
Haojun Liao 已提交
1229

H
Haojun Liao 已提交
1230
  int32_t startOffset = pCtx->offset;
H
Haojun Liao 已提交
1231 1232
  switch (pInputCol->info.type) {
    case TSDB_DATA_TYPE_INT: {
1233
      SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
      if (pCtx->order == TSDB_ORDER_ASC) {
        for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
          int32_t pos = startOffset + (isFirstBlock ? (numOfElems - 1) : numOfElems);
          if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
            if (pDiffInfo->includeNull) {
              colDataSetNull_f(pOutput->nullbitmap, pos);
              if (tsList != NULL) {
                colDataAppendInt64(pTsOutput, pos, &tsList[i]);
              }

              numOfElems += 1;
            }
            continue;
          }

          int32_t v = *(int32_t*)colDataGetData(pInputCol, i);
          if (pDiffInfo->hasPrev) {
            int32_t delta = (int32_t)(v - pDiffInfo->prev.i64);  // direct previous may be null
            if (delta < 0 && pDiffInfo->ignoreNegative) {
              colDataSetNull_f(pOutput->nullbitmap, pos);
            } else {
              colDataAppendInt32(pOutput, pos, &delta);
H
Haojun Liao 已提交
1256 1257
            }

1258 1259 1260
            if (pTsOutput != NULL) {
              colDataAppendInt64(pTsOutput, pos, &tsList[i]);
            }
H
Haojun Liao 已提交
1261
          }
1262 1263 1264 1265

          pDiffInfo->prev.i64 = v;
          pDiffInfo->hasPrev = true;
          numOfElems++;
H
Haojun Liao 已提交
1266
        }
1267 1268 1269 1270 1271
      } else {
        for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
          int32_t v = *(int32_t*)colDataGetData(pInputCol, i);
          int32_t pos = startOffset + numOfElems;

1272
          // there is a row of previous data block to be handled in the first place.
1273
          if (pDiffInfo->hasPrev) {
1274
            int32_t delta = (int32_t)(pDiffInfo->prev.i64 - v);  // direct previous may be null
1275 1276 1277 1278 1279
            if (delta < 0 && pDiffInfo->ignoreNegative) {
              colDataSetNull_f(pOutput->nullbitmap, pos);
            } else {
              colDataAppendInt32(pOutput, pos, &delta);
            }
H
Haojun Liao 已提交
1280

1281
            if (pTsOutput != NULL) {
1282
              colDataAppendInt64(pTsOutput, pos, &pDiffInfo->prevTs);
1283 1284
            }
            pDiffInfo->hasPrev = false;
H
Haojun Liao 已提交
1285 1286
          }

1287
          // it is not the last row of current block
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302
          if (i < pInput->numOfRows + pInput->startRowIndex - 1) {
            int32_t next = *(int32_t*)colDataGetData(pInputCol, i + 1);

            int32_t delta = v - next;  // direct previous may be null
            colDataAppendInt32(pOutput, pos, &delta);

            if (pTsOutput != NULL) {
              colDataAppendInt64(pTsOutput, pos, &tsList[i]);
            }
          } else {
            pDiffInfo->prev.i64 = v;
            if (pTsOutput != NULL) {
              pDiffInfo->prevTs = tsList[i];
            }
            pDiffInfo->hasPrev = true;
H
Haojun Liao 已提交
1303
          }
1304
          numOfElems++;
H
Haojun Liao 已提交
1305 1306 1307 1308 1309
        }

      }
      break;
    }
H
Haojun Liao 已提交
1310

H
Haojun Liao 已提交
1311
    case TSDB_DATA_TYPE_BIGINT: {
1312
      SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
1313
      for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
H
Haojun Liao 已提交
1314 1315 1316 1317 1318
        if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
          continue;
        }

        int32_t v = 0;
H
Haojun Liao 已提交
1319
        if (pDiffInfo->hasPrev) {
1320
          v = *(int64_t*)colDataGetData(pInputCol, i);
H
Haojun Liao 已提交
1321 1322 1323 1324 1325
          int64_t delta = (int64_t)(v - pDiffInfo->prev.i64);  // direct previous may be null
          if (pDiffInfo->ignoreNegative) {
            continue;
          }

1326 1327 1328 1329 1330
          //          *(pOutput++) = delta;
          //          *pTimestamp  = (tsList != NULL)? tsList[i]:0;
          //
          //          pOutput    += 1;
          //          pTimestamp += 1;
H
Haojun Liao 已提交
1331 1332 1333
        }

        pDiffInfo->prev.i64 = v;
H
Haojun Liao 已提交
1334
        pDiffInfo->hasPrev = true;
H
Haojun Liao 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350
        numOfElems++;
      }
      break;
    }
#if 0
    case TSDB_DATA_TYPE_DOUBLE: {
      double *pData = (double *)data;
      double *pOutput = (double *)pCtx->pOutput;

      for (; i < pCtx->size && i >= 0; i += step) {
        if (pCtx->hasNull && isNull((const char*) &pData[i], pCtx->inputType)) {
          continue;
        }
        if ((pDiffInfo->ignoreNegative) && (pData[i] < 0)) {
          continue;
        }
H
Haojun Liao 已提交
1351

H
Haojun Liao 已提交
1352
        if (pDiffInfo->hasPrev) {  // initial value is not set yet
H
Haojun Liao 已提交
1353 1354 1355 1356 1357 1358 1359
          SET_DOUBLE_VAL(pOutput, pData[i] - pDiffInfo->d64Prev);  // direct previous may be null
          *pTimestamp = (tsList != NULL)? tsList[i]:0;
          pOutput    += 1;
          pTimestamp += 1;
        }

        pDiffInfo->d64Prev = pData[i];
H
Haojun Liao 已提交
1360
        pDiffInfo->hasPrev = true;
H
Haojun Liao 已提交
1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
        numOfElems++;
      }
      break;
    }
    case TSDB_DATA_TYPE_FLOAT: {
      float *pData = (float *)data;
      float *pOutput = (float *)pCtx->pOutput;

      for (; i < pCtx->size && i >= 0; i += step) {
        if (pCtx->hasNull && isNull((const char*) &pData[i], pCtx->inputType)) {
          continue;
        }
        if ((pDiffInfo->ignoreNegative) && (pData[i] < 0)) {
          continue;
        }

H
Haojun Liao 已提交
1377
        if (pDiffInfo->hasPrev) {  // initial value is not set yet
H
Haojun Liao 已提交
1378 1379 1380 1381 1382 1383 1384
          *pOutput = (float)(pData[i] - pDiffInfo->d64Prev);  // direct previous may be null
          *pTimestamp = (tsList != NULL)? tsList[i]:0;
          pOutput    += 1;
          pTimestamp += 1;
        }

        pDiffInfo->d64Prev = pData[i];
H
Haojun Liao 已提交
1385
        pDiffInfo->hasPrev = true;
H
Haojun Liao 已提交
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
        numOfElems++;
      }
      break;
    }
    case TSDB_DATA_TYPE_SMALLINT: {
      int16_t *pData = (int16_t *)data;
      int16_t *pOutput = (int16_t *)pCtx->pOutput;

      for (; i < pCtx->size && i >= 0; i += step) {
        if (pCtx->hasNull && isNull((const char*) &pData[i], pCtx->inputType)) {
          continue;
        }
        if ((pDiffInfo->ignoreNegative) && (pData[i] < 0)) {
          continue;
        }

H
Haojun Liao 已提交
1402
        if (pDiffInfo->hasPrev) {  // initial value is not set yet
H
Haojun Liao 已提交
1403 1404 1405 1406 1407 1408 1409
          *pOutput = (int16_t)(pData[i] - pDiffInfo->i64Prev);  // direct previous may be null
          *pTimestamp = (tsList != NULL)? tsList[i]:0;
          pOutput    += 1;
          pTimestamp += 1;
        }

        pDiffInfo->i64Prev = pData[i];
H
Haojun Liao 已提交
1410
        pDiffInfo->hasPrev = true;
H
Haojun Liao 已提交
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
        numOfElems++;
      }
      break;
    }

    case TSDB_DATA_TYPE_TINYINT: {
      int8_t *pData = (int8_t *)data;
      int8_t *pOutput = (int8_t *)pCtx->pOutput;

      for (; i < pCtx->size && i >= 0; i += step) {
        if (pCtx->hasNull && isNull((char *)&pData[i], pCtx->inputType)) {
          continue;
        }
        if ((pDiffInfo->ignoreNegative) && (pData[i] < 0)) {
          continue;
        }

H
Haojun Liao 已提交
1428
        if (pDiffInfo->hasPrev) {  // initial value is not set yet
H
Haojun Liao 已提交
1429 1430 1431 1432 1433 1434 1435
          *pOutput = (int8_t)(pData[i] - pDiffInfo->i64Prev);  // direct previous may be null
          *pTimestamp = (tsList != NULL)? tsList[i]:0;
          pOutput    += 1;
          pTimestamp += 1;
        }

        pDiffInfo->i64Prev = pData[i];
H
Haojun Liao 已提交
1436
        pDiffInfo->hasPrev = true;
H
Haojun Liao 已提交
1437 1438 1439 1440 1441 1442 1443
        numOfElems++;
      }
      break;
    }
#endif
    default:
      break;
1444
      //      qError("error input type");
H
Haojun Liao 已提交
1445 1446 1447
  }

  // initial value is not set yet
1448
  if (numOfElems <= 0) {
H
Haojun Liao 已提交
1449 1450 1451 1452 1453
    /*
     * 1. current block and blocks before are full of null
     * 2. current block may be null value
     */
    assert(pCtx->hasNull);
wmmhello's avatar
wmmhello 已提交
1454
    return 0;
H
Haojun Liao 已提交
1455
  } else {
1456
    return (isFirstBlock) ? numOfElems - 1 : numOfElems;
H
Haojun Liao 已提交
1457
  }
H
Haojun Liao 已提交
1458
}
H
Haojun Liao 已提交
1459

1460
bool getTopBotFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
1461
  SValueNode* pkNode = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
1462
  pEnv->calcMemSize = sizeof(STopBotRes) + pkNode->datum.i * sizeof(STopBotResItem);
1463 1464 1465
  return true;
}

1466 1467 1468 1469
static STopBotRes* getTopBotOutputInfo(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  STopBotRes*          pRes = GET_ROWCELL_INTERBUF(pResInfo);
  pRes->pItems = (STopBotResItem*)((char*)pRes + sizeof(STopBotRes));
1470 1471

  return pRes;
1472 1473
}

1474 1475
static void doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock, uint16_t type,
                            uint64_t uid, SResultRowEntryInfo* pEntryInfo);
1476

1477 1478 1479
static void saveTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STopBotResItem* pItem);
static void copyTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STopBotResItem* pItem);

1480 1481 1482
int32_t topFunction(SqlFunctionCtx* pCtx) {
  int32_t              numOfElems = 0;
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1483

1484 1485 1486
  //  if ((void *)pRes->res[0] != (void *)((char *)pRes + sizeof(STopBotRes) + POINTER_BYTES * pCtx->param[0].i)) {
  //    buildTopBotStruct(pRes, pCtx);
  //  }
1487 1488

  SInputColumnInfoData* pInput = &pCtx->input;
1489
  SColumnInfoData*      pCol = pInput->pData[0];
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502

  int32_t type = pInput->pData[0]->info.type;

  int32_t start = pInput->startRowIndex;
  int32_t numOfRows = pInput->numOfRows;

  for (int32_t i = start; i < numOfRows + start; ++i) {
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
      continue;
    }
    numOfElems++;

    char* data = colDataGetData(pCol, i);
1503
    doAddIntoResult(pCtx, data, i, pCtx->pSrcBlock, type, pInput->uid, pResInfo);
1504 1505
  }

1506
  return TSDB_CODE_SUCCESS;
1507 1508
}

1509 1510
static int32_t topBotResComparFn(const void* p1, const void* p2, const void* param) {
  uint16_t type = *(uint16_t*)param;
1511

1512 1513
  STopBotResItem* val1 = (STopBotResItem*)p1;
  STopBotResItem* val2 = (STopBotResItem*)p2;
1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535

  if (IS_SIGNED_NUMERIC_TYPE(type)) {
    if (val1->v.i == val2->v.i) {
      return 0;
    }

    return (val1->v.i > val2->v.i) ? 1 : -1;
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
    if (val1->v.u == val2->v.u) {
      return 0;
    }

    return (val1->v.u > val2->v.u) ? 1 : -1;
  }

  if (val1->v.d == val2->v.d) {
    return 0;
  }

  return (val1->v.d > val2->v.d) ? 1 : -1;
}

1536 1537
void doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock, uint16_t type,
                     uint64_t uid, SResultRowEntryInfo* pEntryInfo) {
1538 1539
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
  int32_t     maxSize = pCtx->param[1].param.i;
1540

1541 1542 1543
  SVariant val = {0};
  taosVariantCreateFromBinary(&val, pData, tDataTypes[type].bytes, type);

1544
  STopBotResItem* pItems = pRes->pItems;
1545 1546 1547
  assert(pItems != NULL);

  // not full yet
1548 1549
  if (pEntryInfo->numOfRes < maxSize) {
    STopBotResItem* pItem = &pItems[pEntryInfo->numOfRes];
1550
    pItem->v = val;
1551
    pItem->uid = uid;
1552

1553 1554
    // save the data of this tuple
    saveTupleData(pCtx, rowIndex, pSrcBlock, pItem);
1555 1556 1557

    // allocate the buffer and keep the data of this row into the new allocated buffer
    pEntryInfo->numOfRes++;
1558 1559 1560
    taosheapsort((void*)pItems, sizeof(STopBotResItem), pEntryInfo->numOfRes, (const void*)&type, topBotResComparFn,
                 false);
  } else {  // replace the minimum value in the result
1561
    if ((IS_SIGNED_NUMERIC_TYPE(type) && val.i > pItems[0].v.i) ||
1562
        (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u > pItems[0].v.u) || (IS_FLOAT_TYPE(type) && val.d > pItems[0].v.d)) {
1563
      // replace the old data and the coresponding tuple data
1564
      STopBotResItem* pItem = &pItems[0];
1565
      pItem->v = val;
1566
      pItem->uid = uid;
1567 1568 1569

      // save the data of this tuple by over writing the old data
      copyTupleData(pCtx, rowIndex, pSrcBlock, pItem);
1570

1571 1572
      taosheapadjust((void*)pItems, sizeof(STopBotResItem), 0, pEntryInfo->numOfRes - 1, (const void*)&type,
                     topBotResComparFn, NULL, false);
1573
    }
1574 1575
  }
}
1576

1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630
void saveTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STopBotResItem* pItem) {
  SFilePage* pPage = NULL;

  int32_t completeRowSize = pSrcBlock->info.rowSize + pSrcBlock->info.numOfCols * sizeof(bool);

  if (pCtx->curBufPage == -1) {
    pPage = getNewBufPage(pCtx->pBuf, 0, &pCtx->curBufPage);
    pPage->num = sizeof(SFilePage);
  } else {
    pPage = getBufPage(pCtx->pBuf, pCtx->curBufPage);
    if (pPage->num + completeRowSize > getBufPageSize(pCtx->pBuf)) {
      pPage = getNewBufPage(pCtx->pBuf, 0, &pCtx->curBufPage);
      pPage->num = sizeof(SFilePage);
    }
  }

  pItem->tuplePos.pageId = pCtx->curBufPage;

  // keep the current row data, extract method
  int32_t offset = 0;
  bool*   nullList = (bool*)((char*)pPage + pPage->num);
  char*   pStart = (char*)(nullList + sizeof(bool) * pSrcBlock->info.numOfCols);
  for (int32_t i = 0; i < pSrcBlock->info.numOfCols; ++i) {
    SColumnInfoData* pCol = taosArrayGet(pSrcBlock->pDataBlock, i);
    bool             isNull = colDataIsNull_s(pCol, rowIndex);
    if (isNull) {
      nullList[i] = true;
      continue;
    }

    char* p = colDataGetData(pCol, rowIndex);
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
      memcpy(pStart + offset, p, varDataTLen(p));
    } else {
      memcpy(pStart + offset, p, pCol->info.bytes);
    }

    offset += pCol->info.bytes;
  }

  pItem->tuplePos.offset = pPage->num;
  pPage->num += completeRowSize;

  setBufPageDirty(pPage, true);
  releaseBufPage(pCtx->pBuf, pPage);
}

void copyTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STopBotResItem* pItem) {
  SFilePage* pPage = getBufPage(pCtx->pBuf, pItem->tuplePos.pageId);

  bool* nullList = (bool*)((char*)pPage + pItem->tuplePos.offset);
  char* pStart = (char*)(nullList + pSrcBlock->info.numOfCols * sizeof(bool));

  int32_t offset = 0;
1631
  for (int32_t i = 0; i < pSrcBlock->info.numOfCols; ++i) {
1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
    SColumnInfoData* pCol = taosArrayGet(pSrcBlock->pDataBlock, i);
    if ((nullList[i] = colDataIsNull_s(pCol, rowIndex)) == true) {
      continue;
    }

    char* p = colDataGetData(pCol, rowIndex);
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
      memcpy(pStart + offset, p, varDataTLen(p));
    } else {
      memcpy(pStart + offset, p, pCol->info.bytes);
    }

    offset += pCol->info.bytes;
  }

  setBufPageDirty(pPage, true);
  releaseBufPage(pCtx->pBuf, pPage);
}

int32_t topBotFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1652 1653
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
  STopBotRes*          pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
1654 1655
  pEntryInfo->complete = true;

1656 1657
  int32_t          type = pCtx->input.pData[0]->info.type;
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
1658 1659 1660 1661
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  // todo assign the tag value and the corresponding row data
  int32_t currentRow = pBlock->info.rows;
1662
  switch (type) {
1663 1664 1665
    case TSDB_DATA_TYPE_INT: {
      for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) {
        STopBotResItem* pItem = &pRes->pItems[i];
1666
        colDataAppendInt32(pCol, currentRow, (int32_t*)&pItem->v.i);
1667 1668 1669

        int32_t pageId = pItem->tuplePos.pageId;
        int32_t offset = pItem->tuplePos.offset;
1670 1671
        if (pItem->tuplePos.pageId != -1) {
          SFilePage* pPage = getBufPage(pCtx->pBuf, pageId);
H
Haojun Liao 已提交
1672

1673 1674 1675 1676 1677 1678 1679
          bool* nullList = (bool*)((char*)pPage + offset);
          char* pStart = (char*)(nullList + pCtx->pSrcBlock->info.numOfCols * sizeof(bool));

          // todo set the offset value to optimize the performance.
          for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
            SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];

1680 1681 1682
            SFunctParam* pFuncParam = &pc->pExpr->base.pParam[0];
            int32_t      srcSlotId = pFuncParam->pCol->slotId;
            int32_t      dstSlotId = pCtx->pExpr->base.resSchema.slotId;
1683 1684

            int32_t ps = 0;
1685
            for (int32_t k = 0; k < srcSlotId; ++k) {
1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696
              SColumnInfoData* pSrcCol = taosArrayGet(pCtx->pSrcBlock->pDataBlock, k);
              ps += pSrcCol->info.bytes;
            }

            SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId);
            if (nullList[srcSlotId]) {
              colDataAppendNULL(pDstCol, currentRow);
            } else {
              colDataAppend(pDstCol, currentRow, (pStart + ps), false);
            }
          }
1697
        }
1698 1699

        currentRow += 1;
1700
      }
H
Haojun Liao 已提交
1701

1702 1703 1704 1705 1706
      break;
    }
  }

  return pEntryInfo->numOfRes;
1707
}
G
Ganlin Zhao 已提交
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805

bool getSpreadFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SSpreadInfo);
  return true;
}

bool spreadFunctionSetup(SqlFunctionCtx *pCtx, SResultRowEntryInfo* pResultInfo) {
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
  SET_DOUBLE_VAL(&pInfo->min, DBL_MAX);
  SET_DOUBLE_VAL(&pInfo->max, -DBL_MAX);
  pInfo->hasResult = false;
  return true;
}

int32_t spreadFunction(SqlFunctionCtx *pCtx) {
  int32_t numOfElems = 0;

  // Only the pre-computing information loaded and actual data does not loaded
  SInputColumnInfoData* pInput = &pCtx->input;
  SColumnDataAgg *pAgg = pInput->pColumnDataAgg[0];
  int32_t type = pInput->pData[0]->info.type;

  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

  if (pInput->colDataAggIsSet) {
    numOfElems = pInput->numOfRows - pAgg->numOfNull;
    if (numOfElems == 0) {
      goto _spread_over;
    }
    double tmin = 0.0, tmax = 0.0;
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
      tmin = (double)GET_INT64_VAL(&pAgg->min);
      tmax = (double)GET_INT64_VAL(&pAgg->max);
    } else if (IS_FLOAT_TYPE(type)) {
      tmin = GET_DOUBLE_VAL(&pAgg->min);
      tmax = GET_DOUBLE_VAL(&pAgg->max);
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
      tmin = (double)GET_UINT64_VAL(&pAgg->min);
      tmax = (double)GET_UINT64_VAL(&pAgg->max);
    }

    if (GET_DOUBLE_VAL(&pInfo->min) > tmin) {
      SET_DOUBLE_VAL(&pInfo->min, tmin);
    }

    if (GET_DOUBLE_VAL(&pInfo->max) < tmax) {
      SET_DOUBLE_VAL(&pInfo->max, tmax);
    }

  } else {  // computing based on the true data block
    SColumnInfoData* pCol = pInput->pData[0];

    int32_t start     = pInput->startRowIndex;
    int32_t numOfRows = pInput->numOfRows;

    // check the valid data one by one
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
        continue;
      }

      char *data = colDataGetData(pCol, i);

      double v = 0;
      GET_TYPED_DATA(v, double, type, data);
      if (v < GET_DOUBLE_VAL(&pInfo->min)) {
        SET_DOUBLE_VAL(&pInfo->min, v);
      }

      if (v > GET_DOUBLE_VAL(&pInfo->max)) {
        SET_DOUBLE_VAL(&pInfo->max, v);
      }

      numOfElems += 1;
    }
  }

_spread_over:
  // data in the check operation are all null, not output
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
  if (numOfElems > 0) {
    pInfo->hasResult = true;
  }

  return TSDB_CODE_SUCCESS;
}

int32_t spreadFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  if (pInfo->hasResult == true) {
    SET_DOUBLE_VAL(&pInfo->result, pInfo->max - pInfo->min);
  }
  return functionFinalize(pCtx, pBlock);
}
1806 1807 1808 1809 1810 1811

bool getHistogramFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SHistoFuncInfo) + HISTOGRAM_MAX_BINS_NUM * sizeof(SHistoFuncBin);
  return true;
}

1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
static int8_t getHistogramBinType(char *binTypeStr) {
  int8_t binType;
  if (strcasecmp(binTypeStr, "user_input") == 0) {
    binType = USER_INPUT_BIN;
  } else if (strcasecmp(binTypeStr, "linear_bin") == 0) {
    binType = LINEAR_BIN;
  } else if (strcasecmp(binTypeStr, "log_bin") == 0) {
    binType = LOG_BIN;
  } else {
    binType = UNKNOWN_BIN;
  }

  return binType;
}

static bool getHistogramBinDesc(SHistoFuncInfo *pInfo, char *binDescStr, int8_t binType, bool normalized) {
  cJSON*  binDesc = cJSON_Parse(binDescStr);
  int32_t numOfBins;
  double* intervals;
  if (cJSON_IsObject(binDesc)) { /* linaer/log bins */
    int32_t numOfParams = cJSON_GetArraySize(binDesc);
    int32_t startIndex;
    if (numOfParams != 4) {
      return false;
    }

    cJSON* start    = cJSON_GetObjectItem(binDesc, "start");
    cJSON* factor   = cJSON_GetObjectItem(binDesc, "factor");
    cJSON* width    = cJSON_GetObjectItem(binDesc, "width");
    cJSON* count    = cJSON_GetObjectItem(binDesc, "count");
    cJSON* infinity = cJSON_GetObjectItem(binDesc, "infinity");

    if (!cJSON_IsNumber(start) || !cJSON_IsNumber(count) || !cJSON_IsBool(infinity)) {
      return false;
    }

    if (count->valueint <= 0 || count->valueint > 1000) { // limit count to 1000
      return false;
    }

    if (isinf(start->valuedouble) || (width != NULL && isinf(width->valuedouble)) ||
        (factor != NULL && isinf(factor->valuedouble)) || (count != NULL && isinf(count->valuedouble))) {
      return false;
    }

1857
    int32_t counter = (int32_t)count->valueint;
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 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
    if (infinity->valueint == false) {
      startIndex = 0;
      numOfBins = counter + 1;
    } else {
      startIndex = 1;
      numOfBins = counter + 3;
    }

    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
    if (cJSON_IsNumber(width) && factor == NULL && binType == LINEAR_BIN) {
      // linear bin process
      if (width->valuedouble == 0) {
        taosMemoryFree(intervals);
        return false;
      }
      for (int i = 0; i < counter + 1; ++i) {
        intervals[startIndex] = start->valuedouble + i * width->valuedouble;
        if (isinf(intervals[startIndex])) {
          taosMemoryFree(intervals);
          return false;
        }
        startIndex++;
      }
    } else if (cJSON_IsNumber(factor) && width == NULL && binType == LOG_BIN) {
      // log bin process
      if (start->valuedouble == 0) {
        taosMemoryFree(intervals);
        return false;
      }
      if (factor->valuedouble < 0 || factor->valuedouble == 0 || factor->valuedouble == 1) {
        taosMemoryFree(intervals);
        return false;
      }
      for (int i = 0; i < counter + 1; ++i) {
        intervals[startIndex] = start->valuedouble * pow(factor->valuedouble, i * 1.0);
        if (isinf(intervals[startIndex])) {
          taosMemoryFree(intervals);
          return false;
        }
        startIndex++;
      }
    } else {
      taosMemoryFree(intervals);
      return false;
    }

    if (infinity->valueint == true) {
      intervals[0] = -INFINITY;
      intervals[numOfBins - 1] = INFINITY;
      // in case of desc bin orders, -inf/inf should be swapped
      ASSERT(numOfBins >= 4);
      if (intervals[1] > intervals[numOfBins - 2]) {
        TSWAP(intervals[0], intervals[numOfBins - 1]);
      }
    }
  } else if (cJSON_IsArray(binDesc)) { /* user input bins */
    if (binType != USER_INPUT_BIN) {
      return false;
    }
1917
    numOfBins = cJSON_GetArraySize(binDesc);
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
    cJSON* bin = binDesc->child;
    if (bin == NULL) {
      taosMemoryFree(intervals);
      return false;
    }
    int i = 0;
    while (bin) {
      intervals[i] = bin->valuedouble;
      if (!cJSON_IsNumber(bin)) {
        taosMemoryFree(intervals);
        return false;
      }
      if (i != 0 && intervals[i] <= intervals[i - 1]) {
        taosMemoryFree(intervals);
        return false;
      }
      bin = bin->next;
      i++;
    }
  } else {
    return false;
  }

1942
  pInfo->numOfBins  = numOfBins - 1;
1943
  pInfo->normalized = normalized;
1944
  for (int32_t i = 0; i < pInfo->numOfBins; ++i) {
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
    pInfo->bins[i].lower = intervals[i] < intervals[i + 1] ? intervals[i] : intervals[i + 1];
    pInfo->bins[i].upper = intervals[i + 1] > intervals[i] ? intervals[i + 1] : intervals[i];
    pInfo->bins[i].count = 0;
  }

  taosMemoryFree(intervals);
  return true;
}

bool histogramFunctionSetup(SqlFunctionCtx *pCtx, SResultRowEntryInfo *pResultInfo) {
1955 1956 1957 1958
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

1959
  SHistoFuncInfo *pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
1960

1961 1962 1963 1964 1965 1966
  int8_t binType = getHistogramBinType(varDataVal(pCtx->param[1].param.pz));
  if (binType == UNKNOWN_BIN) {
    return false;
  }
  char* binDesc = varDataVal(pCtx->param[2].param.pz);
  int64_t normalized = pCtx->param[3].param.i;
1967 1968 1969
  if (normalized != 0 && normalized != 1) {
    return false;
  }
1970 1971 1972
  if (!getHistogramBinDesc(pInfo, binDesc, binType, (bool)normalized)) {
    return false;
  }
1973 1974 1975 1976 1977

  return true;
}

int32_t histogramFunction(SqlFunctionCtx *pCtx) {
1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

  SInputColumnInfoData* pInput = &pCtx->input;
  SColumnInfoData*      pCol = pInput->pData[0];

  int32_t type = pInput->pData[0]->info.type;

  int32_t start = pInput->startRowIndex;
  int32_t numOfRows = pInput->numOfRows;

1988 1989
  int32_t numOfElems = 0;
  int32_t totalElems = 0;
1990 1991 1992 1993 1994
  for (int32_t i = start; i < numOfRows + start; ++i) {
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
      continue;
    }

1995 1996
    numOfElems++;

1997 1998 1999 2000 2001 2002 2003
    char* data = colDataGetData(pCol, i);
    double v;
    GET_TYPED_DATA(v, double, type, data);

    for (int32_t k = 0; k < pInfo->numOfBins; ++k) {
      if (v > pInfo->bins[k].lower && v <= pInfo->bins[k].upper) {
        pInfo->bins[k].count++;
2004
        totalElems++;
2005 2006 2007
        break;
      }
    }
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018

  }

  if (pInfo->normalized) {
    for (int32_t k = 0; k < pInfo->numOfBins; ++k) {
      if(totalElems != 0) {
        pInfo->bins[k].percentage = pInfo->bins[k].count / (double)totalElems;
      } else {
        pInfo->bins[k].percentage = 0;
      }
    }
2019 2020
  }

2021
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, pInfo->numOfBins);
2022 2023 2024 2025
  return TSDB_CODE_SUCCESS;
}

int32_t histogramFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
2026
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2027
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2028 2029 2030 2031 2032
  int32_t        slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  int32_t currentRow = pBlock->info.rows;

2033
  for (int32_t i = 0; i < pResInfo->numOfRes; ++i) {
2034
    int32_t len;
2035
    char buf[512] = {0};
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
    if (!pInfo->normalized) {
      len = sprintf(buf + VARSTR_HEADER_SIZE, "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%"PRId64"}",
                   pInfo->bins[i].lower, pInfo->bins[i].upper, pInfo->bins[i].count);
    } else {
      len = sprintf(buf + VARSTR_HEADER_SIZE, "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%lf}",
                   pInfo->bins[i].lower, pInfo->bins[i].upper, pInfo->bins[i].percentage);
    }
    varDataSetLen(buf, len);
    colDataAppend(pCol, currentRow, buf, false);
    currentRow++;
  }

2048
  return pResInfo->numOfRes;
2049
}