taosdemo.c 203.1 KB
Newer Older
S
TD-1057  
Shengliang Guan 已提交
1
/*
H
hzcheng 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15
 * 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/>.
 */

16 17 18 19 20

/*
   when in some thread query return error, thread don't exit, but return, otherwise coredump in other thread.
*/

S
slguan 已提交
21
#define _GNU_SOURCE
22 23
#define CURL_STATICLIB

S
TD-1057  
Shengliang Guan 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
#ifdef LINUX
  #include "os.h"
  #include <argp.h>
  #include <assert.h>
  #include <inttypes.h>
  #ifndef _ALPINE
    #include <error.h>
  #endif
  #include <pthread.h>
  #include <semaphore.h>
  #include <stdbool.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  #include <sys/time.h>
  #include <time.h>
  #include <unistd.h>
  #include <wordexp.h>
  #include <regex.h>
#else  
  #include <assert.h>
  #include <regex.h>
  #include <stdio.h>
  #include "os.h"
48
  
49
#ifdef WINDOWS
50 51 52
  #include <winsock2.h>
  typedef unsigned __int32 uint32_t;

53
  #pragma comment ( lib, "ws2_32.lib" )
54
#endif
S
TD-1057  
Shengliang Guan 已提交
55
#endif  
H
hzcheng 已提交
56

57 58
#include "cJSON.h"

H
hzcheng 已提交
59
#include "taos.h"
60
#include "taoserror.h"
H
Hui Li 已提交
61
#include "tutil.h"
S
slguan 已提交
62

63 64 65
#define REQ_EXTRA_BUF_LEN   1024
#define RESP_BUF_LEN        4096

S
slguan 已提交
66 67
extern char configDir[];

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
#define INSERT_JSON_NAME      "insert.json"
#define QUERY_JSON_NAME       "query.json"
#define SUBSCRIBE_JSON_NAME   "subscribe.json"

#define INSERT_MODE        0
#define QUERY_MODE         1
#define SUBSCRIBE_MODE     2

#define MAX_SQL_SIZE       65536
#define BUFFER_SIZE        (65536*2)
#define MAX_DB_NAME_SIZE   64
#define MAX_TB_NAME_SIZE   64
#define MAX_DATA_SIZE      16000
#define MAX_NUM_DATATYPE   10
#define OPT_ABORT          1 /* –abort */
#define STRING_LEN         60000
#define MAX_PREPARED_RAND  1000000
#define MAX_FILE_NAME_LEN  256

#define   MAX_SAMPLES_ONCE_FROM_FILE   10000
#define   MAX_NUM_DATATYPE 10

#define   MAX_DB_COUNT           8
#define   MAX_SUPER_TABLE_COUNT  8
#define   MAX_COLUMN_COUNT       1024
#define   MAX_TAG_COUNT          128

#define   MAX_QUERY_SQL_COUNT    10
#define   MAX_QUERY_SQL_LENGTH   256

#define   MAX_DATABASE_COUNT     256
99
#define INPUT_BUF_LEN   256
100

101 102
#define DEFAULT_TIMESTAMP_STEP  10

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
typedef enum CREATE_SUB_TALBE_MOD_EN {
  PRE_CREATE_SUBTBL,
  AUTO_CREATE_SUBTBL,
  NO_CREATE_SUBTBL
} CREATE_SUB_TALBE_MOD_EN;
  
typedef enum TALBE_EXISTS_EN {
  TBL_ALREADY_EXISTS,
  TBL_NO_EXISTS,
  TBL_EXISTS_BUTT
} TALBE_EXISTS_EN;

enum MODE {
  SYNC, 
  ASYNC,
  MODE_BUT
};
120

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
enum QUERY_TYPE {
  NO_INSERT_TYPE,
  INSERT_TYPE, 
  QUERY_TYPE_BUT
} ;  

enum _show_db_index {
  TSDB_SHOW_DB_NAME_INDEX,
  TSDB_SHOW_DB_CREATED_TIME_INDEX,
  TSDB_SHOW_DB_NTABLES_INDEX,
  TSDB_SHOW_DB_VGROUPS_INDEX,
  TSDB_SHOW_DB_REPLICA_INDEX,
  TSDB_SHOW_DB_QUORUM_INDEX,  
  TSDB_SHOW_DB_DAYS_INDEX,
  TSDB_SHOW_DB_KEEP_INDEX,
  TSDB_SHOW_DB_CACHE_INDEX,
  TSDB_SHOW_DB_BLOCKS_INDEX,
  TSDB_SHOW_DB_MINROWS_INDEX,
  TSDB_SHOW_DB_MAXROWS_INDEX,
  TSDB_SHOW_DB_WALLEVEL_INDEX,
  TSDB_SHOW_DB_FSYNC_INDEX,
  TSDB_SHOW_DB_COMP_INDEX,
  TSDB_SHOW_DB_CACHELAST_INDEX,
  TSDB_SHOW_DB_PRECISION_INDEX,  
  TSDB_SHOW_DB_UPDATE_INDEX,
  TSDB_SHOW_DB_STATUS_INDEX,
  TSDB_MAX_SHOW_DB
};

// -----------------------------------------SHOW TABLES CONFIGURE -------------------------------------
enum _show_stables_index {
  TSDB_SHOW_STABLES_NAME_INDEX,
  TSDB_SHOW_STABLES_CREATED_TIME_INDEX,
  TSDB_SHOW_STABLES_COLUMNS_INDEX,
  TSDB_SHOW_STABLES_METRIC_INDEX,  
  TSDB_SHOW_STABLES_UID_INDEX,  
  TSDB_SHOW_STABLES_TID_INDEX,
  TSDB_SHOW_STABLES_VGID_INDEX,  
  TSDB_MAX_SHOW_STABLES
};  
enum _describe_table_index {
  TSDB_DESCRIBE_METRIC_FIELD_INDEX,
  TSDB_DESCRIBE_METRIC_TYPE_INDEX,
  TSDB_DESCRIBE_METRIC_LENGTH_INDEX,
  TSDB_DESCRIBE_METRIC_NOTE_INDEX,
  TSDB_MAX_DESCRIBE_METRIC
};

typedef struct {
  char field[TSDB_COL_NAME_LEN + 1];
  char type[16];
  int length;
  char note[128];
} SColDes;
H
hzcheng 已提交
175 176

/* Used by main to communicate with parse_opt. */
177 178
typedef struct SArguments_S {
  char *   metaFile;
179
  int      test_mode;
180 181 182 183 184 185 186 187 188 189
  char *   host;
  uint16_t port;
  char *   user;
  char *   password;
  char *   database;
  int      replica;
  char *   tb_prefix;
  char *   sqlFile;
  bool     use_metric;
  bool     insert_only;
190
  bool     answer_yes;
191
  bool     debug_print;
192
  bool     verbose_print;
193 194 195 196 197 198
  char *   output_file;
  int      mode;
  char *   datatype[MAX_NUM_DATATYPE + 1];
  int      len_of_binary;
  int      num_of_CPR;
  int      num_of_threads;
199
  int      insert_interval;
200
  int      num_of_RPR;
201
  int      max_sql_len;
202 203 204
  int      num_of_tables;
  int      num_of_DPT;
  int      abort;
205 206
  int      disorderRatio;
  int      disorderRange;
207 208
  int      method_of_delete;
  char **  arg_list;
209 210 211 212 213 214 215 216 217 218
} SArguments;

typedef struct SColumn_S {
  char  field[TSDB_COL_NAME_LEN + 1];
  char  dataType[MAX_TB_NAME_SIZE];
  int   dataLen;
  char  note[128];  
} StrColumn;

typedef struct SSuperTable_S {
219
  char         sTblName[MAX_TB_NAME_SIZE+1];
220 221 222 223 224 225
  int          childTblCount;
  bool         superTblExists;    // 0: no, 1: yes
  bool         childTblExists;    // 0: no, 1: yes  
  int          batchCreateTableNum;  // 0: no batch,  > 0: batch table number in one sql
  int8_t       autoCreateTable;                  // 0: create sub table, 1: auto create sub table
  char         childTblPrefix[MAX_TB_NAME_SIZE];
226
  char         dataSource[MAX_TB_NAME_SIZE+1];  // rand_gen or sample
227
  char         insertMode[MAX_TB_NAME_SIZE];  // taosc, restful
228 229
  int           childTblLimit;
  int           childTblOffset;
230 231 232 233 234 235 236

  int          multiThreadWriteOneTbl;   // 0: no, 1: yes
  int          numberOfTblInOneSql;      // 0/1: one table, > 1: number of tbl
  int          rowsPerTbl;               // 
  int          disorderRatio;            // 0: no disorder, >0: x%
  int          disorderRange;            // ms or us by database precision
  int          maxSqlLen;                // 
237 238

  int          insertInterval;          // insert interval, will override global insert interval
239 240 241 242
  int64_t      insertRows;               // 0: no limit
  int          timeStampStep;
  char         startTimestamp[MAX_TB_NAME_SIZE];  // 
  char         sampleFormat[MAX_TB_NAME_SIZE];  // csv, json
243 244
  char         sampleFile[MAX_FILE_NAME_LEN+1];
  char         tagsFile[MAX_FILE_NAME_LEN+1];
245 246 247 248 249 250 251

  int          columnCount;
  StrColumn    columns[MAX_COLUMN_COUNT];
  int          tagCount;
  StrColumn    tags[MAX_TAG_COUNT];

  char*        childTblName;
252
  char*        colsOfCreateChildTable;
253 254 255 256 257 258 259 260 261 262 263 264 265 266
  int          lenOfOneRow;
  int          lenOfTagOfOneRow;

  char*        sampleDataBuf;
  int          sampleDataBufSize;
  //int          sampleRowCount;
  //int          sampleUsePos;

  int          tagSource;    // 0: rand, 1: tag sample
  char*        tagDataBuf;
  int          tagSampleCount;
  int          tagUsePos;

  // statistics  
267
  int64_t    totalInsertRows;
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
  int64_t    totalAffectedRows;
} SSuperTable;

typedef struct {
  char     name[TSDB_DB_NAME_LEN + 1];
  char     create_time[32];
  int32_t  ntables;
  int32_t  vgroups;  
  int16_t  replica;
  int16_t  quorum;
  int16_t  days;  
  char     keeplist[32];
  int32_t  cache; //MB
  int32_t  blocks;
  int32_t  minrows;
  int32_t  maxrows;
  int8_t   wallevel;
  int32_t  fsync;
  int8_t   comp;
  int8_t   cachelast;
  char     precision[8];   // time resolution
  int8_t   update;
  char     status[16];
} SDbInfo;

typedef struct SDbCfg_S { 
//  int       maxtablesPerVnode;
  int       minRows; 
  int       maxRows;
  int       comp;
  int       walLevel;
299
  int       cacheLast;
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
  int       fsync;  
  int       replica;
  int       update;
  int       keep;
  int       days;
  int       cache;
  int       blocks;
  int       quorum;
  char      precision[MAX_TB_NAME_SIZE];  
} SDbCfg;

typedef struct SDataBase_S {
  char         dbName[MAX_DB_NAME_SIZE];
  int          drop;  // 0: use exists, 1: if exists, drop then new create
  SDbCfg       dbCfg;
  int          superTblCount;
  SSuperTable  superTbls[MAX_SUPER_TABLE_COUNT];
} SDataBase;

typedef struct SDbs_S {
320
  char         cfgDir[MAX_FILE_NAME_LEN+1];
321 322 323 324
  char         host[MAX_DB_NAME_SIZE];
  uint16_t     port;
  char         user[MAX_DB_NAME_SIZE];
  char         password[MAX_DB_NAME_SIZE];
325
  char         resultFile[MAX_FILE_NAME_LEN+1];
326 327 328 329 330 331 332 333 334 335 336
  bool         use_metric;
  bool         insert_only;
  bool         do_aggreFunc;
  bool         queryMode;
  
  int          threadCount;
  int          threadCountByCreateTbl;
  int          dbCount;
  SDataBase    db[MAX_DB_COUNT];

  // statistics
337
  int64_t    totalInsertRows;
338
  int64_t    totalAffectedRows;
339

340 341 342 343 344 345 346 347 348 349
} SDbs;

typedef struct SuperQueryInfo_S {
  int          rate;  // 0: unlimit  > 0   loop/s
  int          concurrent;
  int          sqlCount;
  int          subscribeMode; // 0: sync, 1: async
  int          subscribeInterval; // ms
  int          subscribeRestart;
  int          subscribeKeepProgress;
350 351
  char         sql[MAX_QUERY_SQL_COUNT][MAX_QUERY_SQL_LENGTH+1];  
  char         result[MAX_QUERY_SQL_COUNT][MAX_FILE_NAME_LEN+1];
352 353 354 355
  TAOS_SUB*    tsub[MAX_QUERY_SQL_COUNT];
} SuperQueryInfo;

typedef struct SubQueryInfo_S {
356
  char         sTblName[MAX_TB_NAME_SIZE+1];
357 358 359 360 361 362 363 364 365
  int          rate;  // 0: unlimit  > 0   loop/s
  int          threadCnt;  
  int          subscribeMode; // 0: sync, 1: async
  int          subscribeInterval; // ms
  int          subscribeRestart;
  int          subscribeKeepProgress;
  int          childTblCount;
  char         childTblPrefix[MAX_TB_NAME_SIZE];
  int          sqlCount;
366 367
  char         sql[MAX_QUERY_SQL_COUNT][MAX_QUERY_SQL_LENGTH+1];  
  char         result[MAX_QUERY_SQL_COUNT][MAX_FILE_NAME_LEN+1];
368 369 370 371 372 373
  TAOS_SUB*    tsub[MAX_QUERY_SQL_COUNT];
  
  char*        childTblName;
} SubQueryInfo;

typedef struct SQueryMetaInfo_S {
374
  char         cfgDir[MAX_FILE_NAME_LEN+1];
375 376 377 378
  char         host[MAX_DB_NAME_SIZE];
  uint16_t     port;
  char         user[MAX_DB_NAME_SIZE];
  char         password[MAX_DB_NAME_SIZE];
379
  char         dbName[MAX_DB_NAME_SIZE+1];
380 381 382 383 384 385 386 387 388
  char         queryMode[MAX_TB_NAME_SIZE];  // taosc, restful

  SuperQueryInfo  superQueryInfo;
  SubQueryInfo    subQueryInfo;  
} SQueryMetaInfo;

typedef struct SThreadInfo_S {
  TAOS *taos;
  int threadID;
389
  char db_name[MAX_DB_NAME_SIZE+1];
390 391 392 393 394
  char fp[4096];
  char tb_prefix[MAX_TB_NAME_SIZE];
  int start_table_id;
  int end_table_id;
  int data_of_rate;
395
  uint64_t start_time;  
396 397 398 399 400 401 402
  char* cols;  
  bool  use_metric;  
  SSuperTable* superTblInfo;

  // for async insert
  tsem_t lock_sem;
  int64_t  counter;  
403 404
  uint64_t  st;
  uint64_t  et;
405 406 407
  int64_t  lastTs;

  // statistics
408
  int64_t totalInsertRows;
409
  int64_t totalAffectedRows;
410 411 412 413 414 415 416 417

  // insert delay statistics
  int64_t cntDelay;
  int64_t totalDelay;
  int64_t avgDelay;
  int64_t maxDelay;
  int64_t minDelay;
  
418 419
} threadInfo;

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 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
#ifdef WINDOWS
#include <windows.h>
// Some old MinGW/CYGWIN distributions don't define this:
#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
#define ENABLE_VIRTUAL_TERMINAL_PROCESSING  0x0004
#endif

static HANDLE g_stdoutHandle;
static DWORD g_consoleMode;

void setupForAnsiEscape(void) {
  DWORD mode = 0;
  g_stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE);

  if(g_stdoutHandle == INVALID_HANDLE_VALUE) {
    exit(GetLastError());
  }

  if(!GetConsoleMode(g_stdoutHandle, &mode)) {
    exit(GetLastError());
  }

  g_consoleMode = mode;

  // Enable ANSI escape codes
  mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;

  if(!SetConsoleMode(g_stdoutHandle, mode)) {
    exit(GetLastError());
  }    
}

void resetAfterAnsiEscape(void) {
  // Reset colors
  printf("\x1b[0m");    

  // Reset console mode
  if(!SetConsoleMode(g_stdoutHandle, g_consoleMode)) {
    exit(GetLastError());
  }
}
#else
void setupForAnsiEscape(void) {}

void resetAfterAnsiEscape(void) {
  // Reset colors
  printf("\x1b[0m");
}
#endif

470 471 472
static int createDatabases();
static void createChildTables();
static int queryDbExec(TAOS *taos, char *command, int type);
473 474 475 476 477 478 479 480 481 482

/* ************ Global variables ************  */

int32_t  randint[MAX_PREPARED_RAND];
int64_t  randbigint[MAX_PREPARED_RAND];
float    randfloat[MAX_PREPARED_RAND];
double   randdouble[MAX_PREPARED_RAND];
char *aggreFunc[] = {"*", "count(*)", "avg(col0)", "sum(col0)", 
    "max(col0)", "min(col0)", "first(col0)", "last(col0)"};

483
SArguments g_args = {
484 485
                     NULL,            // metaFile
                     0,               // test_mode
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
                     "127.0.0.1",     // host
                     6030,            // port
                     "root",          // user
                     #ifdef _TD_POWER_ 
                     "powerdb",      // password
                     #else
                     "taosdata",      // password
                     #endif
                     "test",          // database
                     1,               // replica
                     "t",             // tb_prefix
                     NULL,            // sqlFile
                     false,           // use_metric
                     false,           // insert_only
                     false,           // debug_print
501
                     false,           // verbose_print
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
                     false,           // answer_yes;
                     "./output.txt",  // output_file
                     0,               // mode : sync or async
                     {
                     "TINYINT",           // datatype
                     "SMALLINT",
                     "INT",
                     "BIGINT",
                     "FLOAT",
                     "DOUBLE",
                     "BINARY",
                     "NCHAR",
                     "BOOL",
                     "TIMESTAMP"
                     },
                     16,              // len_of_binary
                     10,              // num_of_CPR
                     10,              // num_of_connections/thread
                     0,               // insert_interval
                     100,             // num_of_RPR
522
                     TSDB_PAYLOAD_SIZE,  // max_sql_len
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
                     10000,           // num_of_tables
                     10000,           // num_of_DPT
                     0,               // abort
                     0,               // disorderRatio
                     1000,            // disorderRange
                     1,               // method_of_delete
                     NULL             // arg_list
};



static SDbs            g_Dbs;
static int             g_totalChildTables = 0;
static SQueryMetaInfo  g_queryInfo;
static FILE *          g_fpOfInsertResult = NULL;

#define debugPrint(fmt, ...) \
540
    do { if (g_args.debug_print || g_args.verbose_print) \
541
      fprintf(stderr, "DEBG: "fmt, __VA_ARGS__); } while(0)
542
#define verbosePrint(fmt, ...) \
543 544
    do { if (g_args.verbose_print) fprintf(stderr, "VERB: "fmt, __VA_ARGS__); } while(0)

545
///////////////////////////////////////////////////
H
hzcheng 已提交
546

547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
void printHelp() {
  char indent[10] = "        ";
  printf("%s%s%s%s\n", indent, "-f", indent, 
          "The meta file to the execution procedure. Default is './meta.json'.");
  printf("%s%s%s%s\n", indent, "-u", indent, 
          "The TDengine user name to use when connecting to the server. Default is 'root'.");
#ifdef _TD_POWER_
  printf("%s%s%s%s\n", indent, "-P", indent, 
          "The password to use when connecting to the server. Default is 'powerdb'.");
  printf("%s%s%s%s\n", indent, "-c", indent, 
          "Configuration directory. Default is '/etc/power/'.");
#else
  printf("%s%s%s%s\n", indent, "-P", indent, 
          "The password to use when connecting to the server. Default is 'taosdata'.");
  printf("%s%s%s%s\n", indent, "-c", indent, 
          "Configuration directory. Default is '/etc/taos/'.");
#endif  
  printf("%s%s%s%s\n", indent, "-h", indent, 
          "The host to connect to TDengine. Default is localhost.");
  printf("%s%s%s%s\n", indent, "-p", indent, 
          "The TCP/IP port number to use for the connection. Default is 0.");
  printf("%s%s%s%s\n", indent, "-d", indent, 
          "Destination database. Default is 'test'.");
  printf("%s%s%s%s\n", indent, "-a", indent, 
          "Set the replica parameters of the database, Default 1, min: 1, max: 3.");
  printf("%s%s%s%s\n", indent, "-m", indent, 
          "Table prefix name. Default is 't'.");
  printf("%s%s%s%s\n", indent, "-s", indent, "The select sql file.");
  printf("%s%s%s%s\n", indent, "-M", indent, "Use metric flag.");
  printf("%s%s%s%s\n", indent, "-o", indent, 
          "Direct output to the named file. Default is './output.txt'.");
  printf("%s%s%s%s\n", indent, "-q", indent, 
          "Query mode--0: SYNC, 1: ASYNC. Default is SYNC.");
  printf("%s%s%s%s\n", indent, "-b", indent, 
          "The data_type of columns, default: TINYINT,SMALLINT,INT,BIGINT,FLOAT,DOUBLE,BINARY,NCHAR,BOOL,TIMESTAMP.");
  printf("%s%s%s%s\n", indent, "-w", indent, 
          "The length of data_type 'BINARY' or 'NCHAR'. Default is 16");
  printf("%s%s%s%s\n", indent, "-l", indent, 
          "The number of columns per record. Default is 10.");
  printf("%s%s%s%s\n", indent, "-T", indent, 
          "The number of threads. Default is 10.");
  printf("%s%s%s%s\n", indent, "-i", indent, 
          "The sleep time (ms) between insertion. Default is 0.");
  printf("%s%s%s%s\n", indent, "-r", indent, 
          "The number of records per request. Default is 100.");
  printf("%s%s%s%s\n", indent, "-t", indent, 
          "The number of tables. Default is 10000.");
  printf("%s%s%s%s\n", indent, "-n", indent, 
          "The number of records per table. Default is 10000.");
  printf("%s%s%s%s\n", indent, "-x", indent, "Not insert only flag.");
  printf("%s%s%s%s\n", indent, "-y", indent, "Default input yes for prompt.");
  printf("%s%s%s%s\n", indent, "-O", indent, 
          "Insert mode--0: In order, > 0: disorder ratio. Default is in order.");
  printf("%s%s%s%s\n", indent, "-R", indent, 
          "Out of order data's range, ms, default is 1000.");
602 603
  printf("%s%s%s%s\n", indent, "-g", indent, 
          "Print debug info.");
604 605 606 607 608 609
/*    printf("%s%s%s%s\n", indent, "-D", indent, 
          "if elete database if exists. 0: no, 1: yes, default is 1");
          */
}

void parse_args(int argc, char *argv[], SArguments *arguments) {
610
  char **sptr;
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
  wordexp_t full_path;

  for (int i = 1; i < argc; i++) {
    if (strcmp(argv[i], "-f") == 0) {
      arguments->metaFile = argv[++i];
    } else if (strcmp(argv[i], "-c") == 0) {
        char *configPath = argv[++i];
      if (wordexp(configPath, &full_path, 0) != 0) {
          fprintf(stderr, "Invalid path %s\n", configPath);
          return;
      }
      taos_options(TSDB_OPTION_CONFIGDIR, full_path.we_wordv[0]);
      wordfree(&full_path);
    } else if (strcmp(argv[i], "-h") == 0) {
      arguments->host = argv[++i];
    } else if (strcmp(argv[i], "-p") == 0) {
      arguments->port = atoi(argv[++i]);
    } else if (strcmp(argv[i], "-u") == 0) {
      arguments->user = argv[++i];
    } else if (strcmp(argv[i], "-P") == 0) {
      arguments->password = argv[++i];
    } else if (strcmp(argv[i], "-o") == 0) {
      arguments->output_file = argv[++i];
    } else if (strcmp(argv[i], "-s") == 0) {
      arguments->sqlFile = argv[++i];
    } else if (strcmp(argv[i], "-q") == 0) {
      arguments->mode = atoi(argv[++i]);
    } else if (strcmp(argv[i], "-T") == 0) {
      arguments->num_of_threads = atoi(argv[++i]);
    } else if (strcmp(argv[i], "-i") == 0) {
      arguments->insert_interval = atoi(argv[++i]);
    } else if (strcmp(argv[i], "-r") == 0) {
      arguments->num_of_RPR = atoi(argv[++i]);
    } else if (strcmp(argv[i], "-t") == 0) {
      arguments->num_of_tables = atoi(argv[++i]);
    } else if (strcmp(argv[i], "-n") == 0) {
      arguments->num_of_DPT = atoi(argv[++i]);
    } else if (strcmp(argv[i], "-d") == 0) {
      arguments->database = argv[++i];
    } else if (strcmp(argv[i], "-l") == 0) {
      arguments->num_of_CPR = atoi(argv[++i]);
    } else if (strcmp(argv[i], "-b") == 0) {
653
      sptr = arguments->datatype;
654 655
      ++i;
      if (strstr(argv[i], ",") == NULL) {
656
        // only one col
657 658 659 660 661 662 663 664 665 666 667 668
        if (strcasecmp(argv[i], "INT")
                && strcasecmp(argv[i], "FLOAT")
                && strcasecmp(argv[i], "TINYINT")
                && strcasecmp(argv[i], "BOOL")
                && strcasecmp(argv[i], "SMALLINT")
                && strcasecmp(argv[i], "BIGINT")
                && strcasecmp(argv[i], "DOUBLE")
                && strcasecmp(argv[i], "BINARY") 
                && strcasecmp(argv[i], "NCHAR")) {
          fprintf(stderr, "Invalid data_type!\n");
          printHelp();
          exit(EXIT_FAILURE);
669
        }
670
        sptr[0] = argv[i];
671
      } else {
672
        // more than one col
673
        int index = 0;
674
        char *dupstr = strdup(argv[i]);
675 676 677
        char *running = dupstr;
        char *token = strsep(&running, ",");
        while (token != NULL) {
678 679 680 681 682 683 684 685 686 687 688 689
          if (strcasecmp(token, "INT")
                  && strcasecmp(token, "FLOAT")
                  && strcasecmp(token, "TINYINT")
                  && strcasecmp(token, "BOOL")
                  && strcasecmp(token, "SMALLINT")
                  && strcasecmp(token, "BIGINT")
                  && strcasecmp(token, "DOUBLE")
                  && strcasecmp(token, "BINARY")
                  && strcasecmp(token, "NCHAR")) {
            fprintf(stderr, "Invalid data_type!\n");
            printHelp();
            exit(EXIT_FAILURE);
H
hzcheng 已提交
690
          }
691 692 693
          sptr[index++] = token;
          token = strsep(&running, ",");
          if (index >= MAX_NUM_DATATYPE) break;
S
TD-1057  
Shengliang Guan 已提交
694
        }
695
        sptr[index] = NULL;
696
      }
697 698 699 700 701
    } else if (strcmp(argv[i], "-w") == 0) {
      arguments->len_of_binary = atoi(argv[++i]);
    } else if (strcmp(argv[i], "-m") == 0) {
      arguments->tb_prefix = argv[++i];
    } else if (strcmp(argv[i], "-M") == 0) {
702
      arguments->use_metric = true;
703
    } else if (strcmp(argv[i], "-x") == 0) {
704
      arguments->insert_only = true;
705
    } else if (strcmp(argv[i], "-y") == 0) {
706
      arguments->answer_yes = true;
707 708
    } else if (strcmp(argv[i], "-g") == 0) {
      arguments->debug_print = true;
709 710
    } else if (strcmp(argv[i], "-gg") == 0) {
      arguments->verbose_print = true;
711 712 713 714 715 716 717 718 719
    } else if (strcmp(argv[i], "-c") == 0) {
      strcpy(configDir, argv[++i]);
    } else if (strcmp(argv[i], "-O") == 0) {
      arguments->disorderRatio = atoi(argv[++i]);
      if (arguments->disorderRatio > 1 
              || arguments->disorderRatio < 0) {
        arguments->disorderRatio = 0;
      } else if (arguments->disorderRatio == 1) {
        arguments->disorderRange = 10;
720
      }
721 722 723 724 725 726
    } else if (strcmp(argv[i], "-R") == 0) {
      arguments->disorderRange = atoi(argv[++i]);
      if (arguments->disorderRange == 1 
              && (arguments->disorderRange > 50 
              || arguments->disorderRange <= 0)) {
        arguments->disorderRange = 10;
727
      }
728 729 730 731
    } else if (strcmp(argv[i], "-a") == 0) {
      arguments->replica = atoi(argv[++i]);
      if (arguments->replica > 3 || arguments->replica < 1) {
          arguments->replica = 1;
732
      }
733 734 735 736 737
    } else if (strcmp(argv[i], "-D") == 0) {
      arguments->method_of_delete = atoi(argv[++i]);
      if (arguments->method_of_delete < 0
              || arguments->method_of_delete > 3) {
        arguments->method_of_delete = 0;
S
TD-1057  
Shengliang Guan 已提交
738
      }
739 740 741 742 743 744 745
    } else if (strcmp(argv[i], "--help") == 0) {
      printHelp();
      exit(0);
    } else {
      fprintf(stderr, "wrong options\n");
      printHelp();
      exit(EXIT_FAILURE);
S
TD-1057  
Shengliang Guan 已提交
746 747
    }
  }
748

749 750
  if (((arguments->debug_print) && (arguments->metaFile == NULL))
          || arguments->verbose_print) {
751
    printf("###################################################################\n");
752
    printf("# meta file:                         %s\n", arguments->metaFile);
753 754 755 756 757 758
    printf("# Server IP:                         %s:%hu\n", 
            arguments->host == NULL ? "localhost" : arguments->host,
            arguments->port );
    printf("# User:                              %s\n", arguments->user);
    printf("# Password:                          %s\n", arguments->password);
    printf("# Use metric:                        %s\n", arguments->use_metric ? "true" : "false");
759 760 761 762 763 764 765 766 767
    if (*(arguments->datatype)) {
        printf("# Specified data type:               ");
        for (int i = 0; i < MAX_NUM_DATATYPE; i++)
            if (arguments->datatype[i])
               printf("%s,", arguments->datatype[i]);
            else
                break;
        printf("\n");
    }
768
    printf("# Insertion interval:                %d\n", arguments->insert_interval);
769
    printf("# Number of records per req:         %d\n", arguments->num_of_RPR);
770
    printf("# Max SQL length:                    %d\n", arguments->max_sql_len);
771
    printf("# Length of Binary:                  %d\n", arguments->len_of_binary);
772 773 774 775 776 777 778 779 780 781 782 783 784
    printf("# Number of Threads:                 %d\n", arguments->num_of_threads);
    printf("# Number of Tables:                  %d\n", arguments->num_of_tables);
    printf("# Number of Data per Table:          %d\n", arguments->num_of_DPT);
    printf("# Database name:                     %s\n", arguments->database);
    printf("# Table prefix:                      %s\n", arguments->tb_prefix);
    if (arguments->disorderRatio) {
      printf("# Data order:                        %d\n", arguments->disorderRatio);
      printf("# Data out of order rate:            %d\n", arguments->disorderRange);
  
    }
    printf("# Delete method:                     %d\n", arguments->method_of_delete);
    printf("# Answer yes when prompt:            %d\n", arguments->answer_yes);
    printf("# Print debug info:                  %d\n", arguments->debug_print);
785
    printf("# Print verbose info:                %d\n", arguments->verbose_print);
786 787 788 789 790 791
    printf("###################################################################\n");
    if (!arguments->answer_yes) {
        printf("Press enter key to continue\n\n");
        (void) getchar();
    }
  }
792
}
H
hzcheng 已提交
793

794 795 796 797 798 799 800 801 802
static bool getInfoFromJsonFile(char* file);
//static int generateOneRowDataForStb(SSuperTable* stbInfo);
//static int getDataIntoMemForStb(SSuperTable* stbInfo);
static void init_rand_data();
void tmfclose(FILE *fp) {
  if (NULL != fp) {
    fclose(fp);
  }
}
803

804 805 806
void tmfree(char *buf) {
  if (NULL != buf) {
    free(buf);
H
Hui Li 已提交
807
  }
808
}
H
Hui Li 已提交
809

810
static int queryDbExec(TAOS *taos, char *command, int type) {
811 812 813
  int i;
  TAOS_RES *res = NULL;
  int32_t   code = -1;
814

815 816 817 818
  for (i = 0; i < 5; i++) {
    if (NULL != res) {
      taos_free_result(res);
      res = NULL;
H
hzcheng 已提交
819
    }
820

821 822 823 824 825
    res = taos_query(taos, command);
    code = taos_errno(res);
    if (0 == code) {
      break;
    }    
H
hzcheng 已提交
826 827
  }

828
  if (code != 0) {
829
    debugPrint("%s() LN%d - command: %s\n", __func__, __LINE__, command);
830 831 832 833
    fprintf(stderr, "Failed to run %s, reason: %s\n", command, taos_errstr(res));
    taos_free_result(res);
    //taos_close(taos);
    return -1;
834
  }
H
hzcheng 已提交
835

836 837 838 839
  if (INSERT_TYPE == type) {
    int affectedRows = taos_affected_rows(res);
    taos_free_result(res);
    return affectedRows;
H
hzcheng 已提交
840
  }
841
  
842
  taos_free_result(res);
843 844
  return 0;
}
H
hzcheng 已提交
845

846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
static void getResult(TAOS_RES *res, char* resultFileName) {  
  TAOS_ROW    row = NULL;
  int         num_rows = 0;
  int         num_fields = taos_field_count(res);
  TAOS_FIELD *fields     = taos_fetch_fields(res);

  FILE *fp = NULL;
  if (resultFileName[0] != 0) {
    fp = fopen(resultFileName, "at");
    if (fp == NULL) {
      fprintf(stderr, "failed to open result file: %s, result will not save to file\n", resultFileName);
    }
  }
  
  char* databuf = (char*) calloc(1, 100*1024*1024);
  if (databuf == NULL) {
    fprintf(stderr, "failed to malloc, warning: save result to file slowly!\n");
863 864
    if (fp)
        fclose(fp);
865 866
    return ;
  }
H
hzcheng 已提交
867

868 869
  int   totalLen = 0;
  char  temp[16000];
H
hzcheng 已提交
870

871 872 873 874 875 876
  // fetch the records row by row
  while ((row = taos_fetch_row(res))) {
    if (totalLen >= 100*1024*1024 - 32000) {
      if (fp) fprintf(fp, "%s", databuf);
      totalLen = 0;
      memset(databuf, 0, 100*1024*1024);
H
hzcheng 已提交
877
    }
878 879 880 881 882 883
    num_rows++;
    int len = taos_print_row(temp, row, fields, num_fields);
    len += sprintf(temp + len, "\n");
    //printf("query result:%s\n", temp);
    memcpy(databuf + totalLen, temp, len);
    totalLen += len;
H
hzcheng 已提交
884 885
  }

886 887 888 889
  if (fp) fprintf(fp, "%s", databuf);
  tmfclose(fp);
  free(databuf);
}
H
hzcheng 已提交
890

891 892 893 894 895 896
static void selectAndGetResult(TAOS *taos, char *command, char* resultFileName) {
  TAOS_RES *res = taos_query(taos, command);
  if (res == NULL || taos_errno(res) != 0) {
    printf("failed to sql:%s, reason:%s\n", command, taos_errstr(res));
    taos_free_result(res);
    return;
H
hzcheng 已提交
897
  }
H
Hui Li 已提交
898
  
899 900 901
  getResult(res, resultFileName);
  taos_free_result(res);
}
H
hzcheng 已提交
902

903 904 905 906 907
double getCurrentTime() {
  struct timeval tv;
  if (gettimeofday(&tv, NULL) != 0) {
    perror("Failed to get current time in ms");
    return 0.0;
H
hzcheng 已提交
908
  }
S
Shuduo Sang 已提交
909

910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
  return tv.tv_sec + tv.tv_usec / 1E6;
}

static int32_t rand_bool(){
  static int cursor;
  cursor++;
  cursor = cursor % MAX_PREPARED_RAND;
  return randint[cursor] % 2;
}

static int32_t rand_tinyint(){
  static int cursor;
  cursor++;
  cursor = cursor % MAX_PREPARED_RAND;
  return randint[cursor] % 128;
}

static int32_t rand_smallint(){
  static int cursor;
  cursor++;
  cursor = cursor % MAX_PREPARED_RAND;
  return randint[cursor] % 32767;
}

static int32_t rand_int(){
  static int cursor;
  cursor++;
  cursor = cursor % MAX_PREPARED_RAND;
  return randint[cursor];
}

static int64_t rand_bigint(){
  static int cursor;
  cursor++;
  cursor = cursor % MAX_PREPARED_RAND;
  return randbigint[cursor];
  
}

static float rand_float(){
  static int cursor;
  cursor++;
  cursor = cursor % MAX_PREPARED_RAND;
  return randfloat[cursor];    
}

static const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
void rand_string(char *str, int size) {
  str[0] = 0;
  if (size > 0) {
    //--size;
    int n;
    for (n = 0; n < size; n++) {
      int key = rand_tinyint() % (int)(sizeof(charset) - 1);
      str[n] = charset[key];
    }
    str[n] = 0;
  }
}

static double rand_double() {
  static int cursor;
  cursor++;
  cursor = cursor % MAX_PREPARED_RAND;
  return randdouble[cursor];

}

static void init_rand_data() {
  for (int i = 0; i < MAX_PREPARED_RAND; i++){
    randint[i] = (int)(rand() % 65535);
    randbigint[i] = (int64_t)(rand() % 2147483648);
    randfloat[i] = (float)(rand() / 1000.0);
    randdouble[i] = (double)(rand() / 1000000.0);
  }
}

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
#define SHOW_PARSE_RESULT_START()   \
    do { if (g_args.metaFile)  \
        printf("\033[1m\033[40;32m================ %s parse result START ================\033[0m\n", \
                g_args.metaFile); } while(0)

#define SHOW_PARSE_RESULT_END() \
    do { if (g_args.metaFile)   \
        printf("\033[1m\033[40;32m================ %s parse result END================\033[0m\n", \
                g_args.metaFile); } while(0)

#define SHOW_PARSE_RESULT_START_TO_FILE(fp)   \
    do { if (g_args.metaFile)  \
        fprintf(fp, "\033[1m\033[40;32m================ %s parse result START ================\033[0m\n", \
                g_args.metaFile); } while(0)

#define SHOW_PARSE_RESULT_END_TO_FILE(fp) \
    do { if (g_args.metaFile)   \
        fprintf(fp, "\033[1m\033[40;32m================ %s parse result END================\033[0m\n", \
                g_args.metaFile); } while(0)

1007
static int printfInsertMeta() {
1008 1009
    SHOW_PARSE_RESULT_START();

1010 1011 1012 1013 1014 1015
  printf("host:                       \033[33m%s:%u\033[0m\n", g_Dbs.host, g_Dbs.port);
  printf("user:                       \033[33m%s\033[0m\n", g_Dbs.user);
  printf("password:                   \033[33m%s\033[0m\n", g_Dbs.password);
  printf("resultFile:                 \033[33m%s\033[0m\n", g_Dbs.resultFile);
  printf("thread num of insert data:  \033[33m%d\033[0m\n", g_Dbs.threadCount);
  printf("thread num of create table: \033[33m%d\033[0m\n", g_Dbs.threadCountByCreateTbl);
1016 1017
  printf("insert interval:            \033[33m%d\033[0m\n", g_args.insert_interval);
  printf("number of records per req:  \033[33m%d\033[0m\n", g_args.num_of_RPR);
1018
  printf("max sql length:             \033[33m%d\033[0m\n", g_args.max_sql_len);
1019 1020 1021 1022

  printf("database count:             \033[33m%d\033[0m\n", g_Dbs.dbCount);
  for (int i = 0; i < g_Dbs.dbCount; i++) {
    printf("database[\033[33m%d\033[0m]:\n", i);
1023
    printf("  database[%d] name:      \033[33m%s\033[0m\n", i, g_Dbs.db[i].dbName);
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
    if (0 == g_Dbs.db[i].drop) {
      printf("  drop:                  \033[33mno\033[0m\n");     
    }else {
      printf("  drop:                  \033[33myes\033[0m\n"); 
    }

    if (g_Dbs.db[i].dbCfg.blocks > 0) {
      printf("  blocks:                \033[33m%d\033[0m\n", g_Dbs.db[i].dbCfg.blocks);
    }
    if (g_Dbs.db[i].dbCfg.cache > 0) {
      printf("  cache:                 \033[33m%d\033[0m\n", g_Dbs.db[i].dbCfg.cache);
    }
    if (g_Dbs.db[i].dbCfg.days > 0) {
      printf("  days:                  \033[33m%d\033[0m\n", g_Dbs.db[i].dbCfg.days);
    }
    if (g_Dbs.db[i].dbCfg.keep > 0) {
      printf("  keep:                  \033[33m%d\033[0m\n", g_Dbs.db[i].dbCfg.keep);
    }
    if (g_Dbs.db[i].dbCfg.replica > 0) {
      printf("  replica:               \033[33m%d\033[0m\n", g_Dbs.db[i].dbCfg.replica);
    }
    if (g_Dbs.db[i].dbCfg.update > 0) {
      printf("  update:                \033[33m%d\033[0m\n", g_Dbs.db[i].dbCfg.update);
    }
    if (g_Dbs.db[i].dbCfg.minRows > 0) {
      printf("  minRows:               \033[33m%d\033[0m\n", g_Dbs.db[i].dbCfg.minRows);
    }
    if (g_Dbs.db[i].dbCfg.maxRows > 0) {
      printf("  maxRows:               \033[33m%d\033[0m\n", g_Dbs.db[i].dbCfg.maxRows);
    }
    if (g_Dbs.db[i].dbCfg.comp > 0) {
      printf("  comp:                  \033[33m%d\033[0m\n", g_Dbs.db[i].dbCfg.comp);
    }
    if (g_Dbs.db[i].dbCfg.walLevel > 0) {
      printf("  walLevel:              \033[33m%d\033[0m\n", g_Dbs.db[i].dbCfg.walLevel);
    }
    if (g_Dbs.db[i].dbCfg.fsync > 0) {
      printf("  fsync:                 \033[33m%d\033[0m\n", g_Dbs.db[i].dbCfg.fsync);
    }
    if (g_Dbs.db[i].dbCfg.quorum > 0) {
      printf("  quorum:                \033[33m%d\033[0m\n", g_Dbs.db[i].dbCfg.quorum);
    }
    if (g_Dbs.db[i].dbCfg.precision[0] != 0) {
1067 1068
      if ((0 == strncasecmp(g_Dbs.db[i].dbCfg.precision, "ms", 2))
              || (0 == strncasecmp(g_Dbs.db[i].dbCfg.precision, "us", 2))) {
1069 1070
        printf("  precision:             \033[33m%s\033[0m\n", g_Dbs.db[i].dbCfg.precision);
      } else {
1071 1072 1073
        printf("\033[1m\033[40;31m  precision error:       %s\033[0m\n",
                g_Dbs.db[i].dbCfg.precision);
        return -1;
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
      }
    }

    printf("  super table count:     \033[33m%d\033[0m\n", g_Dbs.db[i].superTblCount);
    for (int j = 0; j < g_Dbs.db[i].superTblCount; j++) {
      printf("  super table[\033[33m%d\033[0m]:\n", j);
    
      printf("      stbName:           \033[33m%s\033[0m\n",  g_Dbs.db[i].superTbls[j].sTblName);   

      if (PRE_CREATE_SUBTBL == g_Dbs.db[i].superTbls[j].autoCreateTable) {
        printf("      autoCreateTable:   \033[33m%s\033[0m\n",  "no");
      } else if (AUTO_CREATE_SUBTBL == g_Dbs.db[i].superTbls[j].autoCreateTable) {
        printf("      autoCreateTable:   \033[33m%s\033[0m\n",  "yes");
      } else {
        printf("      autoCreateTable:   \033[33m%s\033[0m\n",  "error");
      }
      
      if (TBL_NO_EXISTS == g_Dbs.db[i].superTbls[j].childTblExists) {
        printf("      childTblExists:    \033[33m%s\033[0m\n",  "no");
      } else if (TBL_ALREADY_EXISTS == g_Dbs.db[i].superTbls[j].childTblExists) {
        printf("      childTblExists:    \033[33m%s\033[0m\n",  "yes");
      } else {
        printf("      childTblExists:    \033[33m%s\033[0m\n",  "error");
      }
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109

      printf("      childTblCount:     \033[33m%d\033[0m\n",  g_Dbs.db[i].superTbls[j].childTblCount);
      printf("      childTblPrefix:    \033[33m%s\033[0m\n",  g_Dbs.db[i].superTbls[j].childTblPrefix);
      printf("      dataSource:        \033[33m%s\033[0m\n",  g_Dbs.db[i].superTbls[j].dataSource);
      printf("      insertMode:        \033[33m%s\033[0m\n",  g_Dbs.db[i].superTbls[j].insertMode);
      if (g_Dbs.db[i].superTbls[j].childTblLimit > 0) {
        printf("      childTblLimit:     \033[33m%d\033[0m\n",  g_Dbs.db[i].superTbls[j].childTblLimit);
      }
      if (g_Dbs.db[i].superTbls[j].childTblOffset > 0) {
        printf("      childTblOffset:    \033[33m%d\033[0m\n",  g_Dbs.db[i].superTbls[j].childTblOffset);
      }
      printf("      insertRows:        \033[33m%"PRId64"\033[0m\n", g_Dbs.db[i].superTbls[j].insertRows);
1110 1111

      if (0 == g_Dbs.db[i].superTbls[j].multiThreadWriteOneTbl) {
1112
        printf("      multiThreadWriteOneTbl:  \033[33mno\033[0m\n");
1113
      }else {
1114
        printf("      multiThreadWriteOneTbl:  \033[33myes\033[0m\n");
1115
      }
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
      printf("      numberOfTblInOneSql:     \033[33m%d\033[0m\n",
              g_Dbs.db[i].superTbls[j].numberOfTblInOneSql);
      printf("      rowsPerTbl:        \033[33m%d\033[0m\n",
              g_Dbs.db[i].superTbls[j].rowsPerTbl);
      printf("      disorderRange:     \033[33m%d\033[0m\n",
              g_Dbs.db[i].superTbls[j].disorderRange);
      printf("      disorderRatio:     \033[33m%d\033[0m\n",
              g_Dbs.db[i].superTbls[j].disorderRatio);
      printf("      maxSqlLen:         \033[33m%d\033[0m\n",
              g_Dbs.db[i].superTbls[j].maxSqlLen);
      printf("      timeStampStep:     \033[33m%d\033[0m\n",
              g_Dbs.db[i].superTbls[j].timeStampStep);
      printf("      startTimestamp:    \033[33m%s\033[0m\n",
              g_Dbs.db[i].superTbls[j].startTimestamp);
      printf("      sampleFormat:      \033[33m%s\033[0m\n",
              g_Dbs.db[i].superTbls[j].sampleFormat);
      printf("      sampleFile:        \033[33m%s\033[0m\n",
              g_Dbs.db[i].superTbls[j].sampleFile);
      printf("      tagsFile:          \033[33m%s\033[0m\n",
              g_Dbs.db[i].superTbls[j].tagsFile);
      printf("      columnCount:       \033[33m%d\033[0m\n        ",
              g_Dbs.db[i].superTbls[j].columnCount);
1138 1139
      for (int k = 0; k < g_Dbs.db[i].superTbls[j].columnCount; k++) {
        //printf("dataType:%s, dataLen:%d\t", g_Dbs.db[i].superTbls[j].columns[k].dataType, g_Dbs.db[i].superTbls[j].columns[k].dataLen);
1140 1141 1142 1143
        if ((0 == strncasecmp(g_Dbs.db[i].superTbls[j].columns[k].dataType,
                       "binary", 6))
                || (0 == strncasecmp(g_Dbs.db[i].superTbls[j].columns[k].dataType,
                       "nchar", 5))) {
1144
          printf("column[\033[33m%d\033[0m]:\033[33m%s(%d)\033[0m ", k,
1145 1146
                  g_Dbs.db[i].superTbls[j].columns[k].dataType,
                  g_Dbs.db[i].superTbls[j].columns[k].dataLen);
1147
        } else {
1148 1149
          printf("column[%d]:\033[33m%s\033[0m ", k,
                  g_Dbs.db[i].superTbls[j].columns[k].dataType);
1150 1151 1152
        }
      }
      printf("\n");
1153 1154 1155

      printf("      tagCount:            \033[33m%d\033[0m\n        ",
              g_Dbs.db[i].superTbls[j].tagCount);
1156 1157
      for (int k = 0; k < g_Dbs.db[i].superTbls[j].tagCount; k++) {
        //printf("dataType:%s, dataLen:%d\t", g_Dbs.db[i].superTbls[j].tags[k].dataType, g_Dbs.db[i].superTbls[j].tags[k].dataLen);
1158 1159 1160
        if ((0 == strncasecmp(g_Dbs.db[i].superTbls[j].tags[k].dataType, "binary", 6))
                || (0 == strncasecmp(g_Dbs.db[i].superTbls[j].tags[k].dataType, "nchar", 5))) {
          printf("tag[%d]:\033[33m%s(%d)\033[0m ", k,
1161 1162
                  g_Dbs.db[i].superTbls[j].tags[k].dataType,
                  g_Dbs.db[i].superTbls[j].tags[k].dataLen);
1163
        } else {
1164 1165
          printf("tag[%d]:\033[33m%s\033[0m ", k,
                  g_Dbs.db[i].superTbls[j].tags[k].dataType);
1166
        }
1167 1168 1169 1170 1171
      }
      printf("\n");
    }
    printf("\n");
  }
1172 1173

  SHOW_PARSE_RESULT_END();
1174 1175

  return 0;
1176 1177 1178
}

static void printfInsertMetaToFile(FILE* fp) {
1179 1180
    SHOW_PARSE_RESULT_START_TO_FILE(fp);

1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
  fprintf(fp, "host:                       %s:%u\n", g_Dbs.host, g_Dbs.port);
  fprintf(fp, "user:                       %s\n", g_Dbs.user);
  fprintf(fp, "password:                   %s\n", g_Dbs.password);
  fprintf(fp, "resultFile:                 %s\n", g_Dbs.resultFile);
  fprintf(fp, "thread num of insert data:  %d\n", g_Dbs.threadCount);
  fprintf(fp, "thread num of create table: %d\n", g_Dbs.threadCountByCreateTbl);

  fprintf(fp, "database count:          %d\n", g_Dbs.dbCount);
  for (int i = 0; i < g_Dbs.dbCount; i++) {
    fprintf(fp, "database[%d]:\n", i);
1191
    fprintf(fp, "  database[%d] name:       %s\n", i, g_Dbs.db[i].dbName);
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
    if (0 == g_Dbs.db[i].drop) {
      fprintf(fp, "  drop:                  no\n");     
    }else {
      fprintf(fp, "  drop:                  yes\n"); 
    }

    if (g_Dbs.db[i].dbCfg.blocks > 0) {
      fprintf(fp, "  blocks:                %d\n", g_Dbs.db[i].dbCfg.blocks);
    }
    if (g_Dbs.db[i].dbCfg.cache > 0) {
      fprintf(fp, "  cache:                 %d\n", g_Dbs.db[i].dbCfg.cache);
    }
    if (g_Dbs.db[i].dbCfg.days > 0) {
      fprintf(fp, "  days:                  %d\n", g_Dbs.db[i].dbCfg.days);
    }
    if (g_Dbs.db[i].dbCfg.keep > 0) {
      fprintf(fp, "  keep:                  %d\n", g_Dbs.db[i].dbCfg.keep);
    }
    if (g_Dbs.db[i].dbCfg.replica > 0) {
      fprintf(fp, "  replica:               %d\n", g_Dbs.db[i].dbCfg.replica);
    }
    if (g_Dbs.db[i].dbCfg.update > 0) {
      fprintf(fp, "  update:                %d\n", g_Dbs.db[i].dbCfg.update);
    }
    if (g_Dbs.db[i].dbCfg.minRows > 0) {
      fprintf(fp, "  minRows:               %d\n", g_Dbs.db[i].dbCfg.minRows);
    }
    if (g_Dbs.db[i].dbCfg.maxRows > 0) {
      fprintf(fp, "  maxRows:               %d\n", g_Dbs.db[i].dbCfg.maxRows);
    }
    if (g_Dbs.db[i].dbCfg.comp > 0) {
      fprintf(fp, "  comp:                  %d\n", g_Dbs.db[i].dbCfg.comp);
    }
    if (g_Dbs.db[i].dbCfg.walLevel > 0) {
      fprintf(fp, "  walLevel:              %d\n", g_Dbs.db[i].dbCfg.walLevel);
    }
    if (g_Dbs.db[i].dbCfg.fsync > 0) {
      fprintf(fp, "  fsync:                 %d\n", g_Dbs.db[i].dbCfg.fsync);
    }
    if (g_Dbs.db[i].dbCfg.quorum > 0) {
      fprintf(fp, "  quorum:                %d\n", g_Dbs.db[i].dbCfg.quorum);
    }
    if (g_Dbs.db[i].dbCfg.precision[0] != 0) {
1235 1236
      if ((0 == strncasecmp(g_Dbs.db[i].dbCfg.precision, "ms", 2))
              || (0 == strncasecmp(g_Dbs.db[i].dbCfg.precision, "us", 2))) {
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
        fprintf(fp, "  precision:             %s\n", g_Dbs.db[i].dbCfg.precision);
      } else {
        fprintf(fp, "  precision error:       %s\n", g_Dbs.db[i].dbCfg.precision);
      }
    }

    fprintf(fp, "  super table count:     %d\n", g_Dbs.db[i].superTblCount);
    for (int j = 0; j < g_Dbs.db[i].superTblCount; j++) {
      fprintf(fp, "  super table[%d]:\n", j);
    
      fprintf(fp, "      stbName:           %s\n",  g_Dbs.db[i].superTbls[j].sTblName);   

      if (PRE_CREATE_SUBTBL == g_Dbs.db[i].superTbls[j].autoCreateTable) {
        fprintf(fp, "      autoCreateTable:   %s\n",  "no");
      } else if (AUTO_CREATE_SUBTBL == g_Dbs.db[i].superTbls[j].autoCreateTable) {
        fprintf(fp, "      autoCreateTable:   %s\n",  "yes");
      } else {
        fprintf(fp, "      autoCreateTable:   %s\n",  "error");
      }
      
      if (TBL_NO_EXISTS == g_Dbs.db[i].superTbls[j].childTblExists) {
        fprintf(fp, "      childTblExists:    %s\n",  "no");
      } else if (TBL_ALREADY_EXISTS == g_Dbs.db[i].superTbls[j].childTblExists) {
        fprintf(fp, "      childTblExists:    %s\n",  "yes");
      } else {
        fprintf(fp, "      childTblExists:    %s\n",  "error");
      }
      
      fprintf(fp, "      childTblCount:     %d\n",  g_Dbs.db[i].superTbls[j].childTblCount);      
      fprintf(fp, "      childTblPrefix:    %s\n",  g_Dbs.db[i].superTbls[j].childTblPrefix);      
      fprintf(fp, "      dataSource:        %s\n",  g_Dbs.db[i].superTbls[j].dataSource);      
      fprintf(fp, "      insertMode:        %s\n",  g_Dbs.db[i].superTbls[j].insertMode);      
      fprintf(fp, "      insertRows:        %"PRId64"\n", g_Dbs.db[i].superTbls[j].insertRows); 
1270
      fprintf(fp, "      insert interval:   %d\n", g_Dbs.db[i].superTbls[j].insertInterval);
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312

      if (0 == g_Dbs.db[i].superTbls[j].multiThreadWriteOneTbl) {
        fprintf(fp, "      multiThreadWriteOneTbl:  no\n");     
      }else {
        fprintf(fp, "      multiThreadWriteOneTbl:  yes\n"); 
      }
      fprintf(fp, "      numberOfTblInOneSql:     %d\n",  g_Dbs.db[i].superTbls[j].numberOfTblInOneSql);     
      fprintf(fp, "      rowsPerTbl:        %d\n",  g_Dbs.db[i].superTbls[j].rowsPerTbl);     
      fprintf(fp, "      disorderRange:     %d\n",  g_Dbs.db[i].superTbls[j].disorderRange);     
      fprintf(fp, "      disorderRatio:     %d\n",  g_Dbs.db[i].superTbls[j].disorderRatio);
      fprintf(fp, "      maxSqlLen:         %d\n",  g_Dbs.db[i].superTbls[j].maxSqlLen);     
      
      fprintf(fp, "      timeStampStep:     %d\n",  g_Dbs.db[i].superTbls[j].timeStampStep);      
      fprintf(fp, "      startTimestamp:    %s\n",  g_Dbs.db[i].superTbls[j].startTimestamp);             
      fprintf(fp, "      sampleFormat:      %s\n",  g_Dbs.db[i].superTbls[j].sampleFormat);
      fprintf(fp, "      sampleFile:        %s\n",  g_Dbs.db[i].superTbls[j].sampleFile); 
      fprintf(fp, "      tagsFile:          %s\n",  g_Dbs.db[i].superTbls[j].tagsFile);   
    
      fprintf(fp, "      columnCount:       %d\n        ",  g_Dbs.db[i].superTbls[j].columnCount);
      for (int k = 0; k < g_Dbs.db[i].superTbls[j].columnCount; k++) {
        //printf("dataType:%s, dataLen:%d\t", g_Dbs.db[i].superTbls[j].columns[k].dataType, g_Dbs.db[i].superTbls[j].columns[k].dataLen);
        if ((0 == strncasecmp(g_Dbs.db[i].superTbls[j].columns[k].dataType, "binary", 6)) || (0 == strncasecmp(g_Dbs.db[i].superTbls[j].columns[k].dataType, "nchar", 5))) {
          fprintf(fp, "column[%d]:%s(%d) ", k, g_Dbs.db[i].superTbls[j].columns[k].dataType, g_Dbs.db[i].superTbls[j].columns[k].dataLen);
        } else {
          fprintf(fp, "column[%d]:%s ", k, g_Dbs.db[i].superTbls[j].columns[k].dataType);
        }
      }
      fprintf(fp, "\n");
      
      fprintf(fp, "      tagCount:            %d\n        ",  g_Dbs.db[i].superTbls[j].tagCount);
      for (int k = 0; k < g_Dbs.db[i].superTbls[j].tagCount; k++) {
        //printf("dataType:%s, dataLen:%d\t", g_Dbs.db[i].superTbls[j].tags[k].dataType, g_Dbs.db[i].superTbls[j].tags[k].dataLen);
        if ((0 == strncasecmp(g_Dbs.db[i].superTbls[j].tags[k].dataType, "binary", 6)) || (0 == strncasecmp(g_Dbs.db[i].superTbls[j].tags[k].dataType, "nchar", 5))) {
          fprintf(fp, "tag[%d]:%s(%d) ", k, g_Dbs.db[i].superTbls[j].tags[k].dataType, g_Dbs.db[i].superTbls[j].tags[k].dataLen);
        } else {
          fprintf(fp, "tag[%d]:%s ", k, g_Dbs.db[i].superTbls[j].tags[k].dataType);
        }     
      }
      fprintf(fp, "\n");
    }
    fprintf(fp, "\n");
  }
1313
    SHOW_PARSE_RESULT_END_TO_FILE(fp);
1314 1315 1316
}

static void printfQueryMeta() {
1317
    SHOW_PARSE_RESULT_START();
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
  printf("host:                    \033[33m%s:%u\033[0m\n", g_queryInfo.host, g_queryInfo.port);
  printf("user:                    \033[33m%s\033[0m\n", g_queryInfo.user);
  printf("password:                \033[33m%s\033[0m\n", g_queryInfo.password);
  printf("database name:           \033[33m%s\033[0m\n", g_queryInfo.dbName);

  printf("\n");
  printf("specified table query info:                   \n");  
  printf("query interval: \033[33m%d\033[0m\n", g_queryInfo.superQueryInfo.rate);
  printf("concurrent:     \033[33m%d\033[0m\n", g_queryInfo.superQueryInfo.concurrent);
  printf("sqlCount:       \033[33m%d\033[0m\n", g_queryInfo.superQueryInfo.sqlCount); 

1329
  if (SUBSCRIBE_MODE == g_args.test_mode) {
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
    printf("mod:            \033[33m%d\033[0m\n", g_queryInfo.superQueryInfo.subscribeMode);
    printf("interval:       \033[33m%d\033[0m\n", g_queryInfo.superQueryInfo.subscribeInterval);
    printf("restart:        \033[33m%d\033[0m\n", g_queryInfo.superQueryInfo.subscribeRestart);
    printf("keepProgress:   \033[33m%d\033[0m\n", g_queryInfo.superQueryInfo.subscribeKeepProgress);
  }

  for (int i = 0; i < g_queryInfo.superQueryInfo.sqlCount; i++) {
    printf("  sql[%d]: \033[33m%s\033[0m\n", i, g_queryInfo.superQueryInfo.sql[i]);
  }
  printf("\n");
  printf("super table query info:                   \n");  
  printf("query interval: \033[33m%d\033[0m\n", g_queryInfo.subQueryInfo.rate);
  printf("threadCnt:      \033[33m%d\033[0m\n", g_queryInfo.subQueryInfo.threadCnt);
  printf("childTblCount:  \033[33m%d\033[0m\n", g_queryInfo.subQueryInfo.childTblCount);
  printf("stable name:    \033[33m%s\033[0m\n", g_queryInfo.subQueryInfo.sTblName);

1346
  if (SUBSCRIBE_MODE == g_args.test_mode) {
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
    printf("mod:            \033[33m%d\033[0m\n", g_queryInfo.subQueryInfo.subscribeMode);
    printf("interval:       \033[33m%d\033[0m\n", g_queryInfo.subQueryInfo.subscribeInterval);
    printf("restart:        \033[33m%d\033[0m\n", g_queryInfo.subQueryInfo.subscribeRestart);
    printf("keepProgress:   \033[33m%d\033[0m\n", g_queryInfo.subQueryInfo.subscribeKeepProgress);
  }
  
  printf("sqlCount:       \033[33m%d\033[0m\n", g_queryInfo.subQueryInfo.sqlCount);  
  for (int i = 0; i < g_queryInfo.subQueryInfo.sqlCount; i++) {
    printf("  sql[%d]: \033[33m%s\033[0m\n", i, g_queryInfo.subQueryInfo.sql[i]);
  }  
  printf("\n");
1358 1359

    SHOW_PARSE_RESULT_END();
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 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 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
}


static char* xFormatTimestamp(char* buf, int64_t val, int precision) {
  time_t tt;
  if (precision == TSDB_TIME_PRECISION_MICRO) {
    tt = (time_t)(val / 1000000);
  } else {
    tt = (time_t)(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;
  }
  */

#ifdef WINDOWS
  if (tt < 0) tt = 0;
#endif

  struct tm* ptm = localtime(&tt);
  size_t pos = strftime(buf, 32, "%Y-%m-%d %H:%M:%S", ptm);

  if (precision == TSDB_TIME_PRECISION_MICRO) {
    sprintf(buf + pos, ".%06d", (int)(val % 1000000));
  } else {
    sprintf(buf + pos, ".%03d", (int)(val % 1000));
  }

  return buf;
}

static void xDumpFieldToFile(FILE* fp, const char* val, TAOS_FIELD* field, int32_t length, int precision) {
  if (val == NULL) {
    fprintf(fp, "%s", TSDB_DATA_NULL_STR);
    return;
  }

  char buf[TSDB_MAX_BYTES_PER_ROW];
  switch (field->type) {
    case TSDB_DATA_TYPE_BOOL:
      fprintf(fp, "%d", ((((int32_t)(*((char *)val))) == 1) ? 1 : 0));
      break;
    case TSDB_DATA_TYPE_TINYINT:
      fprintf(fp, "%d", *((int8_t *)val));
      break;
    case TSDB_DATA_TYPE_SMALLINT:
      fprintf(fp, "%d", *((int16_t *)val));
      break;
    case TSDB_DATA_TYPE_INT:
      fprintf(fp, "%d", *((int32_t *)val));
      break;
    case TSDB_DATA_TYPE_BIGINT:
      fprintf(fp, "%" PRId64, *((int64_t *)val));
      break;
    case TSDB_DATA_TYPE_FLOAT:
      fprintf(fp, "%.5f", GET_FLOAT_VAL(val));
      break;
    case TSDB_DATA_TYPE_DOUBLE:
      fprintf(fp, "%.9f", GET_DOUBLE_VAL(val));
      break;
    case TSDB_DATA_TYPE_BINARY:
    case TSDB_DATA_TYPE_NCHAR:
      memcpy(buf, val, length);
      buf[length] = 0;
      fprintf(fp, "\'%s\'", buf);
      break;
    case TSDB_DATA_TYPE_TIMESTAMP:
      xFormatTimestamp(buf, *(int64_t*)val, precision);
      fprintf(fp, "'%s'", buf);
      break;
    default:
      break;
  }
}

static int xDumpResultToFile(const char* fname, TAOS_RES* tres) {
  TAOS_ROW row = taos_fetch_row(tres);
  if (row == NULL) {
    return 0;
  }

  FILE* fp = fopen(fname, "at");
  if (fp == NULL) {
    fprintf(stderr, "ERROR: failed to open file: %s\n", fname);
    return -1;
  }

  int num_fields = taos_num_fields(tres);
  TAOS_FIELD *fields = taos_fetch_fields(tres);
  int precision = taos_result_precision(tres);

  for (int col = 0; col < num_fields; col++) {
    if (col > 0) {
      fprintf(fp, ",");
    }
    fprintf(fp, "%s", fields[col].name);
  }
  fputc('\n', fp);
  
  int numOfRows = 0;
  do {
    int32_t* length = taos_fetch_lengths(tres);
    for (int i = 0; i < num_fields; i++) {
      if (i > 0) {
        fputc(',', fp);
      }
      xDumpFieldToFile(fp, (const char*)row[i], fields +i, length[i], precision);
    }
    fputc('\n', fp);

    numOfRows++;
    row = taos_fetch_row(tres);
  } while( row != NULL);

  fclose(fp);

  return numOfRows;
}

static int getDbFromServer(TAOS * taos, SDbInfo** dbInfos) {  
  TAOS_RES * res;  
  TAOS_ROW row = NULL;
  int count = 0;
  
  res = taos_query(taos, "show databases;");  
  int32_t code = taos_errno(res);
  
  if (code != 0) {
    fprintf(stderr, "failed to run <show databases>, reason: %s\n", taos_errstr(res));
    return -1;
  }

  TAOS_FIELD *fields = taos_fetch_fields(res);

  while ((row = taos_fetch_row(res)) != NULL) {
    // sys database name : 'log'
    if (strncasecmp(row[TSDB_SHOW_DB_NAME_INDEX], "log", fields[TSDB_SHOW_DB_NAME_INDEX].bytes) == 0) continue;

    dbInfos[count] = (SDbInfo *)calloc(1, sizeof(SDbInfo));
    if (dbInfos[count] == NULL) {
      fprintf(stderr, "failed to allocate memory for some dbInfo[%d]\n", count);
      return -1;
    }

1508
    tstrncpy(dbInfos[count]->name, (char *)row[TSDB_SHOW_DB_NAME_INDEX], fields[TSDB_SHOW_DB_NAME_INDEX].bytes);
1509 1510 1511 1512 1513 1514 1515
    xFormatTimestamp(dbInfos[count]->create_time, *(int64_t*)row[TSDB_SHOW_DB_CREATED_TIME_INDEX], TSDB_TIME_PRECISION_MILLI);
    dbInfos[count]->ntables = *((int32_t *)row[TSDB_SHOW_DB_NTABLES_INDEX]);
    dbInfos[count]->vgroups = *((int32_t *)row[TSDB_SHOW_DB_VGROUPS_INDEX]);  
    dbInfos[count]->replica = *((int16_t *)row[TSDB_SHOW_DB_REPLICA_INDEX]);
    dbInfos[count]->quorum = *((int16_t *)row[TSDB_SHOW_DB_QUORUM_INDEX]);
    dbInfos[count]->days = *((int16_t *)row[TSDB_SHOW_DB_DAYS_INDEX]);  

1516
    tstrncpy(dbInfos[count]->keeplist, (char *)row[TSDB_SHOW_DB_KEEP_INDEX], fields[TSDB_SHOW_DB_KEEP_INDEX].bytes);      
1517 1518 1519 1520 1521 1522 1523 1524 1525
    dbInfos[count]->cache = *((int32_t *)row[TSDB_SHOW_DB_CACHE_INDEX]);
    dbInfos[count]->blocks = *((int32_t *)row[TSDB_SHOW_DB_BLOCKS_INDEX]);
    dbInfos[count]->minrows = *((int32_t *)row[TSDB_SHOW_DB_MINROWS_INDEX]);
    dbInfos[count]->maxrows = *((int32_t *)row[TSDB_SHOW_DB_MAXROWS_INDEX]);
    dbInfos[count]->wallevel = *((int8_t *)row[TSDB_SHOW_DB_WALLEVEL_INDEX]);
    dbInfos[count]->fsync = *((int32_t *)row[TSDB_SHOW_DB_FSYNC_INDEX]);
    dbInfos[count]->comp = (int8_t)(*((int8_t *)row[TSDB_SHOW_DB_COMP_INDEX]));
    dbInfos[count]->cachelast = (int8_t)(*((int8_t *)row[TSDB_SHOW_DB_CACHELAST_INDEX]));

1526 1527 1528
    tstrncpy(dbInfos[count]->precision, 
            (char *)row[TSDB_SHOW_DB_PRECISION_INDEX],
            fields[TSDB_SHOW_DB_PRECISION_INDEX].bytes);  
1529
    dbInfos[count]->update = *((int8_t *)row[TSDB_SHOW_DB_UPDATE_INDEX]);
1530
    tstrncpy(dbInfos[count]->status, (char *)row[TSDB_SHOW_DB_STATUS_INDEX], fields[TSDB_SHOW_DB_STATUS_INDEX].bytes); 
1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
    
    count++;
    if (count > MAX_DATABASE_COUNT) {
      fprintf(stderr, "The database count overflow than %d\n", MAX_DATABASE_COUNT);      
      break;
    }
  }

  return count;
}

static void printfDbInfoForQueryToFile(char* filename, SDbInfo* dbInfos, int index) {
1543
  if (filename[0] == 0)
1544
      return;
1545 1546 1547 1548 1549

  FILE *fp = fopen(filename, "at");
  if (fp == NULL) {
    fprintf(stderr, "failed to open file: %s\n", filename);
    return;
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 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
  }

  fprintf(fp, "================ database[%d] ================\n", index);
  fprintf(fp, "name: %s\n", dbInfos->name);
  fprintf(fp, "created_time: %s\n", dbInfos->create_time);
  fprintf(fp, "ntables: %d\n", dbInfos->ntables);
  fprintf(fp, "vgroups: %d\n", dbInfos->vgroups);  
  fprintf(fp, "replica: %d\n", dbInfos->replica);
  fprintf(fp, "quorum: %d\n", dbInfos->quorum);
  fprintf(fp, "days: %d\n", dbInfos->days);    
  fprintf(fp, "keep0,keep1,keep(D): %s\n", dbInfos->keeplist);      
  fprintf(fp, "cache(MB): %d\n", dbInfos->cache);
  fprintf(fp, "blocks: %d\n", dbInfos->blocks);
  fprintf(fp, "minrows: %d\n", dbInfos->minrows);
  fprintf(fp, "maxrows: %d\n", dbInfos->maxrows);
  fprintf(fp, "wallevel: %d\n", dbInfos->wallevel);
  fprintf(fp, "fsync: %d\n", dbInfos->fsync);
  fprintf(fp, "comp: %d\n", dbInfos->comp);
  fprintf(fp, "cachelast: %d\n", dbInfos->cachelast);  
  fprintf(fp, "precision: %s\n", dbInfos->precision);  
  fprintf(fp, "update: %d\n", dbInfos->update);
  fprintf(fp, "status: %s\n", dbInfos->status); 
  fprintf(fp, "\n");

  fclose(fp);
}

static void printfQuerySystemInfo(TAOS * taos) {
  char filename[MAX_QUERY_SQL_LENGTH+1] = {0};
  char buffer[MAX_QUERY_SQL_LENGTH+1] = {0};
  TAOS_RES* res;

  time_t t;
  struct tm* lt;
  time(&t);
  lt = localtime(&t);
  snprintf(filename, MAX_QUERY_SQL_LENGTH, "querySystemInfo-%d-%d-%d %d:%d:%d", lt->tm_year+1900, lt->tm_mon, lt->tm_mday, lt->tm_hour, lt->tm_min, lt->tm_sec);
  
  // show variables
  res = taos_query(taos, "show variables;");
  //getResult(res, filename);
  xDumpResultToFile(filename, res);

  // show dnodes
  res = taos_query(taos, "show dnodes;");
  xDumpResultToFile(filename, res);
  //getResult(res, filename);
  
  // show databases
  res = taos_query(taos, "show databases;");
  SDbInfo** dbInfos = (SDbInfo **)calloc(MAX_DATABASE_COUNT, sizeof(SDbInfo *));
  if (dbInfos == NULL) {
    fprintf(stderr, "failed to allocate memory\n");
    return;
  }
  int dbCount = getDbFromServer(taos, dbInfos);
1606 1607 1608 1609
  if (dbCount <= 0) {
      free(dbInfos);
      return;
  }
1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631

  for (int i = 0; i < dbCount; i++) {
    // printf database info 
    printfDbInfoForQueryToFile(filename, dbInfos[i], i);
    
    // show db.vgroups
    snprintf(buffer, MAX_QUERY_SQL_LENGTH, "show %s.vgroups;", dbInfos[i]->name);
    res = taos_query(taos, buffer);
    xDumpResultToFile(filename, res);
  
    // show db.stables
    snprintf(buffer, MAX_QUERY_SQL_LENGTH, "show %s.stables;", dbInfos[i]->name);
    res = taos_query(taos, buffer);
    xDumpResultToFile(filename, res);

    free(dbInfos[i]);
  }

  free(dbInfos);
  
}

1632
void ERROR_EXIT(const char *msg) { perror(msg); exit(-1); }
1633 1634 1635

int postProceSql(char* host, uint16_t port, char* sqlstr)
{
1636
    char *req_fmt = "POST %s HTTP/1.1\r\nHost: %s:%d\r\nAccept: */*\r\nAuthorization: Basic %s\r\nContent-Length: %d\r\nContent-Type: application/x-www-form-urlencoded\r\n\r\n%s";
1637 1638 1639 1640 1641

    char *url = "/rest/sql";

    struct hostent *server;
    struct sockaddr_in serv_addr;
1642
    int bytes, sent, received, req_str_len, resp_len;
1643 1644 1645
    char *request_buf;
    char response_buf[RESP_BUF_LEN];
    uint16_t rest_port = port + TSDB_PORT_HTTP;
1646

1647 1648 1649 1650
    int req_buf_len = strlen(sqlstr) + REQ_EXTRA_BUF_LEN;

    request_buf = malloc(req_buf_len);
    if (NULL == request_buf)
1651
        ERROR_EXIT("ERROR, cannot allocate memory.");
1652

1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
    char userpass_buf[INPUT_BUF_LEN];
    int mod_table[] = {0, 2, 1};

    static char base64[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
      'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
      'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
      'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
      'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
      'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
      'w', 'x', 'y', 'z', '0', '1', '2', '3',
      '4', '5', '6', '7', '8', '9', '+', '/'};
1664

1665 1666 1667 1668 1669 1670
    snprintf(userpass_buf, INPUT_BUF_LEN, "%s:%s",
        g_Dbs.user, g_Dbs.password);
    size_t userpass_buf_len = strlen(userpass_buf);
    size_t encoded_len = 4 * ((userpass_buf_len +2) / 3);

    char base64_buf[INPUT_BUF_LEN];
1671
#ifdef WINDOWS
1672
    WSADATA wsaData;
1673
    WSAStartup(MAKEWORD(2, 2), &wsaData);
1674 1675 1676 1677
    SOCKET sockfd;
#else
    int sockfd;
#endif
1678
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
1679
    if (sockfd < 0) {
1680 1681 1682 1683
#ifdef WINDOWS
        fprintf(stderr, "Could not create socket : %d" , WSAGetLastError());
#endif
        debugPrint("%s() LN%d sockfd=%d\n", __func__, __LINE__, sockfd);
1684
        free(request_buf);
1685
        ERROR_EXIT("ERROR opening socket");
1686
    }
1687 1688

    server = gethostbyname(host);
1689 1690
    if (server == NULL) {
        free(request_buf);
1691
        ERROR_EXIT("ERROR, no such host");
1692
    }
1693

1694
    debugPrint("h_name: %s\nh_addretype: %s\nh_length: %d\n",
1695 1696 1697 1698
            server->h_name,
            (server->h_addrtype == AF_INET)?"ipv4":"ipv6",
            server->h_length);

1699
    memset(&serv_addr, 0, sizeof(serv_addr));
1700
    serv_addr.sin_family = AF_INET;
1701
    serv_addr.sin_port = htons(rest_port);
1702 1703 1704
#ifdef WINDOWS
    serv_addr.sin_addr.s_addr = inet_addr(host);
#else
1705
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);
1706
#endif
1707

1708 1709 1710
    int retConn = connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr));
    debugPrint("%s() LN%d connect() return %d\n", __func__, __LINE__, retConn);
    if (retConn < 0) {
1711
        free(request_buf);
1712
        ERROR_EXIT("ERROR connecting");
1713
    }
1714

1715 1716 1717
    memset(base64_buf, 0, INPUT_BUF_LEN);

    for (int n = 0, m = 0; n < userpass_buf_len;) {
1718
      uint32_t oct_a = n < userpass_buf_len ?
1719
        (unsigned char) userpass_buf[n++]:0;
1720
      uint32_t oct_b = n < userpass_buf_len ?
1721
        (unsigned char) userpass_buf[n++]:0;
1722
      uint32_t oct_c = n < userpass_buf_len ?
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
        (unsigned char) userpass_buf[n++]:0;
      uint32_t triple = (oct_a << 0x10) + (oct_b << 0x08) + oct_c;

      base64_buf[m++] = base64[(triple >> 3* 6) & 0x3f];
      base64_buf[m++] = base64[(triple >> 2* 6) & 0x3f];
      base64_buf[m++] = base64[(triple >> 1* 6) & 0x3f];
      base64_buf[m++] = base64[(triple >> 0* 6) & 0x3f];
    }

    for (int l = 0; l < mod_table[userpass_buf_len % 3]; l++)
      base64_buf[encoded_len - 1 - l] = '=';

    debugPrint("%s() LN%d: auth string base64 encoded: %s\n", __func__, __LINE__, base64_buf);
    char *auth = base64_buf;

1738 1739 1740
    int r = snprintf(request_buf,
            req_buf_len,
            req_fmt, url, host, rest_port,
1741 1742 1743 1744 1745
            auth, strlen(sqlstr), sqlstr);
    if (r >= req_buf_len) {
        free(request_buf);
        ERROR_EXIT("ERROR too long request");
    }
1746
    verbosePrint("%s() LN%d: Request:\n%s\n", __func__, __LINE__, request_buf);
1747

1748
    req_str_len = strlen(request_buf);
1749 1750
    sent = 0;
    do {
1751 1752 1753
#ifdef WINDOWS
        bytes = send(sockfd, request_buf + sent, req_str_len - sent, 0);
#else
1754
        bytes = write(sockfd, request_buf + sent, req_str_len - sent);
1755
#endif
1756
        if (bytes < 0)
1757
            ERROR_EXIT("ERROR writing message to socket");
1758 1759 1760
        if (bytes == 0)
            break;
        sent+=bytes;
1761
    } while (sent < req_str_len);
1762

1763 1764
    memset(response_buf, 0, RESP_BUF_LEN);
    resp_len = sizeof(response_buf) - 1;
1765 1766
    received = 0;
    do {
1767 1768 1769
#ifdef WINDOWS
        bytes = recv(sockfd, response_buf + received, resp_len - received, 0);
#else
1770
        bytes = read(sockfd, response_buf + received, resp_len - received);
1771
#endif
1772 1773
        if (bytes < 0) {
            free(request_buf);
1774
            ERROR_EXIT("ERROR reading response from socket");
1775
        }
1776 1777
        if (bytes == 0)
            break;
1778 1779
        received += bytes;
    } while (received < resp_len);
1780

1781 1782
    if (received == resp_len) {
        free(request_buf);
1783
        ERROR_EXIT("ERROR storing complete response from socket");
1784
    }
1785

1786
    response_buf[RESP_BUF_LEN - 1] = '\0';
1787 1788 1789
    printf("Response:\n%s\n", response_buf);

    free(request_buf);
1790 1791 1792 1793
#ifdef WINDOWS
    closesocket(sockfd);
    WSACleanup();
#else
1794
    close(sockfd);
1795
#endif
1796 1797 1798 1799

    return 0;
}

1800
static char* getTagValueFromTagSample(SSuperTable* stbInfo, int tagUsePos) {
1801 1802 1803 1804 1805
  char*  dataBuf = (char*)calloc(TSDB_MAX_SQL_LEN+1, 1);
  if (NULL == dataBuf) {
    printf("calloc failed! size:%d\n", TSDB_MAX_SQL_LEN+1);
    return NULL;
  }
1806

1807
  int    dataLen = 0;
1808 1809 1810
  dataLen += snprintf(dataBuf + dataLen, TSDB_MAX_SQL_LEN - dataLen,
          "(%s)", stbInfo->tagDataBuf + stbInfo->lenOfTagOfOneRow * tagUsePos);

1811 1812 1813
  return dataBuf;
}

1814
static char* generateTagVaulesForStb(SSuperTable* stbInfo) {
1815 1816 1817 1818 1819 1820 1821 1822 1823
  char*  dataBuf = (char*)calloc(TSDB_MAX_SQL_LEN+1, 1);
  if (NULL == dataBuf) {
    printf("calloc failed! size:%d\n", TSDB_MAX_SQL_LEN+1);
    return NULL;
  }

  int    dataLen = 0;
  dataLen += snprintf(dataBuf + dataLen, TSDB_MAX_SQL_LEN - dataLen, "(");
  for (int i = 0; i < stbInfo->tagCount; i++) {
1824 1825
    if ((0 == strncasecmp(stbInfo->tags[i].dataType, "binary", strlen("binary")))
            || (0 == strncasecmp(stbInfo->tags[i].dataType, "nchar", strlen("nchar")))) {
1826
      if (stbInfo->tags[i].dataLen > TSDB_MAX_BINARY_LEN) {
1827 1828
        printf("binary or nchar length overflow, max size:%u\n",
                (uint32_t)TSDB_MAX_BINARY_LEN);
1829 1830 1831
        tmfree(dataBuf);
        return NULL;
      }
1832

1833 1834 1835 1836 1837 1838 1839
      char* buf = (char*)calloc(stbInfo->tags[i].dataLen+1, 1);
      if (NULL == buf) {
        printf("calloc failed! size:%d\n", stbInfo->tags[i].dataLen);
        tmfree(dataBuf);
        return NULL;
      }
      rand_string(buf, stbInfo->tags[i].dataLen);
1840 1841
      dataLen += snprintf(dataBuf + dataLen, TSDB_MAX_SQL_LEN - dataLen,
              "\'%s\', ", buf);
1842
      tmfree(buf);
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874
    } else if (0 == strncasecmp(stbInfo->tags[i].dataType,
                "int", strlen("int"))) {
      dataLen += snprintf(dataBuf + dataLen, TSDB_MAX_SQL_LEN - dataLen,
              "%d, ", rand_int());
    } else if (0 == strncasecmp(stbInfo->tags[i].dataType,
                "bigint", strlen("bigint"))) {
      dataLen += snprintf(dataBuf + dataLen, TSDB_MAX_SQL_LEN - dataLen,
              "%"PRId64", ", rand_bigint());
    }  else if (0 == strncasecmp(stbInfo->tags[i].dataType,
                "float", strlen("float"))) {
      dataLen += snprintf(dataBuf + dataLen, TSDB_MAX_SQL_LEN - dataLen,
              "%f, ", rand_float());
    }  else if (0 == strncasecmp(stbInfo->tags[i].dataType,
                "double", strlen("double"))) {
      dataLen += snprintf(dataBuf + dataLen, TSDB_MAX_SQL_LEN - dataLen,
              "%f, ", rand_double());
    }  else if (0 == strncasecmp(stbInfo->tags[i].dataType,
                "smallint", strlen("smallint"))) {
      dataLen += snprintf(dataBuf + dataLen, TSDB_MAX_SQL_LEN - dataLen,
              "%d, ", rand_smallint());
    }  else if (0 == strncasecmp(stbInfo->tags[i].dataType,
                "tinyint", strlen("tinyint"))) {
      dataLen += snprintf(dataBuf + dataLen, TSDB_MAX_SQL_LEN - dataLen,
              "%d, ", rand_tinyint());
    }  else if (0 == strncasecmp(stbInfo->tags[i].dataType,
                "bool", strlen("bool"))) {
      dataLen += snprintf(dataBuf + dataLen, TSDB_MAX_SQL_LEN - dataLen,
              "%d, ", rand_bool());
    }  else if (0 == strncasecmp(stbInfo->tags[i].dataType,
                "timestamp", strlen("timestamp"))) {
      dataLen += snprintf(dataBuf + dataLen, TSDB_MAX_SQL_LEN - dataLen,
              "%"PRId64", ", rand_bigint());
1875 1876 1877 1878 1879 1880
    }  else {
      printf("No support data type: %s\n", stbInfo->tags[i].dataType);
      tmfree(dataBuf);
      return NULL;
    }
  }
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 1917 1918 1919 1920 1921 1922 1923 1924 1925
  dataLen -= 2;
  dataLen += snprintf(dataBuf + dataLen, TSDB_MAX_SQL_LEN - dataLen, ")");  
  return dataBuf;
}

static int calcRowLen(SSuperTable*  superTbls) {  
  int colIndex;
  int  lenOfOneRow = 0;
  
  for (colIndex = 0; colIndex < superTbls->columnCount; colIndex++) {
    char* dataType = superTbls->columns[colIndex].dataType;
    
    if (strcasecmp(dataType, "BINARY") == 0) {
      lenOfOneRow += superTbls->columns[colIndex].dataLen + 3;
    } else if (strcasecmp(dataType, "NCHAR") == 0) {
      lenOfOneRow += superTbls->columns[colIndex].dataLen + 3;
    } else if (strcasecmp(dataType, "INT") == 0)  {
      lenOfOneRow += 11;
    } else if (strcasecmp(dataType, "BIGINT") == 0)  {
      lenOfOneRow += 21;
    } else if (strcasecmp(dataType, "SMALLINT") == 0)  {
      lenOfOneRow += 6;
    } else if (strcasecmp(dataType, "TINYINT") == 0)  {
      lenOfOneRow += 4;
    } else if (strcasecmp(dataType, "BOOL") == 0)  {
      lenOfOneRow += 6;
    } else if (strcasecmp(dataType, "FLOAT") == 0) {
      lenOfOneRow += 22;
    } else if (strcasecmp(dataType, "DOUBLE") == 0) { 
      lenOfOneRow += 42;
    }  else if (strcasecmp(dataType, "TIMESTAMP") == 0) { 
      lenOfOneRow += 21;
    } else {
      printf("get error data type : %s\n", dataType);
      exit(-1);
    }
  }

  superTbls->lenOfOneRow = lenOfOneRow + 20; // timestamp

  int tagIndex;
  int lenOfTagOfOneRow = 0;
  for (tagIndex = 0; tagIndex < superTbls->tagCount; tagIndex++) {
    char* dataType = superTbls->tags[tagIndex].dataType;
1926

1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
    if (strcasecmp(dataType, "BINARY") == 0) {
      lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 3;
    } else if (strcasecmp(dataType, "NCHAR") == 0) {
      lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 3;
    } else if (strcasecmp(dataType, "INT") == 0)  {
      lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 11;
    } else if (strcasecmp(dataType, "BIGINT") == 0)  {
      lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 21;
    } else if (strcasecmp(dataType, "SMALLINT") == 0)  {
      lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 6;
    } else if (strcasecmp(dataType, "TINYINT") == 0)  {
      lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 4;
    } else if (strcasecmp(dataType, "BOOL") == 0)  {
      lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 6;
    } else if (strcasecmp(dataType, "FLOAT") == 0) {
      lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 22;
    } else if (strcasecmp(dataType, "DOUBLE") == 0) { 
      lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 42;
    } else {
      printf("get error tag type : %s\n", dataType);
      exit(-1);
    }
  }

  superTbls->lenOfTagOfOneRow = lenOfTagOfOneRow;
    
  return 0;
}


1957 1958 1959 1960
static int getChildNameOfSuperTableWithLimitAndOffset(TAOS * taos,
        char* dbName, char* sTblName, char** childTblNameOfSuperTbl,
        int* childTblCountOfSuperTbl, int limit, int offset) {

1961
  char command[BUFFER_SIZE] = "\0";
1962 1963
  char limitBuf[100] = "\0";

1964 1965 1966 1967
  TAOS_RES * res;  
  TAOS_ROW row = NULL;

  char* childTblName = *childTblNameOfSuperTbl;
1968 1969 1970 1971 1972

  if (offset >= 0) {
    snprintf(limitBuf, 100, " limit %d offset %d", limit, offset);
  }

1973
  //get all child table name use cmd: select tbname from superTblName;  
1974 1975
  snprintf(command, BUFFER_SIZE, "select tbname from %s.%s %s", dbName, sTblName, limitBuf);

1976 1977 1978 1979 1980 1981 1982 1983 1984
  res = taos_query(taos, command);  
  int32_t code = taos_errno(res);
  if (code != 0) {
    printf("failed to run command %s\n", command);
    taos_free_result(res);
    taos_close(taos);
    exit(-1);
  }

1985
  int childTblCount = (limit < 0)?10000:limit;
1986 1987 1988 1989 1990
  int count = 0;
  childTblName = (char*)calloc(1, childTblCount * TSDB_TABLE_NAME_LEN);
  char* pTblName = childTblName;
  while ((row = taos_fetch_row(res)) != NULL) {
    int32_t* len = taos_fetch_lengths(res);
1991
    tstrncpy(pTblName, (char *)row[0], len[0]+1);
1992 1993 1994 1995 1996 1997 1998
    //printf("==== sub table name: %s\n", pTblName);
    count++;
    if (count >= childTblCount - 1) {
      char *tmp = realloc(childTblName, (size_t)childTblCount*1.5*TSDB_TABLE_NAME_LEN+1);
      if (tmp != NULL) {
        childTblName = tmp;
        childTblCount = (int)(childTblCount*1.5);
1999 2000
        memset(childTblName + count*TSDB_TABLE_NAME_LEN, 0,
                (size_t)((childTblCount-count)*TSDB_TABLE_NAME_LEN));
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
      } else {
        // exit, if allocate more memory failed
        printf("realloc fail for save child table name of %s.%s\n", dbName, sTblName);
        tmfree(childTblName);
        taos_free_result(res);
        taos_close(taos);
        exit(-1);
      }
    }
    pTblName = childTblName + count * TSDB_TABLE_NAME_LEN;    
  }
2012

2013 2014 2015 2016 2017 2018 2019
  *childTblCountOfSuperTbl = count;
  *childTblNameOfSuperTbl  = childTblName;

  taos_free_result(res);
  return 0;
}

2020 2021
static int getAllChildNameOfSuperTable(TAOS * taos, char* dbName,
        char* sTblName, char** childTblNameOfSuperTbl,
2022
        int* childTblCountOfSuperTbl) {
2023 2024 2025 2026 2027 2028

    return getChildNameOfSuperTableWithLimitAndOffset(taos, dbName, sTblName,
            childTblNameOfSuperTbl, childTblCountOfSuperTbl,
            -1, -1);
}

2029 2030
static int getSuperTableFromServer(TAOS * taos, char* dbName,
        SSuperTable*  superTbls) {
2031 2032 2033 2034
  char command[BUFFER_SIZE] = "\0";
  TAOS_RES * res;  
  TAOS_ROW row = NULL;
  int count = 0;
2035

2036
  //get schema use cmd: describe superTblName;
2037
  snprintf(command, BUFFER_SIZE, "describe %s.%s", dbName, superTbls->sTblName);
2038
  res = taos_query(taos, command);
2039 2040 2041
  int32_t code = taos_errno(res);
  if (code != 0) {
    printf("failed to run command %s\n", command);
2042
    taos_free_result(res);
2043 2044 2045 2046 2047 2048 2049 2050 2051 2052
    return -1;
  }

  int tagIndex = 0;
  int columnIndex = 0;
  TAOS_FIELD *fields = taos_fetch_fields(res);
  while ((row = taos_fetch_row(res)) != NULL) {
    if (0 == count) {
      count++;
      continue;
2053
    }
2054 2055

    if (strcmp((char *)row[TSDB_DESCRIBE_METRIC_NOTE_INDEX], "TAG") == 0) {
2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
      tstrncpy(superTbls->tags[tagIndex].field,
              (char *)row[TSDB_DESCRIBE_METRIC_FIELD_INDEX],
              fields[TSDB_DESCRIBE_METRIC_FIELD_INDEX].bytes);
      tstrncpy(superTbls->tags[tagIndex].dataType,
              (char *)row[TSDB_DESCRIBE_METRIC_TYPE_INDEX],
              fields[TSDB_DESCRIBE_METRIC_TYPE_INDEX].bytes);
      superTbls->tags[tagIndex].dataLen =
          *((int *)row[TSDB_DESCRIBE_METRIC_LENGTH_INDEX]);
      tstrncpy(superTbls->tags[tagIndex].note,
              (char *)row[TSDB_DESCRIBE_METRIC_NOTE_INDEX],
              fields[TSDB_DESCRIBE_METRIC_NOTE_INDEX].bytes);
2067
      tagIndex++;
2068
    } else {
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079
      tstrncpy(superTbls->columns[columnIndex].field,
              (char *)row[TSDB_DESCRIBE_METRIC_FIELD_INDEX],
              fields[TSDB_DESCRIBE_METRIC_FIELD_INDEX].bytes);
      tstrncpy(superTbls->columns[columnIndex].dataType,
              (char *)row[TSDB_DESCRIBE_METRIC_TYPE_INDEX],
              fields[TSDB_DESCRIBE_METRIC_TYPE_INDEX].bytes);
      superTbls->columns[columnIndex].dataLen =
          *((int *)row[TSDB_DESCRIBE_METRIC_LENGTH_INDEX]);
      tstrncpy(superTbls->columns[columnIndex].note,
              (char *)row[TSDB_DESCRIBE_METRIC_NOTE_INDEX],
              fields[TSDB_DESCRIBE_METRIC_NOTE_INDEX].bytes);
2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092
      columnIndex++;
    }
    count++;
  }

  superTbls->columnCount = columnIndex;
  superTbls->tagCount    = tagIndex;
  taos_free_result(res);

  calcRowLen(superTbls);

  if (TBL_ALREADY_EXISTS == superTbls->childTblExists) {
    //get all child table name use cmd: select tbname from superTblName;  
2093
    getAllChildNameOfSuperTable(taos, dbName,
2094 2095 2096
            superTbls->sTblName,
            &superTbls->childTblName,
            &superTbls->childTblCount);
2097 2098 2099 2100
  }
  return 0;
}

2101
static int createSuperTable(TAOS * taos, char* dbName, SSuperTable*  superTbls, bool use_metric) {
2102
  char command[BUFFER_SIZE] = "\0";
2103

2104 2105 2106 2107 2108 2109 2110
  char cols[STRING_LEN] = "\0";
  int colIndex;
  int len = 0;

  int  lenOfOneRow = 0;
  for (colIndex = 0; colIndex < superTbls->columnCount; colIndex++) {
    char* dataType = superTbls->columns[colIndex].dataType;
2111
 
2112
    if (strcasecmp(dataType, "BINARY") == 0) {
2113 2114 2115
      len += snprintf(cols + len, STRING_LEN - len,
          ", col%d %s(%d)", colIndex, "BINARY",
          superTbls->columns[colIndex].dataLen);
2116 2117
      lenOfOneRow += superTbls->columns[colIndex].dataLen + 3;
    } else if (strcasecmp(dataType, "NCHAR") == 0) {
2118 2119 2120
      len += snprintf(cols + len, STRING_LEN - len,
          ", col%d %s(%d)", colIndex, "NCHAR",
          superTbls->columns[colIndex].dataLen);
2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139
      lenOfOneRow += superTbls->columns[colIndex].dataLen + 3;
    } else if (strcasecmp(dataType, "INT") == 0)  {
      len += snprintf(cols + len, STRING_LEN - len, ", col%d %s", colIndex, "INT");
      lenOfOneRow += 11;
    } else if (strcasecmp(dataType, "BIGINT") == 0)  {
      len += snprintf(cols + len, STRING_LEN - len, ", col%d %s", colIndex, "BIGINT");
      lenOfOneRow += 21;
    } else if (strcasecmp(dataType, "SMALLINT") == 0)  {
      len += snprintf(cols + len, STRING_LEN - len, ", col%d %s", colIndex, "SMALLINT");
      lenOfOneRow += 6;
    } else if (strcasecmp(dataType, "TINYINT") == 0)  {
      len += snprintf(cols + len, STRING_LEN - len, ", col%d %s", colIndex, "TINYINT");
      lenOfOneRow += 4;
    } else if (strcasecmp(dataType, "BOOL") == 0)  {
      len += snprintf(cols + len, STRING_LEN - len, ", col%d %s", colIndex, "BOOL");
      lenOfOneRow += 6;
    } else if (strcasecmp(dataType, "FLOAT") == 0) {
      len += snprintf(cols + len, STRING_LEN - len, ", col%d %s", colIndex, "FLOAT");
      lenOfOneRow += 22;
2140
    } else if (strcasecmp(dataType, "DOUBLE") == 0) {
2141 2142
      len += snprintf(cols + len, STRING_LEN - len, ", col%d %s", colIndex, "DOUBLE");
      lenOfOneRow += 42;
2143
    }  else if (strcasecmp(dataType, "TIMESTAMP") == 0) {
2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
      len += snprintf(cols + len, STRING_LEN - len, ", col%d %s", colIndex, "TIMESTAMP");
      lenOfOneRow += 21;
    } else {
      taos_close(taos);
      printf("config error data type : %s\n", dataType);
      exit(-1);
    }
  }

  superTbls->lenOfOneRow = lenOfOneRow + 20; // timestamp
  //printf("%s.%s column count:%d, column length:%d\n\n", g_Dbs.db[i].dbName, g_Dbs.db[i].superTbls[j].sTblName, g_Dbs.db[i].superTbls[j].columnCount, lenOfOneRow);

  // save for creating child table
2157 2158
  superTbls->colsOfCreateChildTable = (char*)calloc(len+20, 1);
  if (NULL == superTbls->colsOfCreateChildTable) {
2159 2160 2161 2162
    printf("Failed when calloc, size:%d", len+1);
    taos_close(taos);
    exit(-1);
  }
2163
  snprintf(superTbls->colsOfCreateChildTable, len+20, "(ts timestamp%s)", cols);
2164
  verbosePrint("%s() LN%d: %s\n", __func__, __LINE__, superTbls->colsOfCreateChildTable);
2165 2166 2167 2168 2169 2170 2171 2172 2173 2174

  if (use_metric) {
    char tags[STRING_LEN] = "\0";
    int tagIndex;
    len = 0;

    int lenOfTagOfOneRow = 0;
    len += snprintf(tags + len, STRING_LEN - len, "(");
    for (tagIndex = 0; tagIndex < superTbls->tagCount; tagIndex++) {
      char* dataType = superTbls->tags[tagIndex].dataType;
2175

2176
      if (strcasecmp(dataType, "BINARY") == 0) {
2177 2178
        len += snprintf(tags + len, STRING_LEN - len, "t%d %s(%d), ", tagIndex,
                "BINARY", superTbls->tags[tagIndex].dataLen);
2179 2180
        lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 3;
      } else if (strcasecmp(dataType, "NCHAR") == 0) {
2181 2182
        len += snprintf(tags + len, STRING_LEN - len, "t%d %s(%d), ", tagIndex,
                "NCHAR", superTbls->tags[tagIndex].dataLen);
2183 2184
        lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 3;
      } else if (strcasecmp(dataType, "INT") == 0)  {
2185 2186
        len += snprintf(tags + len, STRING_LEN - len, "t%d %s, ", tagIndex,
                "INT");
2187 2188
        lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 11;
      } else if (strcasecmp(dataType, "BIGINT") == 0)  {
2189 2190
        len += snprintf(tags + len, STRING_LEN - len, "t%d %s, ", tagIndex,
                "BIGINT");
2191 2192
        lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 21;
      } else if (strcasecmp(dataType, "SMALLINT") == 0)  {
2193 2194
        len += snprintf(tags + len, STRING_LEN - len, "t%d %s, ", tagIndex,
                "SMALLINT");
2195 2196
        lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 6;
      } else if (strcasecmp(dataType, "TINYINT") == 0)  {
2197 2198
        len += snprintf(tags + len, STRING_LEN - len, "t%d %s, ", tagIndex,
                "TINYINT");
2199 2200
        lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 4;
      } else if (strcasecmp(dataType, "BOOL") == 0)  {
2201 2202
        len += snprintf(tags + len, STRING_LEN - len, "t%d %s, ", tagIndex,
                "BOOL");
2203 2204
        lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 6;
      } else if (strcasecmp(dataType, "FLOAT") == 0) {
2205 2206
        len += snprintf(tags + len, STRING_LEN - len, "t%d %s, ", tagIndex,
                "FLOAT");
2207 2208
        lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 22;
      } else if (strcasecmp(dataType, "DOUBLE") == 0) { 
2209 2210
        len += snprintf(tags + len, STRING_LEN - len, "t%d %s, ", tagIndex,
                "DOUBLE");
2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
        lenOfTagOfOneRow += superTbls->tags[tagIndex].dataLen + 42;
      } else {
        taos_close(taos);
        printf("config error tag type : %s\n", dataType);
        exit(-1);
      }
    }
    len -= 2;
    len += snprintf(tags + len, STRING_LEN - len, ")");

    superTbls->lenOfTagOfOneRow = lenOfTagOfOneRow;
2222 2223 2224 2225

    snprintf(command, BUFFER_SIZE,
            "create table if not exists %s.%s (ts timestamp%s) tags %s",
            dbName, superTbls->sTblName, cols, tags);
2226
    verbosePrint("%s() LN%d: %s\n", __func__, __LINE__, command);
2227

2228
    if (0 != queryDbExec(taos, command, NO_INSERT_TYPE)) {
2229 2230
        fprintf(stderr, "create supertable %s failed!\n\n",
                superTbls->sTblName);
2231
        return -1;
2232
    }
2233
    debugPrint("create supertable %s success!\n\n", superTbls->sTblName);
2234 2235 2236 2237
  }
  return 0;
}

2238
static int createDatabases() {
2239 2240 2241 2242 2243
  TAOS * taos = NULL;
  int    ret = 0;
  taos = taos_connect(g_Dbs.host, g_Dbs.user, g_Dbs.password, NULL, g_Dbs.port);
  if (taos == NULL) {
    fprintf(stderr, "Failed to connect to TDengine, reason:%s\n", taos_errstr(NULL));
2244
    return -1;
2245 2246 2247 2248 2249 2250
  }
  char command[BUFFER_SIZE] = "\0";

  for (int i = 0; i < g_Dbs.dbCount; i++) {   
    if (g_Dbs.db[i].drop) {
      sprintf(command, "drop database if exists %s;", g_Dbs.db[i].dbName);
2251
      verbosePrint("%s() %d command: %s\n", __func__, __LINE__, command);
2252 2253 2254 2255 2256
      if (0 != queryDbExec(taos, command, NO_INSERT_TYPE)) {
        taos_close(taos);
        return -1;
      }
    }
2257

2258
    int dataLen = 0;
2259 2260
    dataLen += snprintf(command + dataLen, 
        BUFFER_SIZE - dataLen, "create database if not exists %s ", g_Dbs.db[i].dbName);
2261 2262

    if (g_Dbs.db[i].dbCfg.blocks > 0) {
2263 2264
      dataLen += snprintf(command + dataLen,
          BUFFER_SIZE - dataLen, "blocks %d ", g_Dbs.db[i].dbCfg.blocks);
2265 2266
    }
    if (g_Dbs.db[i].dbCfg.cache > 0) {
2267 2268
      dataLen += snprintf(command + dataLen,
          BUFFER_SIZE - dataLen, "cache %d ", g_Dbs.db[i].dbCfg.cache);
2269 2270
    }
    if (g_Dbs.db[i].dbCfg.days > 0) {
2271 2272
      dataLen += snprintf(command + dataLen,
          BUFFER_SIZE - dataLen, "days %d ", g_Dbs.db[i].dbCfg.days);
2273 2274
    }
    if (g_Dbs.db[i].dbCfg.keep > 0) {
2275 2276
      dataLen += snprintf(command + dataLen,
          BUFFER_SIZE - dataLen, "keep %d ", g_Dbs.db[i].dbCfg.keep);
2277 2278
    }
    if (g_Dbs.db[i].dbCfg.replica > 0) {
2279 2280
      dataLen += snprintf(command + dataLen,
          BUFFER_SIZE - dataLen, "replica %d ", g_Dbs.db[i].dbCfg.replica);
2281 2282
    }
    if (g_Dbs.db[i].dbCfg.update > 0) {
2283 2284
      dataLen += snprintf(command + dataLen,
          BUFFER_SIZE - dataLen, "update %d ", g_Dbs.db[i].dbCfg.update);
2285 2286
    }
    //if (g_Dbs.db[i].dbCfg.maxtablesPerVnode > 0) {
2287 2288
    //  dataLen += snprintf(command + dataLen,
    //  BUFFER_SIZE - dataLen, "tables %d ", g_Dbs.db[i].dbCfg.maxtablesPerVnode);
2289 2290
    //}
    if (g_Dbs.db[i].dbCfg.minRows > 0) {
2291 2292
      dataLen += snprintf(command + dataLen,
          BUFFER_SIZE - dataLen, "minrows %d ", g_Dbs.db[i].dbCfg.minRows);
2293 2294
    }
    if (g_Dbs.db[i].dbCfg.maxRows > 0) {
2295 2296
      dataLen += snprintf(command + dataLen,
          BUFFER_SIZE - dataLen, "maxrows %d ", g_Dbs.db[i].dbCfg.maxRows);
2297 2298
    }
    if (g_Dbs.db[i].dbCfg.comp > 0) {
2299 2300
      dataLen += snprintf(command + dataLen,
          BUFFER_SIZE - dataLen, "comp %d ", g_Dbs.db[i].dbCfg.comp);
2301 2302
    }
    if (g_Dbs.db[i].dbCfg.walLevel > 0) {
2303 2304
      dataLen += snprintf(command + dataLen,
          BUFFER_SIZE - dataLen, "wal %d ", g_Dbs.db[i].dbCfg.walLevel);
2305
    }
2306
    if (g_Dbs.db[i].dbCfg.cacheLast > 0) {
2307 2308
      dataLen += snprintf(command + dataLen,
          BUFFER_SIZE - dataLen, "cachelast %d ", g_Dbs.db[i].dbCfg.cacheLast);
2309
    }
2310 2311 2312
    if (g_Dbs.db[i].dbCfg.fsync > 0) {
      dataLen += snprintf(command + dataLen, BUFFER_SIZE - dataLen, "fsync %d ", g_Dbs.db[i].dbCfg.fsync);
    }
2313 2314 2315 2316
    if ((0 == strncasecmp(g_Dbs.db[i].dbCfg.precision, "ms", 2))
            || (0 == strncasecmp(g_Dbs.db[i].dbCfg.precision, "us", 2))) {
      dataLen += snprintf(command + dataLen, BUFFER_SIZE - dataLen,
              "precision \'%s\';", g_Dbs.db[i].dbCfg.precision);
2317
    }
2318

2319
    debugPrint("%s() %d command: %s\n", __func__, __LINE__, command);
2320 2321
    if (0 != queryDbExec(taos, command, NO_INSERT_TYPE)) {
      taos_close(taos);
2322
      fprintf(stderr, "\ncreate database %s failed!\n\n", g_Dbs.db[i].dbName);
2323 2324 2325 2326
      return -1;
    }
    printf("\ncreate database %s success!\n\n", g_Dbs.db[i].dbName);

2327
    debugPrint("%s() %d supertbl count:%d\n", __func__, __LINE__, g_Dbs.db[i].superTblCount);
2328 2329 2330
    for (int j = 0; j < g_Dbs.db[i].superTblCount; j++) {
      // describe super table, if exists
      sprintf(command, "describe %s.%s;", g_Dbs.db[i].dbName, g_Dbs.db[i].superTbls[j].sTblName);
2331
      verbosePrint("%s() %d command: %s\n", __func__, __LINE__, command);
2332 2333 2334 2335 2336 2337 2338 2339 2340
      if (0 != queryDbExec(taos, command, NO_INSERT_TYPE)) {
        g_Dbs.db[i].superTbls[j].superTblExists = TBL_NO_EXISTS;
        ret = createSuperTable(taos, g_Dbs.db[i].dbName, &g_Dbs.db[i].superTbls[j], g_Dbs.use_metric);
      } else {      
        g_Dbs.db[i].superTbls[j].superTblExists = TBL_ALREADY_EXISTS;
        ret = getSuperTableFromServer(taos, g_Dbs.db[i].dbName, &g_Dbs.db[i].superTbls[j]);
      }

      if (0 != ret) {
2341
        printf("\ncreate super table %d failed!\n\n", j);
2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
        taos_close(taos);
        return -1;
      }
    }    
  }

  taos_close(taos);
  return 0;
}

2352
static void* createTable(void *sarg) 
2353 2354 2355 2356 2357 2358
{  
  threadInfo *winfo = (threadInfo *)sarg; 
  SSuperTable* superTblInfo = winfo->superTblInfo;

  int64_t  lastPrintTime = taosGetTimestampMs();

2359 2360 2361 2362 2363 2364
  int buff_len;
  if (superTblInfo)
    buff_len = superTblInfo->maxSqlLen;
  else
    buff_len = BUFFER_SIZE;

2365
  char *buffer = calloc(buff_len, 1);
2366 2367 2368 2369
  if (buffer == NULL) {
    fprintf(stderr, "Memory allocated failed!");
    exit(-1);
  }
2370 2371 2372 2373 2374 2375

  int len = 0;
  int batchNum = 0;
  //printf("Creating table from %d to %d\n", winfo->start_table_id, winfo->end_table_id);
  for (int i = winfo->start_table_id; i <= winfo->end_table_id; i++) {
    if (0 == g_Dbs.use_metric) {
2376
      snprintf(buffer, buff_len, 
2377 2378
              "create table if not exists %s.%s%d %s;",
              winfo->db_name,
2379 2380
              g_args.tb_prefix, i,
              winfo->cols);
2381 2382 2383
    } else {
      if (0 == len) {  
        batchNum = 0;
2384
        memset(buffer, 0, buff_len);
2385
        len += snprintf(buffer + len,
2386
                buff_len - len, "create table ");
2387
      }
2388

2389 2390 2391 2392
      char* tagsValBuf = NULL;
      if (0 == superTblInfo->tagSource) {
        tagsValBuf = generateTagVaulesForStb(superTblInfo);
      } else {
2393 2394 2395
        tagsValBuf = getTagValueFromTagSample(
                superTblInfo,
                i % superTblInfo->tagSampleCount);
2396 2397 2398 2399 2400 2401
      }
      if (NULL == tagsValBuf) {
        free(buffer);
        return NULL;
      }
      
2402 2403 2404 2405 2406 2407
      len += snprintf(buffer + len,
              superTblInfo->maxSqlLen - len,
              "if not exists %s.%s%d using %s.%s tags %s ",
              winfo->db_name, superTblInfo->childTblPrefix,
              i, winfo->db_name,
              superTblInfo->sTblName, tagsValBuf);
2408 2409 2410
      free(tagsValBuf);
      batchNum++;

2411 2412 2413
      if ((batchNum < superTblInfo->batchCreateTableNum)
              && ((superTblInfo->maxSqlLen - len) 
                  >= (superTblInfo->lenOfTagOfOneRow + 256))) {
2414 2415 2416 2417 2418
        continue;
      }
    }

    len = 0;
2419
    verbosePrint("%s() LN%d %s\n", __func__, __LINE__, buffer);
2420
    if (0 != queryDbExec(winfo->taos, buffer, NO_INSERT_TYPE)){
2421
      fprintf(stderr, "queryDbExec() failed. buffer:\n%s\n", buffer);
2422 2423 2424 2425 2426 2427
      free(buffer);
      return NULL;
    }

    int64_t  currentPrintTime = taosGetTimestampMs();
    if (currentPrintTime - lastPrintTime > 30*1000) {
2428 2429
      printf("thread[%d] already create %d - %d tables\n",
              winfo->threadID, winfo->start_table_id, i);
2430 2431 2432 2433 2434
      lastPrintTime = currentPrintTime;
    }
  }
  
  if (0 != len) {
2435
    verbosePrint("%s() %d buffer: %s\n", __func__, __LINE__, buffer);
2436 2437 2438
    if (0 != queryDbExec(winfo->taos, buffer, NO_INSERT_TYPE)) {
      fprintf(stderr, "queryDbExec() failed. buffer:\n%s\n", buffer);
    }
2439
  }
2440

2441 2442 2443 2444
  free(buffer);
  return NULL;
}

2445
int startMultiThreadCreateChildTable(
2446
        char* cols, int threads, int startFrom, int ntables,
2447
        char* db_name, SSuperTable* superTblInfo) {
2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
  pthread_t *pids = malloc(threads * sizeof(pthread_t));
  threadInfo *infos = malloc(threads * sizeof(threadInfo));

  if ((NULL == pids) || (NULL == infos)) {
    printf("malloc failed\n");
    exit(-1);
  }

  if (threads < 1) {
    threads = 1;
  }

  int a = ntables / threads;
  if (a < 1) {
    threads = ntables;
    a = 1;
  }

  int b = 0;
  b = ntables % threads;
2468
 
2469
  int last = startFrom;
2470 2471 2472
  for (int i = 0; i < threads; i++) {
    threadInfo *t_info = infos + i;
    t_info->threadID = i;
H
Hui Li 已提交
2473
    tstrncpy(t_info->db_name, db_name, MAX_DB_NAME_SIZE);
2474
    t_info->superTblInfo = superTblInfo;
2475
    verbosePrint("%s() %d db_name: %s\n", __func__, __LINE__, db_name);
2476 2477 2478 2479 2480 2481
    t_info->taos = taos_connect(
            g_Dbs.host,
            g_Dbs.user,
            g_Dbs.password,
            db_name,
            g_Dbs.port);
2482 2483
    if (t_info->taos == NULL) {
      fprintf(stderr, "Failed to connect to TDengine, reason:%s\n", taos_errstr(NULL));
2484 2485
      free(pids);
      free(infos);  
2486 2487
      return -1;
    }
H
hzcheng 已提交
2488 2489 2490
    t_info->start_table_id = last;
    t_info->end_table_id = i < b ? last + a : last + a - 1;
    last = t_info->end_table_id + 1;
2491 2492
    t_info->use_metric = 1;
    t_info->cols = cols;
2493
    t_info->minDelay = INT16_MAX;
2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
    pthread_create(pids + i, NULL, createTable, t_info);
  }
  
  for (int i = 0; i < threads; i++) {
    pthread_join(pids[i], NULL);
  }

  for (int i = 0; i < threads; i++) {
    threadInfo *t_info = infos + i;
    taos_close(t_info->taos);
  }

  free(pids);
  free(infos);  
2508 2509

  return 0;
2510 2511 2512
}


2513 2514 2515 2516
static void createChildTables() {
    char tblColsBuf[MAX_SQL_SIZE];
    int len;

2517
  for (int i = 0; i < g_Dbs.dbCount; i++) {
2518
    if (g_Dbs.db[i].superTblCount > 0) {
2519
        // with super table
2520 2521
      for (int j = 0; j < g_Dbs.db[i].superTblCount; j++) {
        if ((AUTO_CREATE_SUBTBL == g_Dbs.db[i].superTbls[j].autoCreateTable)
2522
              || (TBL_ALREADY_EXISTS == g_Dbs.db[i].superTbls[j].childTblExists)) {
2523 2524 2525
          continue;
        }

2526
        verbosePrint("%s() LN%d: %s\n", __func__, __LINE__,
2527
                g_Dbs.db[i].superTbls[j].colsOfCreateChildTable);
2528 2529
        int startFrom = 0;
        g_totalChildTables += g_Dbs.db[i].superTbls[j].childTblCount;
2530 2531 2532

        verbosePrint("%s() LN%d: create %d child tables from %d\n", __func__, __LINE__,
              g_totalChildTables, startFrom);  
2533
        startMultiThreadCreateChildTable(
2534
              g_Dbs.db[i].superTbls[j].colsOfCreateChildTable,
2535
              g_Dbs.threadCountByCreateTbl,
2536 2537
              startFrom,
              g_totalChildTables,
2538
              g_Dbs.db[i].dbName, &(g_Dbs.db[i].superTbls[j]));
2539 2540
      }
    } else {
2541 2542
        // normal table
        len = snprintf(tblColsBuf, MAX_SQL_SIZE, "(TS TIMESTAMP");
2543 2544 2545
        int j = 0;
        while (g_args.datatype[j]) {
            if ((strncasecmp(g_args.datatype[j], "BINARY", strlen("BINARY")) == 0)
2546 2547 2548 2549
                    || (strncasecmp(g_args.datatype[j],
                        "NCHAR", strlen("NCHAR")) == 0)) {
                len = snprintf(tblColsBuf + len, MAX_SQL_SIZE,
                        ", COL%d %s(60)", j, g_args.datatype[j]);
2550
            } else {
2551 2552
                len = snprintf(tblColsBuf + len, MAX_SQL_SIZE,
                        ", COL%d %s", j, g_args.datatype[j]);
2553 2554
            }
            len = strlen(tblColsBuf);
2555
            j++;
2556 2557
        }

2558
        len = snprintf(tblColsBuf + len, MAX_SQL_SIZE - len, ")");
2559

2560 2561
        verbosePrint("%s() LN%d: dbName: %s num of tb: %d schema: %s\n",
                __func__, __LINE__,
2562
                g_Dbs.db[i].dbName, g_args.num_of_tables, tblColsBuf);
2563
        startMultiThreadCreateChildTable(
2564
              tblColsBuf,
2565
              g_Dbs.threadCountByCreateTbl,
2566
              0,
2567
              g_args.num_of_tables,
2568 2569 2570
              g_Dbs.db[i].dbName,
              NULL);
    }
2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
  }
}

/*
  Read 10000 lines at most. If more than 10000 lines, continue to read after using
*/
int readTagFromCsvFileToMem(SSuperTable  * superTblInfo) {
  size_t  n = 0;
  ssize_t readLen = 0;
  char *  line = NULL;
2581

2582 2583
  FILE *fp = fopen(superTblInfo->tagsFile, "r");
  if (fp == NULL) {
2584 2585
    printf("Failed to open tags file: %s, reason:%s\n",
            superTblInfo->tagsFile, strerror(errno));
2586 2587 2588 2589 2590 2591 2592
    return -1;
  }

  if (superTblInfo->tagDataBuf) {
    free(superTblInfo->tagDataBuf);
    superTblInfo->tagDataBuf = NULL;
  }
2593

2594 2595 2596 2597 2598 2599 2600 2601 2602
  int tagCount = 10000;
  int count = 0;
  char* tagDataBuf = calloc(1, superTblInfo->lenOfTagOfOneRow * tagCount);
  if (tagDataBuf == NULL) {
    printf("Failed to calloc, reason:%s\n", strerror(errno));
    fclose(fp);
    return -1;
  }

2603
  while ((readLen = tgetline(&line, &n, fp)) != -1) {
2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
    if (('\r' == line[readLen - 1]) || ('\n' == line[readLen - 1])) {
      line[--readLen] = 0;
    }

    if (readLen == 0) {
      continue;
    }

    memcpy(tagDataBuf + count * superTblInfo->lenOfTagOfOneRow, line, readLen);
    count++;

    if (count >= tagCount - 1) {
2616 2617
      char *tmp = realloc(tagDataBuf,
              (size_t)tagCount*1.5*superTblInfo->lenOfTagOfOneRow);
2618 2619 2620
      if (tmp != NULL) {
        tagDataBuf = tmp;
        tagCount = (int)(tagCount*1.5);
2621 2622
        memset(tagDataBuf + count*superTblInfo->lenOfTagOfOneRow,
                0, (size_t)((tagCount-count)*superTblInfo->lenOfTagOfOneRow));
2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650
      } else {
        // exit, if allocate more memory failed
        printf("realloc fail for save tag val from %s\n", superTblInfo->tagsFile);
        tmfree(tagDataBuf);
        free(line);
        fclose(fp);
        return -1;
      }
    }
  }

  superTblInfo->tagDataBuf = tagDataBuf;
  superTblInfo->tagSampleCount = count;

  free(line);
  fclose(fp);
  return 0;
}

int readSampleFromJsonFileToMem(SSuperTable  * superTblInfo) {
  // TODO
  return 0;
}


/*
  Read 10000 lines at most. If more than 10000 lines, continue to read after using
*/
2651 2652
static int readSampleFromCsvFileToMem(
        SSuperTable* superTblInfo) {
2653 2654 2655 2656
  size_t  n = 0;
  ssize_t readLen = 0;
  char *  line = NULL;
  int getRows = 0;
2657 2658 2659
 
  FILE*  fp = fopen(superTblInfo->sampleFile, "r");
  if (fp == NULL) {
2660
      fprintf(stderr, "Failed to open sample file: %s, reason:%s\n",
2661 2662 2663
              superTblInfo->sampleFile, strerror(errno));
      return -1;
  }
2664

2665 2666
  memset(superTblInfo->sampleDataBuf, 0,
          MAX_SAMPLES_ONCE_FROM_FILE * superTblInfo->lenOfOneRow);
2667
  while (1) {
2668
    readLen = tgetline(&line, &n, fp);
2669 2670
    if (-1 == readLen) {
      if(0 != fseek(fp, 0, SEEK_SET)) {
2671
        fprintf(stderr, "Failed to fseek file: %s, reason:%s\n",
2672
                superTblInfo->sampleFile, strerror(errno));
2673
        fclose(fp);
2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
        return -1;
      }
      continue;
    }
  
    if (('\r' == line[readLen - 1]) || ('\n' == line[readLen - 1])) {
      line[--readLen] = 0;
    }

    if (readLen == 0) {
      continue;
    }

    if (readLen > superTblInfo->lenOfOneRow) {
2688 2689
      printf("sample row len[%d] overflow define schema len[%d], so discard this row\n",
              (int32_t)readLen, superTblInfo->lenOfOneRow);
2690 2691 2692
      continue;
    }

2693 2694
    memcpy(superTblInfo->sampleDataBuf + getRows * superTblInfo->lenOfOneRow,
          line, readLen);
2695 2696 2697 2698 2699 2700 2701
    getRows++;

    if (getRows == MAX_SAMPLES_ONCE_FROM_FILE) {
      break;
    }
  }

2702
  fclose(fp);
2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726
  tmfree(line);
  return 0;
}

/*
void readSampleFromFileToMem(SSuperTable  * supterTblInfo) {
  int ret;
  if (0 == strncasecmp(supterTblInfo->sampleFormat, "csv", 3)) {
    ret = readSampleFromCsvFileToMem(supterTblInfo);
  } else if (0 == strncasecmp(supterTblInfo->sampleFormat, "json", 4)) {
    ret = readSampleFromJsonFileToMem(supterTblInfo);
  }

  if (0 != ret) {
    exit(-1);
  }
}
*/
static bool getColumnAndTagTypeFromInsertJsonFile(cJSON* stbInfo, SSuperTable* superTbls) {  
  bool  ret = false;
  
  // columns 
  cJSON *columns = cJSON_GetObjectItem(stbInfo, "columns");
  if (columns && columns->type != cJSON_Array) {
2727
    printf("ERROR: failed to read json, columns not found\n");
2728 2729 2730 2731 2732 2733 2734 2735 2736
    goto PARSE_OVER;
  } else if (NULL == columns) {
    superTbls->columnCount = 0;
    superTbls->tagCount    = 0;
    return true;
  }
  
  int columnSize = cJSON_GetArraySize(columns);
  if (columnSize > MAX_COLUMN_COUNT) {
2737
    printf("ERROR: failed to read json, column size overflow, max column size is %d\n",
2738
            MAX_COLUMN_COUNT);
2739 2740 2741 2742 2743 2744
    goto PARSE_OVER;
  }

  int count = 1;
  int index = 0;
  StrColumn    columnCase;
2745

2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
  //superTbls->columnCount = columnSize;  
  for (int k = 0; k < columnSize; ++k) {
    cJSON* column = cJSON_GetArrayItem(columns, k);
    if (column == NULL) continue;

    count = 1;
    cJSON* countObj = cJSON_GetObjectItem(column, "count");
    if (countObj && countObj->type == cJSON_Number) {
      count = countObj->valueint;    
    } else if (countObj && countObj->type != cJSON_Number) {
2756
      printf("ERROR: failed to read json, column count not found\n");
2757 2758 2759 2760 2761 2762 2763 2764 2765
      goto PARSE_OVER;
    } else {
      count = 1;
    }

    // column info 
    memset(&columnCase, 0, sizeof(StrColumn));
    cJSON *dataType = cJSON_GetObjectItem(column, "type");
    if (!dataType || dataType->type != cJSON_String || dataType->valuestring == NULL) {
2766
      printf("ERROR: failed to read json, column type not found\n");
2767 2768
      goto PARSE_OVER;
    }
2769 2770
    //tstrncpy(superTbls->columns[k].dataType, dataType->valuestring, MAX_TB_NAME_SIZE);
    tstrncpy(columnCase.dataType, dataType->valuestring, MAX_TB_NAME_SIZE);
2771 2772 2773 2774 2775
            
    cJSON* dataLen = cJSON_GetObjectItem(column, "len");
    if (dataLen && dataLen->type == cJSON_Number) {
      columnCase.dataLen = dataLen->valueint;    
    } else if (dataLen && dataLen->type != cJSON_Number) {
2776
      printf("ERROR: failed to read json, column len not found\n");
2777 2778 2779 2780 2781 2782
      goto PARSE_OVER;
    } else {
      columnCase.dataLen = 8;
    }
    
    for (int n = 0; n < count; ++n) {
2783
      tstrncpy(superTbls->columns[index].dataType, columnCase.dataType, MAX_TB_NAME_SIZE);
2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794
      superTbls->columns[index].dataLen = columnCase.dataLen; 
      index++;
    }
  }  
  superTbls->columnCount = index;  
  
  count = 1;
  index = 0;
  // tags 
  cJSON *tags = cJSON_GetObjectItem(stbInfo, "tags");
  if (!tags || tags->type != cJSON_Array) {
2795
    printf("ERROR: failed to read json, tags not found\n");
2796 2797 2798 2799 2800
    goto PARSE_OVER;
  }
  
  int tagSize = cJSON_GetArraySize(tags);
  if (tagSize > MAX_TAG_COUNT) {
2801
    printf("ERROR: failed to read json, tags size overflow, max tag size is %d\n", MAX_TAG_COUNT);
2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814
    goto PARSE_OVER;
  }
  
  //superTbls->tagCount = tagSize;  
  for (int k = 0; k < tagSize; ++k) {
    cJSON* tag = cJSON_GetArrayItem(tags, k);
    if (tag == NULL) continue;
    
    count = 1;
    cJSON* countObj = cJSON_GetObjectItem(tag, "count");
    if (countObj && countObj->type == cJSON_Number) {
      count = countObj->valueint;    
    } else if (countObj && countObj->type != cJSON_Number) {
2815
      printf("ERROR: failed to read json, column count not found\n");
2816 2817 2818 2819 2820 2821 2822 2823 2824
      goto PARSE_OVER;
    } else {
      count = 1;
    }

    // column info 
    memset(&columnCase, 0, sizeof(StrColumn));
    cJSON *dataType = cJSON_GetObjectItem(tag, "type");
    if (!dataType || dataType->type != cJSON_String || dataType->valuestring == NULL) {
2825
      printf("ERROR: failed to read json, tag type not found\n");
2826 2827
      goto PARSE_OVER;
    }
2828
    tstrncpy(columnCase.dataType, dataType->valuestring, MAX_TB_NAME_SIZE);
2829 2830 2831 2832 2833
            
    cJSON* dataLen = cJSON_GetObjectItem(tag, "len");
    if (dataLen && dataLen->type == cJSON_Number) {
      columnCase.dataLen = dataLen->valueint;    
    } else if (dataLen && dataLen->type != cJSON_Number) {
2834
      printf("ERROR: failed to read json, column len not found\n");
2835 2836 2837 2838 2839 2840
      goto PARSE_OVER;
    } else {
      columnCase.dataLen = 0;
    }  
    
    for (int n = 0; n < count; ++n) {
2841
      tstrncpy(superTbls->tags[index].dataType, columnCase.dataType, MAX_TB_NAME_SIZE);
2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861
      superTbls->tags[index].dataLen = columnCase.dataLen; 
      index++;
    }
  }      
  superTbls->tagCount = index;

  ret = true;

PARSE_OVER:
  //free(content);
  //cJSON_Delete(root);
  //fclose(fp);
  return ret;
}

static bool getMetaFromInsertJsonFile(cJSON* root) {
  bool  ret = false;

  cJSON* cfgdir = cJSON_GetObjectItem(root, "cfgdir");
  if (cfgdir && cfgdir->type == cJSON_String && cfgdir->valuestring != NULL) {
2862
    tstrncpy(g_Dbs.cfgDir, cfgdir->valuestring, MAX_FILE_NAME_LEN);
2863 2864 2865 2866
  }

  cJSON* host = cJSON_GetObjectItem(root, "host");
  if (host && host->type == cJSON_String && host->valuestring != NULL) {
2867
    tstrncpy(g_Dbs.host, host->valuestring, MAX_DB_NAME_SIZE);
2868
  } else if (!host) {
2869
    tstrncpy(g_Dbs.host, "127.0.0.1", MAX_DB_NAME_SIZE);
2870
  } else {
2871
    printf("ERROR: failed to read json, host not found\n");
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883
    goto PARSE_OVER;
  }

  cJSON* port = cJSON_GetObjectItem(root, "port");
  if (port && port->type == cJSON_Number) {
    g_Dbs.port = port->valueint;
  } else if (!port) {
    g_Dbs.port = 6030;
  }

  cJSON* user = cJSON_GetObjectItem(root, "user");
  if (user && user->type == cJSON_String && user->valuestring != NULL) {
2884
    tstrncpy(g_Dbs.user, user->valuestring, MAX_DB_NAME_SIZE);   
2885
  } else if (!user) {
2886
    tstrncpy(g_Dbs.user, "root", MAX_DB_NAME_SIZE);
2887 2888 2889 2890
  }

  cJSON* password = cJSON_GetObjectItem(root, "password");
  if (password && password->type == cJSON_String && password->valuestring != NULL) {
2891
    tstrncpy(g_Dbs.password, password->valuestring, MAX_DB_NAME_SIZE);
2892
  } else if (!password) {
2893
    tstrncpy(g_Dbs.password, "taosdata", MAX_DB_NAME_SIZE);
2894 2895 2896 2897
  }

  cJSON* resultfile = cJSON_GetObjectItem(root, "result_file");
  if (resultfile && resultfile->type == cJSON_String && resultfile->valuestring != NULL) {
2898
    tstrncpy(g_Dbs.resultFile, resultfile->valuestring, MAX_FILE_NAME_LEN);
2899
  } else if (!resultfile) {
2900
    tstrncpy(g_Dbs.resultFile, "./insert_res.txt", MAX_FILE_NAME_LEN);
2901 2902 2903 2904 2905 2906 2907 2908
  }

  cJSON* threads = cJSON_GetObjectItem(root, "thread_count");
  if (threads && threads->type == cJSON_Number) {
    g_Dbs.threadCount = threads->valueint;
  } else if (!threads) {
    g_Dbs.threadCount = 1;
  } else {
2909
    printf("ERROR: failed to read json, threads not found\n");
2910 2911
    goto PARSE_OVER;
  }  
2912
 
2913 2914 2915 2916 2917 2918
  cJSON* threads2 = cJSON_GetObjectItem(root, "thread_count_create_tbl");
  if (threads2 && threads2->type == cJSON_Number) {
    g_Dbs.threadCountByCreateTbl = threads2->valueint;
  } else if (!threads2) {
    g_Dbs.threadCountByCreateTbl = 1;
  } else {
2919
    printf("ERROR: failed to read json, threads2 not found\n");
2920 2921 2922
    goto PARSE_OVER;
  } 

2923 2924 2925 2926
      cJSON* gInsertInterval = cJSON_GetObjectItem(root, "insert_interval");
      if (gInsertInterval && gInsertInterval->type == cJSON_Number) {
        g_args.insert_interval = gInsertInterval->valueint;
      } else if (!gInsertInterval) {
2927
        g_args.insert_interval = 0;
2928
      } else {
2929
        fprintf(stderr, "ERROR: failed to read json, insert_interval input mistake\n");
2930 2931 2932
        goto PARSE_OVER;
      }
 
2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943
      cJSON* maxSqlLen = cJSON_GetObjectItem(root, "max_sql_len");
      if (maxSqlLen && maxSqlLen->type == cJSON_Number) {
        g_args.max_sql_len = maxSqlLen->valueint;
      } else if (!maxSqlLen) {
        g_args.max_sql_len = TSDB_PAYLOAD_SIZE;
      } else {
        fprintf(stderr, "ERROR: failed to read json, max_sql_len input mistake\n");
        goto PARSE_OVER;
      }
 

2944 2945
      cJSON* numRecPerReq = cJSON_GetObjectItem(root, "num_of_records_per_req");
      if (numRecPerReq && numRecPerReq->type == cJSON_Number) {
2946
        g_args.num_of_RPR = numRecPerReq->valueint;
2947
      } else if (!numRecPerReq) {
2948
        g_args.num_of_RPR = 100;
2949
      } else {
2950
        printf("ERROR: failed to read json, num_of_records_per_req not found\n");
2951 2952 2953
        goto PARSE_OVER;
      }
 
2954
  cJSON *answerPrompt = cJSON_GetObjectItem(root, "confirm_parameter_prompt"); // yes, no,
2955 2956 2957
  if (answerPrompt 
          && answerPrompt->type == cJSON_String
          && answerPrompt->valuestring != NULL) {
2958 2959 2960 2961 2962 2963 2964 2965 2966 2967
    if (0 == strncasecmp(answerPrompt->valuestring, "yes", 3)) {
      g_args.answer_yes = false;
    } else if (0 == strncasecmp(answerPrompt->valuestring, "no", 2)) {
      g_args.answer_yes = true;
    } else {
      g_args.answer_yes = false;
    }
  } else if (!answerPrompt) {
    g_args.answer_yes = false;
  } else {
2968
    printf("ERROR: failed to read json, confirm_parameter_prompt not found\n");
2969 2970 2971 2972 2973
    goto PARSE_OVER;
  }  

  cJSON* dbs = cJSON_GetObjectItem(root, "databases");
  if (!dbs || dbs->type != cJSON_Array) {
2974
    printf("ERROR: failed to read json, databases not found\n");
2975 2976 2977 2978 2979
    goto PARSE_OVER;
  }

  int dbSize = cJSON_GetArraySize(dbs);
  if (dbSize > MAX_DB_COUNT) {
2980
    printf("ERROR: failed to read json, databases size overflow, max database is %d\n", MAX_DB_COUNT);
2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991
    goto PARSE_OVER;
  }

  g_Dbs.dbCount = dbSize;
  for (int i = 0; i < dbSize; ++i) {
    cJSON* dbinfos = cJSON_GetArrayItem(dbs, i);
    if (dbinfos == NULL) continue;

    // dbinfo 
    cJSON *dbinfo = cJSON_GetObjectItem(dbinfos, "dbinfo");
    if (!dbinfo || dbinfo->type != cJSON_Object) {
2992
      printf("ERROR: failed to read json, dbinfo not found\n");
2993 2994 2995 2996 2997
      goto PARSE_OVER;
    }
    
    cJSON *dbName = cJSON_GetObjectItem(dbinfo, "name");
    if (!dbName || dbName->type != cJSON_String || dbName->valuestring == NULL) {
2998
      printf("ERROR: failed to read json, db name not found\n");
2999 3000
      goto PARSE_OVER;
    }
3001
    tstrncpy(g_Dbs.db[i].dbName, dbName->valuestring, MAX_DB_NAME_SIZE);
3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012

    cJSON *drop = cJSON_GetObjectItem(dbinfo, "drop");
    if (drop && drop->type == cJSON_String && drop->valuestring != NULL) {
      if (0 == strncasecmp(drop->valuestring, "yes", 3)) {
        g_Dbs.db[i].drop = 1;
      } else {
        g_Dbs.db[i].drop = 0;
      }        
    } else if (!drop) {
      g_Dbs.db[i].drop = 0;
    } else {
3013
      printf("ERROR: failed to read json, drop not found\n");
3014 3015 3016 3017 3018
      goto PARSE_OVER;
    }

    cJSON *precision = cJSON_GetObjectItem(dbinfo, "precision");
    if (precision && precision->type == cJSON_String && precision->valuestring != NULL) {
3019
      tstrncpy(g_Dbs.db[i].dbCfg.precision, precision->valuestring, MAX_DB_NAME_SIZE);
3020
    } else if (!precision) {
3021
      //tstrncpy(g_Dbs.db[i].dbCfg.precision, "ms", MAX_DB_NAME_SIZE);
3022 3023
      memset(g_Dbs.db[i].dbCfg.precision, 0, MAX_DB_NAME_SIZE);
    } else {
3024
      printf("ERROR: failed to read json, precision not found\n");
3025 3026 3027 3028 3029 3030 3031 3032 3033
      goto PARSE_OVER;
    }

    cJSON* update = cJSON_GetObjectItem(dbinfo, "update");
    if (update && update->type == cJSON_Number) {
      g_Dbs.db[i].dbCfg.update = update->valueint;
    } else if (!update) {
      g_Dbs.db[i].dbCfg.update = -1;
    } else {
3034
      printf("ERROR: failed to read json, update not found\n");
3035 3036 3037 3038 3039 3040 3041 3042 3043
      goto PARSE_OVER;
    }

    cJSON* replica = cJSON_GetObjectItem(dbinfo, "replica");
    if (replica && replica->type == cJSON_Number) {
      g_Dbs.db[i].dbCfg.replica = replica->valueint;
    } else if (!replica) {
      g_Dbs.db[i].dbCfg.replica = -1;
    } else {
3044
      printf("ERROR: failed to read json, replica not found\n");
3045 3046 3047 3048 3049 3050 3051 3052 3053
      goto PARSE_OVER;
    }

    cJSON* keep = cJSON_GetObjectItem(dbinfo, "keep");
    if (keep && keep->type == cJSON_Number) {
      g_Dbs.db[i].dbCfg.keep = keep->valueint;
    } else if (!keep) {
      g_Dbs.db[i].dbCfg.keep = -1;
    } else {
3054
     printf("ERROR: failed to read json, keep not found\n");
3055 3056 3057 3058 3059 3060 3061 3062 3063
     goto PARSE_OVER;
    }
    
    cJSON* days = cJSON_GetObjectItem(dbinfo, "days");
    if (days && days->type == cJSON_Number) {
      g_Dbs.db[i].dbCfg.days = days->valueint;
    } else if (!days) {
      g_Dbs.db[i].dbCfg.days = -1;
    } else {
3064
     printf("ERROR: failed to read json, days not found\n");
3065 3066 3067 3068 3069 3070 3071 3072 3073
     goto PARSE_OVER;
    }
    
    cJSON* cache = cJSON_GetObjectItem(dbinfo, "cache");
    if (cache && cache->type == cJSON_Number) {
      g_Dbs.db[i].dbCfg.cache = cache->valueint;
    } else if (!cache) {
      g_Dbs.db[i].dbCfg.cache = -1;
    } else {
3074
     printf("ERROR: failed to read json, cache not found\n");
3075 3076 3077 3078 3079 3080 3081 3082 3083
     goto PARSE_OVER;
    }
        
    cJSON* blocks= cJSON_GetObjectItem(dbinfo, "blocks");
    if (blocks && blocks->type == cJSON_Number) {
      g_Dbs.db[i].dbCfg.blocks = blocks->valueint;
    } else if (!blocks) {
      g_Dbs.db[i].dbCfg.blocks = -1;
    } else {
3084
     printf("ERROR: failed to read json, block not found\n");
3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103
     goto PARSE_OVER;
    }

    //cJSON* maxtablesPerVnode= cJSON_GetObjectItem(dbinfo, "maxtablesPerVnode");
    //if (maxtablesPerVnode && maxtablesPerVnode->type == cJSON_Number) {
    //  g_Dbs.db[i].dbCfg.maxtablesPerVnode = maxtablesPerVnode->valueint;
    //} else if (!maxtablesPerVnode) {
    //  g_Dbs.db[i].dbCfg.maxtablesPerVnode = TSDB_DEFAULT_TABLES;
    //} else {
    // printf("failed to read json, maxtablesPerVnode not found");
    // goto PARSE_OVER;
    //}

    cJSON* minRows= cJSON_GetObjectItem(dbinfo, "minRows");
    if (minRows && minRows->type == cJSON_Number) {
      g_Dbs.db[i].dbCfg.minRows = minRows->valueint;
    } else if (!minRows) {
      g_Dbs.db[i].dbCfg.minRows = -1;
    } else {
3104
     printf("ERROR: failed to read json, minRows not found\n");
3105 3106 3107 3108 3109 3110 3111 3112 3113
     goto PARSE_OVER;
    }

    cJSON* maxRows= cJSON_GetObjectItem(dbinfo, "maxRows");
    if (maxRows && maxRows->type == cJSON_Number) {
      g_Dbs.db[i].dbCfg.maxRows = maxRows->valueint;
    } else if (!maxRows) {
      g_Dbs.db[i].dbCfg.maxRows = -1;
    } else {
3114
     printf("ERROR: failed to read json, maxRows not found\n");
3115 3116 3117 3118 3119 3120 3121 3122 3123
     goto PARSE_OVER;
    }

    cJSON* comp= cJSON_GetObjectItem(dbinfo, "comp");
    if (comp && comp->type == cJSON_Number) {
      g_Dbs.db[i].dbCfg.comp = comp->valueint;
    } else if (!comp) {
      g_Dbs.db[i].dbCfg.comp = -1;
    } else {
3124
     printf("ERROR: failed to read json, comp not found\n");
3125 3126 3127 3128 3129 3130 3131 3132 3133
     goto PARSE_OVER;
    }

    cJSON* walLevel= cJSON_GetObjectItem(dbinfo, "walLevel");
    if (walLevel && walLevel->type == cJSON_Number) {
      g_Dbs.db[i].dbCfg.walLevel = walLevel->valueint;
    } else if (!walLevel) {
      g_Dbs.db[i].dbCfg.walLevel = -1;
    } else {
3134
     printf("ERROR: failed to read json, walLevel not found\n");
3135 3136 3137
     goto PARSE_OVER;
    }

3138 3139 3140 3141 3142 3143
    cJSON* cacheLast= cJSON_GetObjectItem(dbinfo, "cachelast");
    if (cacheLast && cacheLast->type == cJSON_Number) {
      g_Dbs.db[i].dbCfg.cacheLast = cacheLast->valueint;
    } else if (!cacheLast) {
      g_Dbs.db[i].dbCfg.cacheLast = -1;
    } else {
3144
     printf("ERROR: failed to read json, cacheLast not found\n");
3145 3146 3147
     goto PARSE_OVER;
    }

3148 3149 3150 3151 3152 3153
    cJSON* quorum= cJSON_GetObjectItem(dbinfo, "quorum");
    if (quorum && quorum->type == cJSON_Number) {
      g_Dbs.db[i].dbCfg.quorum = quorum->valueint;
    } else if (!quorum) {
      g_Dbs.db[i].dbCfg.quorum = -1;
    } else {
3154
     printf("ERROR: failed to read json, walLevel not found\n");
3155 3156 3157 3158 3159 3160 3161 3162 3163
     goto PARSE_OVER;
    }

    cJSON* fsync= cJSON_GetObjectItem(dbinfo, "fsync");
    if (fsync && fsync->type == cJSON_Number) {
      g_Dbs.db[i].dbCfg.fsync = fsync->valueint;
    } else if (!fsync) {
      g_Dbs.db[i].dbCfg.fsync = -1;
    } else {
3164
     printf("ERROR: failed to read json, fsync not found\n");
3165 3166 3167 3168 3169 3170
     goto PARSE_OVER;
    }    

    // super_talbes 
    cJSON *stables = cJSON_GetObjectItem(dbinfos, "super_tables");
    if (!stables || stables->type != cJSON_Array) {
3171
      printf("ERROR: failed to read json, super_tables not found\n");
3172 3173 3174 3175 3176
      goto PARSE_OVER;
    }    
    
    int stbSize = cJSON_GetArraySize(stables);
    if (stbSize > MAX_SUPER_TABLE_COUNT) {
3177
      printf("ERROR: failed to read json, databases size overflow, max database is %d\n", MAX_SUPER_TABLE_COUNT);
3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188
      goto PARSE_OVER;
    }

    g_Dbs.db[i].superTblCount = stbSize;
    for (int j = 0; j < stbSize; ++j) {
      cJSON* stbInfo = cJSON_GetArrayItem(stables, j);
      if (stbInfo == NULL) continue;
    
      // dbinfo 
      cJSON *stbName = cJSON_GetObjectItem(stbInfo, "name");
      if (!stbName || stbName->type != cJSON_String || stbName->valuestring == NULL) {
3189
        printf("ERROR: failed to read json, stb name not found\n");
3190 3191
        goto PARSE_OVER;
      }
3192
      tstrncpy(g_Dbs.db[i].superTbls[j].sTblName, stbName->valuestring, MAX_TB_NAME_SIZE);
3193 3194 3195
    
      cJSON *prefix = cJSON_GetObjectItem(stbInfo, "childtable_prefix");
      if (!prefix || prefix->type != cJSON_String || prefix->valuestring == NULL) {
3196
        printf("ERROR: failed to read json, childtable_prefix not found\n");
3197 3198
        goto PARSE_OVER;
      }
3199
      tstrncpy(g_Dbs.db[i].superTbls[j].childTblPrefix, prefix->valuestring, MAX_DB_NAME_SIZE);
3200 3201

      cJSON *autoCreateTbl = cJSON_GetObjectItem(stbInfo, "auto_create_table"); // yes, no, null
3202 3203 3204
      if (autoCreateTbl
              && autoCreateTbl->type == cJSON_String
              && autoCreateTbl->valuestring != NULL) {
3205 3206 3207 3208 3209 3210 3211 3212 3213 3214
        if (0 == strncasecmp(autoCreateTbl->valuestring, "yes", 3)) {
          g_Dbs.db[i].superTbls[j].autoCreateTable = AUTO_CREATE_SUBTBL;
        } else if (0 == strncasecmp(autoCreateTbl->valuestring, "no", 2)) {
          g_Dbs.db[i].superTbls[j].autoCreateTable = PRE_CREATE_SUBTBL;
        } else {
          g_Dbs.db[i].superTbls[j].autoCreateTable = PRE_CREATE_SUBTBL;
        }
      } else if (!autoCreateTbl) {
        g_Dbs.db[i].superTbls[j].autoCreateTable = PRE_CREATE_SUBTBL;
      } else {
3215
        printf("ERROR: failed to read json, auto_create_table not found\n");
3216 3217 3218 3219 3220 3221 3222
        goto PARSE_OVER;
      }
      
      cJSON* batchCreateTbl = cJSON_GetObjectItem(stbInfo, "batch_create_tbl_num");
      if (batchCreateTbl && batchCreateTbl->type == cJSON_Number) {
        g_Dbs.db[i].superTbls[j].batchCreateTableNum = batchCreateTbl->valueint;
      } else if (!batchCreateTbl) {
3223
        g_Dbs.db[i].superTbls[j].batchCreateTableNum = 1000;
3224
      } else {
3225
        printf("ERROR: failed to read json, batch_create_tbl_num not found\n");
3226 3227 3228 3229
        goto PARSE_OVER;
      }      

      cJSON *childTblExists = cJSON_GetObjectItem(stbInfo, "child_table_exists"); // yes, no
3230 3231 3232
      if (childTblExists
              && childTblExists->type == cJSON_String
              && childTblExists->valuestring != NULL) {
3233 3234 3235 3236 3237 3238 3239 3240 3241 3242
        if (0 == strncasecmp(childTblExists->valuestring, "yes", 3)) {
          g_Dbs.db[i].superTbls[j].childTblExists = TBL_ALREADY_EXISTS;
        } else if (0 == strncasecmp(childTblExists->valuestring, "no", 2)) {
          g_Dbs.db[i].superTbls[j].childTblExists = TBL_NO_EXISTS;
        } else {
          g_Dbs.db[i].superTbls[j].childTblExists = TBL_NO_EXISTS;
        }
      } else if (!childTblExists) {
        g_Dbs.db[i].superTbls[j].childTblExists = TBL_NO_EXISTS;
      } else {
3243
        printf("ERROR: failed to read json, child_table_exists not found\n");
3244 3245 3246 3247 3248
        goto PARSE_OVER;
      }
      
      cJSON* count = cJSON_GetObjectItem(stbInfo, "childtable_count");
      if (!count || count->type != cJSON_Number || 0 >= count->valueint) {
3249
        printf("ERROR: failed to read json, childtable_count not found\n");
3250 3251 3252 3253 3254
        goto PARSE_OVER;
      }
      g_Dbs.db[i].superTbls[j].childTblCount = count->valueint;

      cJSON *dataSource = cJSON_GetObjectItem(stbInfo, "data_source");
3255 3256 3257 3258
      if (dataSource && dataSource->type == cJSON_String
              && dataSource->valuestring != NULL) {
        tstrncpy(g_Dbs.db[i].superTbls[j].dataSource,
                dataSource->valuestring, MAX_DB_NAME_SIZE);
3259
      } else if (!dataSource) {
3260
        tstrncpy(g_Dbs.db[i].superTbls[j].dataSource, "rand", MAX_DB_NAME_SIZE);
3261
      } else {
3262
        printf("ERROR: failed to read json, data_source not found\n");
3263 3264 3265 3266
        goto PARSE_OVER;
      }

      cJSON *insertMode = cJSON_GetObjectItem(stbInfo, "insert_mode"); // taosc , restful
3267 3268 3269 3270
      if (insertMode && insertMode->type == cJSON_String
              && insertMode->valuestring != NULL) {
        tstrncpy(g_Dbs.db[i].superTbls[j].insertMode,
                insertMode->valuestring, MAX_DB_NAME_SIZE);
3271
      } else if (!insertMode) {
3272
        tstrncpy(g_Dbs.db[i].superTbls[j].insertMode, "taosc", MAX_DB_NAME_SIZE);
3273
      } else {
3274
        printf("ERROR: failed to read json, insert_mode not found\n");
3275 3276 3277
        goto PARSE_OVER;
      }

3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299
      cJSON* childTbl_limit = cJSON_GetObjectItem(stbInfo, "childtable_limit");
      if (childTbl_limit) {
        if (childTbl_limit->type != cJSON_Number) {
            printf("ERROR: failed to read json, childtable_limit\n");
            goto PARSE_OVER;
        }
        g_Dbs.db[i].superTbls[j].childTblLimit = childTbl_limit->valueint;
      } else {
        g_Dbs.db[i].superTbls[j].childTblLimit = -1;    // select ... limit -1 means all query result
      }

      cJSON* childTbl_offset = cJSON_GetObjectItem(stbInfo, "childtable_offset");
      if (childTbl_offset) {
        if (childTbl_offset->type != cJSON_Number || 0 > childTbl_offset->valueint) {
            printf("ERROR: failed to read json, childtable_offset\n");
            goto PARSE_OVER;
        }
        g_Dbs.db[i].superTbls[j].childTblOffset = childTbl_offset->valueint;
      } else {
        g_Dbs.db[i].superTbls[j].childTblOffset = 0;
      }

3300 3301
      cJSON *ts = cJSON_GetObjectItem(stbInfo, "start_timestamp");
      if (ts && ts->type == cJSON_String && ts->valuestring != NULL) {
3302
        tstrncpy(g_Dbs.db[i].superTbls[j].startTimestamp, ts->valuestring, MAX_DB_NAME_SIZE);
3303
      } else if (!ts) {
3304
        tstrncpy(g_Dbs.db[i].superTbls[j].startTimestamp, "now", MAX_DB_NAME_SIZE);
3305
      } else {
3306
        printf("ERROR: failed to read json, start_timestamp not found\n");
3307 3308
        goto PARSE_OVER;
      }
3309

3310 3311 3312 3313
      cJSON* timestampStep = cJSON_GetObjectItem(stbInfo, "timestamp_step");
      if (timestampStep && timestampStep->type == cJSON_Number) {
        g_Dbs.db[i].superTbls[j].timeStampStep = timestampStep->valueint;
      } else if (!timestampStep) {
3314
        g_Dbs.db[i].superTbls[j].timeStampStep = DEFAULT_TIMESTAMP_STEP;
3315
      } else {
3316
        printf("ERROR: failed to read json, timestamp_step not found\n");
3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328
        goto PARSE_OVER;
      }

      cJSON* sampleDataBufSize = cJSON_GetObjectItem(stbInfo, "sample_buf_size");
      if (sampleDataBufSize && sampleDataBufSize->type == cJSON_Number) {
        g_Dbs.db[i].superTbls[j].sampleDataBufSize = sampleDataBufSize->valueint;
        if (g_Dbs.db[i].superTbls[j].sampleDataBufSize < 1024*1024) {
          g_Dbs.db[i].superTbls[j].sampleDataBufSize = 1024*1024 + 1024;
        }
      } else if (!sampleDataBufSize) {
        g_Dbs.db[i].superTbls[j].sampleDataBufSize = 1024*1024 + 1024;
      } else {
3329
        printf("ERROR: failed to read json, sample_buf_size not found\n");
3330 3331
        goto PARSE_OVER;
      }      
3332

3333 3334
      cJSON *sampleFormat = cJSON_GetObjectItem(stbInfo, "sample_format");
      if (sampleFormat && sampleFormat->type == cJSON_String && sampleFormat->valuestring != NULL) {
3335 3336
        tstrncpy(g_Dbs.db[i].superTbls[j].sampleFormat,
                sampleFormat->valuestring, MAX_DB_NAME_SIZE);
3337
      } else if (!sampleFormat) {
3338
        tstrncpy(g_Dbs.db[i].superTbls[j].sampleFormat, "csv", MAX_DB_NAME_SIZE);
3339
      } else {
3340
        printf("ERROR: failed to read json, sample_format not found\n");
3341 3342
        goto PARSE_OVER;
      }      
3343

3344 3345
      cJSON *sampleFile = cJSON_GetObjectItem(stbInfo, "sample_file");
      if (sampleFile && sampleFile->type == cJSON_String && sampleFile->valuestring != NULL) {
3346 3347
        tstrncpy(g_Dbs.db[i].superTbls[j].sampleFile,
                sampleFile->valuestring, MAX_FILE_NAME_LEN);
3348 3349 3350
      } else if (!sampleFile) {
        memset(g_Dbs.db[i].superTbls[j].sampleFile, 0, MAX_FILE_NAME_LEN);
      } else {
3351
        printf("ERROR: failed to read json, sample_file not found\n");
3352 3353
        goto PARSE_OVER;
      }          
3354

3355 3356
      cJSON *tagsFile = cJSON_GetObjectItem(stbInfo, "tags_file");
      if (tagsFile && tagsFile->type == cJSON_String && tagsFile->valuestring != NULL) {
3357 3358
        tstrncpy(g_Dbs.db[i].superTbls[j].tagsFile,
                tagsFile->valuestring, MAX_FILE_NAME_LEN);
3359 3360 3361 3362 3363 3364 3365 3366 3367
        if (0 == g_Dbs.db[i].superTbls[j].tagsFile[0]) {
          g_Dbs.db[i].superTbls[j].tagSource = 0;
        } else {
          g_Dbs.db[i].superTbls[j].tagSource = 1;
        }
      } else if (!tagsFile) {
        memset(g_Dbs.db[i].superTbls[j].tagsFile, 0, MAX_FILE_NAME_LEN);
        g_Dbs.db[i].superTbls[j].tagSource = 0;
      } else {
3368
        printf("ERROR: failed to read json, tags_file not found\n");
3369 3370
        goto PARSE_OVER;
      }
3371

3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383
      cJSON* maxSqlLen = cJSON_GetObjectItem(stbInfo, "max_sql_len");
      if (maxSqlLen && maxSqlLen->type == cJSON_Number) {
        int32_t len = maxSqlLen->valueint;
        if (len > TSDB_MAX_ALLOWED_SQL_LEN) {
          len = TSDB_MAX_ALLOWED_SQL_LEN;
        } else if (len < TSDB_MAX_SQL_LEN) {
          len = TSDB_MAX_SQL_LEN;
        }       
        g_Dbs.db[i].superTbls[j].maxSqlLen = len;
      } else if (!maxSqlLen) {
        g_Dbs.db[i].superTbls[j].maxSqlLen = TSDB_MAX_SQL_LEN;
      } else {
3384
        printf("ERROR: failed to read json, maxSqlLen not found\n");
3385 3386 3387
        goto PARSE_OVER;
      }      

3388 3389 3390 3391 3392
      cJSON *multiThreadWriteOneTbl =
          cJSON_GetObjectItem(stbInfo, "multi_thread_write_one_tbl"); // no , yes
      if (multiThreadWriteOneTbl
              && multiThreadWriteOneTbl->type == cJSON_String
              && multiThreadWriteOneTbl->valuestring != NULL) {
3393 3394 3395 3396 3397 3398 3399 3400
        if (0 == strncasecmp(multiThreadWriteOneTbl->valuestring, "yes", 3)) {
          g_Dbs.db[i].superTbls[j].multiThreadWriteOneTbl = 1;
        } else {
          g_Dbs.db[i].superTbls[j].multiThreadWriteOneTbl = 0;
        }        
      } else if (!multiThreadWriteOneTbl) {
        g_Dbs.db[i].superTbls[j].multiThreadWriteOneTbl = 0;
      } else {
3401
        printf("ERROR: failed to read json, multiThreadWriteOneTbl not found\n");
3402 3403 3404 3405 3406 3407 3408 3409 3410
        goto PARSE_OVER;
      }

      cJSON* numberOfTblInOneSql = cJSON_GetObjectItem(stbInfo, "number_of_tbl_in_one_sql");
      if (numberOfTblInOneSql && numberOfTblInOneSql->type == cJSON_Number) {
        g_Dbs.db[i].superTbls[j].numberOfTblInOneSql = numberOfTblInOneSql->valueint;
      } else if (!numberOfTblInOneSql) {
        g_Dbs.db[i].superTbls[j].numberOfTblInOneSql = 0;
      } else {
3411
        printf("ERROR: failed to read json, numberOfTblInOneSql not found\n");
3412 3413 3414 3415 3416 3417 3418 3419 3420
        goto PARSE_OVER;
      }      

      cJSON* rowsPerTbl = cJSON_GetObjectItem(stbInfo, "rows_per_tbl");
      if (rowsPerTbl && rowsPerTbl->type == cJSON_Number) {
        g_Dbs.db[i].superTbls[j].rowsPerTbl = rowsPerTbl->valueint;
      } else if (!rowsPerTbl) {
        g_Dbs.db[i].superTbls[j].rowsPerTbl = 1;
      } else {
3421
        printf("ERROR: failed to read json, rowsPerTbl not found\n");
3422 3423 3424 3425 3426 3427 3428 3429 3430
        goto PARSE_OVER;
      }      

      cJSON* disorderRatio = cJSON_GetObjectItem(stbInfo, "disorder_ratio");
      if (disorderRatio && disorderRatio->type == cJSON_Number) {
        g_Dbs.db[i].superTbls[j].disorderRatio = disorderRatio->valueint;
      } else if (!disorderRatio) {
        g_Dbs.db[i].superTbls[j].disorderRatio = 0;
      } else {
3431
        printf("ERROR: failed to read json, disorderRatio not found\n");
3432 3433 3434 3435 3436 3437 3438 3439 3440
        goto PARSE_OVER;
      }      

      cJSON* disorderRange = cJSON_GetObjectItem(stbInfo, "disorder_range");
      if (disorderRange && disorderRange->type == cJSON_Number) {
        g_Dbs.db[i].superTbls[j].disorderRange = disorderRange->valueint;
      } else if (!disorderRange) {
        g_Dbs.db[i].superTbls[j].disorderRange = 1000;
      } else {
3441
        printf("ERROR: failed to read json, disorderRange not found\n");
3442 3443
        goto PARSE_OVER;
      }
3444

3445 3446 3447 3448 3449 3450
      cJSON* insertRows = cJSON_GetObjectItem(stbInfo, "insert_rows");
      if (insertRows && insertRows->type == cJSON_Number) {
        g_Dbs.db[i].superTbls[j].insertRows = insertRows->valueint;
      } else if (!insertRows) {
        g_Dbs.db[i].superTbls[j].insertRows = 0x7FFFFFFFFFFFFFFF;
      } else {
3451
        fprintf(stderr, "failed to read json, insert_rows input mistake");
3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462
        goto PARSE_OVER;
      }

      cJSON* insertInterval = cJSON_GetObjectItem(stbInfo, "insert_interval");
      if (insertInterval && insertInterval->type == cJSON_Number) {
        g_Dbs.db[i].superTbls[j].insertInterval = insertInterval->valueint;
      } else if (!insertInterval) {
        debugPrint("%s() LN%d: stable insert interval be overrided by global %d.\n",
                __func__, __LINE__, g_args.insert_interval);
        g_Dbs.db[i].superTbls[j].insertInterval = g_args.insert_interval;
      } else {
3463
        fprintf(stderr, "failed to read json, insert_interval input mistake");
3464 3465 3466
        goto PARSE_OVER;
      }

3467 3468
      if (NO_CREATE_SUBTBL == g_Dbs.db[i].superTbls[j].autoCreateTable
              || (TBL_ALREADY_EXISTS == g_Dbs.db[i].superTbls[j].childTblExists)) {
3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492
        continue;
      }

      int retVal = getColumnAndTagTypeFromInsertJsonFile(stbInfo, &g_Dbs.db[i].superTbls[j]);
      if (false == retVal) {
        goto PARSE_OVER;
      }      
    }    
  }

  ret = true;

PARSE_OVER:
  //free(content);
  //cJSON_Delete(root);
  //fclose(fp);
  return ret;
}

static bool getMetaFromQueryJsonFile(cJSON* root) {
  bool  ret = false;

  cJSON* cfgdir = cJSON_GetObjectItem(root, "cfgdir");
  if (cfgdir && cfgdir->type == cJSON_String && cfgdir->valuestring != NULL) {
3493
    tstrncpy(g_queryInfo.cfgDir, cfgdir->valuestring, MAX_FILE_NAME_LEN);
3494 3495 3496 3497
  }

  cJSON* host = cJSON_GetObjectItem(root, "host");
  if (host && host->type == cJSON_String && host->valuestring != NULL) {
3498
    tstrncpy(g_queryInfo.host, host->valuestring, MAX_DB_NAME_SIZE);
3499
  } else if (!host) {
3500
    tstrncpy(g_queryInfo.host, "127.0.0.1", MAX_DB_NAME_SIZE);
3501
  } else {
3502
    printf("ERROR: failed to read json, host not found\n");
3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514
    goto PARSE_OVER;
  }

  cJSON* port = cJSON_GetObjectItem(root, "port");
  if (port && port->type == cJSON_Number) {
    g_queryInfo.port = port->valueint;
  } else if (!port) {
    g_queryInfo.port = 6030;
  }

  cJSON* user = cJSON_GetObjectItem(root, "user");
  if (user && user->type == cJSON_String && user->valuestring != NULL) {
3515
    tstrncpy(g_queryInfo.user, user->valuestring, MAX_DB_NAME_SIZE);   
3516
  } else if (!user) {
3517
    tstrncpy(g_queryInfo.user, "root", MAX_DB_NAME_SIZE); ;
3518 3519 3520 3521
  }

  cJSON* password = cJSON_GetObjectItem(root, "password");
  if (password && password->type == cJSON_String && password->valuestring != NULL) {
3522
    tstrncpy(g_queryInfo.password, password->valuestring, MAX_DB_NAME_SIZE);
3523
  } else if (!password) {
3524
    tstrncpy(g_queryInfo.password, "taosdata", MAX_DB_NAME_SIZE);;
3525
  }
H
hzcheng 已提交
3526

3527
  cJSON *answerPrompt = cJSON_GetObjectItem(root, "confirm_parameter_prompt"); // yes, no,
3528 3529
  if (answerPrompt && answerPrompt->type == cJSON_String
          && answerPrompt->valuestring != NULL) {
3530 3531 3532 3533
    if (0 == strncasecmp(answerPrompt->valuestring, "yes", 3)) {
      g_args.answer_yes = false;
    } else if (0 == strncasecmp(answerPrompt->valuestring, "no", 2)) {
      g_args.answer_yes = true;
H
hzcheng 已提交
3534
    } else {
3535
      g_args.answer_yes = false;
H
hzcheng 已提交
3536
    }
3537 3538 3539
  } else if (!answerPrompt) {
    g_args.answer_yes = false;
  } else {
3540
    printf("ERROR: failed to read json, confirm_parameter_prompt not found\n");
3541 3542 3543 3544 3545
    goto PARSE_OVER;
  }  

  cJSON* dbs = cJSON_GetObjectItem(root, "databases");
  if (dbs && dbs->type == cJSON_String && dbs->valuestring != NULL) {
3546
    tstrncpy(g_queryInfo.dbName, dbs->valuestring, MAX_DB_NAME_SIZE);
3547
  } else if (!dbs) {
3548
    printf("ERROR: failed to read json, databases not found\n");
3549
    goto PARSE_OVER;
H
hzcheng 已提交
3550
  }
3551 3552 3553

  cJSON* queryMode = cJSON_GetObjectItem(root, "query_mode");
  if (queryMode && queryMode->type == cJSON_String && queryMode->valuestring != NULL) {
3554
    tstrncpy(g_queryInfo.queryMode, queryMode->valuestring, MAX_TB_NAME_SIZE);
3555
  } else if (!queryMode) {
3556
    tstrncpy(g_queryInfo.queryMode, "taosc", MAX_TB_NAME_SIZE);
3557
  } else {
3558
    printf("ERROR: failed to read json, query_mode not found\n");
3559
    goto PARSE_OVER;
H
hzcheng 已提交
3560
  }
3561 3562 3563 3564 3565 3566 3567
  
  // super_table_query 
  cJSON *superQuery = cJSON_GetObjectItem(root, "specified_table_query");
  if (!superQuery) {
    g_queryInfo.superQueryInfo.concurrent = 0;
    g_queryInfo.superQueryInfo.sqlCount = 0;
  } else if (superQuery->type != cJSON_Object) {
3568
    printf("ERROR: failed to read json, super_table_query not found\n");
3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591
    goto PARSE_OVER;
  } else {  
    cJSON* rate = cJSON_GetObjectItem(superQuery, "query_interval");
    if (rate && rate->type == cJSON_Number) {
      g_queryInfo.superQueryInfo.rate = rate->valueint;
    } else if (!rate) {
      g_queryInfo.superQueryInfo.rate = 0;
    }
  
    cJSON* concurrent = cJSON_GetObjectItem(superQuery, "concurrent");
    if (concurrent && concurrent->type == cJSON_Number) {
      g_queryInfo.superQueryInfo.concurrent = concurrent->valueint;
    } else if (!concurrent) {
      g_queryInfo.superQueryInfo.concurrent = 1;
    }
  
    cJSON* mode = cJSON_GetObjectItem(superQuery, "mode");
    if (mode && mode->type == cJSON_String && mode->valuestring != NULL) {
      if (0 == strcmp("sync", mode->valuestring)) {      
        g_queryInfo.superQueryInfo.subscribeMode = 0;
      } else if (0 == strcmp("async", mode->valuestring)) {      
        g_queryInfo.superQueryInfo.subscribeMode = 1;
      } else {
3592
        printf("ERROR: failed to read json, subscribe mod error\n");
3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614
        goto PARSE_OVER;
      }
    } else {
      g_queryInfo.superQueryInfo.subscribeMode = 0;
    }
    
    cJSON* interval = cJSON_GetObjectItem(superQuery, "interval");
    if (interval && interval->type == cJSON_Number) {
      g_queryInfo.superQueryInfo.subscribeInterval = interval->valueint;
    } else if (!interval) {    
      //printf("failed to read json, subscribe interval no found\n");
      //goto PARSE_OVER;
      g_queryInfo.superQueryInfo.subscribeInterval = 10000;
    }
  
    cJSON* restart = cJSON_GetObjectItem(superQuery, "restart");
    if (restart && restart->type == cJSON_String && restart->valuestring != NULL) {
      if (0 == strcmp("yes", restart->valuestring)) {      
        g_queryInfo.superQueryInfo.subscribeRestart = 1;
      } else if (0 == strcmp("no", restart->valuestring)) {      
        g_queryInfo.superQueryInfo.subscribeRestart = 0;
      } else {
3615
        printf("ERROR: failed to read json, subscribe restart error\n");
3616 3617 3618 3619 3620 3621 3622
        goto PARSE_OVER;
      }
    } else {
      g_queryInfo.superQueryInfo.subscribeRestart = 1;
    }
  
    cJSON* keepProgress = cJSON_GetObjectItem(superQuery, "keepProgress");
3623 3624 3625
    if (keepProgress
            && keepProgress->type == cJSON_String
            && keepProgress->valuestring != NULL) {
3626 3627 3628 3629 3630
      if (0 == strcmp("yes", keepProgress->valuestring)) {      
        g_queryInfo.superQueryInfo.subscribeKeepProgress = 1;
      } else if (0 == strcmp("no", keepProgress->valuestring)) {      
        g_queryInfo.superQueryInfo.subscribeKeepProgress = 0;
      } else {
3631
        printf("ERROR: failed to read json, subscribe keepProgress error\n");
3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642
        goto PARSE_OVER;
      }
    } else {
      g_queryInfo.superQueryInfo.subscribeKeepProgress = 0;
    }

    // sqls   
    cJSON* superSqls = cJSON_GetObjectItem(superQuery, "sqls");
    if (!superSqls) {
      g_queryInfo.superQueryInfo.sqlCount = 0;
    } else if (superSqls->type != cJSON_Array) {
3643
      printf("ERROR: failed to read json, super sqls not found\n");
3644 3645 3646 3647
      goto PARSE_OVER;
    } else {  
      int superSqlSize = cJSON_GetArraySize(superSqls);
      if (superSqlSize > MAX_QUERY_SQL_COUNT) {
3648
        printf("ERROR: failed to read json, query sql size overflow, max is %d\n", MAX_QUERY_SQL_COUNT);
3649 3650
        goto PARSE_OVER;
      }
3651

3652 3653 3654 3655 3656 3657 3658
      g_queryInfo.superQueryInfo.sqlCount = superSqlSize;
      for (int j = 0; j < superSqlSize; ++j) {
        cJSON* sql = cJSON_GetArrayItem(superSqls, j);
        if (sql == NULL) continue;
      
        cJSON *sqlStr = cJSON_GetObjectItem(sql, "sql");
        if (!sqlStr || sqlStr->type != cJSON_String || sqlStr->valuestring == NULL) {
3659
          printf("ERROR: failed to read json, sql not found\n");
3660 3661
          goto PARSE_OVER;
        }
3662
        tstrncpy(g_queryInfo.superQueryInfo.sql[j], sqlStr->valuestring, MAX_QUERY_SQL_LENGTH);
H
hzcheng 已提交
3663

3664 3665
        cJSON *result = cJSON_GetObjectItem(sql, "result");
        if (NULL != result && result->type == cJSON_String && result->valuestring != NULL) {
3666
          tstrncpy(g_queryInfo.superQueryInfo.result[j], result->valuestring, MAX_FILE_NAME_LEN);
3667 3668 3669
        } else if (NULL == result) {
          memset(g_queryInfo.superQueryInfo.result[j], 0, MAX_FILE_NAME_LEN);
        } else {
3670
          printf("ERROR: failed to read json, super query result file not found\n");
3671 3672 3673 3674 3675
          goto PARSE_OVER;
        } 
      }
    }
  }
3676

3677 3678 3679 3680 3681 3682
  // sub_table_query 
  cJSON *subQuery = cJSON_GetObjectItem(root, "super_table_query");
  if (!subQuery) {
    g_queryInfo.subQueryInfo.threadCnt = 0;
    g_queryInfo.subQueryInfo.sqlCount = 0;
  } else if (subQuery->type != cJSON_Object) {
3683
    printf("ERROR: failed to read json, sub_table_query not found\n");
3684 3685
    ret = true;
    goto PARSE_OVER;
H
hzcheng 已提交
3686
  } else {
3687 3688 3689 3690 3691 3692
    cJSON* subrate = cJSON_GetObjectItem(subQuery, "query_interval");
    if (subrate && subrate->type == cJSON_Number) {
      g_queryInfo.subQueryInfo.rate = subrate->valueint;
    } else if (!subrate) {
      g_queryInfo.subQueryInfo.rate = 0;
    }
3693

3694 3695 3696 3697 3698 3699
    cJSON* threads = cJSON_GetObjectItem(subQuery, "threads");
    if (threads && threads->type == cJSON_Number) {
      g_queryInfo.subQueryInfo.threadCnt = threads->valueint;
    } else if (!threads) {
      g_queryInfo.subQueryInfo.threadCnt = 1;
    }
3700

3701 3702 3703 3704 3705 3706
    //cJSON* subTblCnt = cJSON_GetObjectItem(subQuery, "childtable_count");
    //if (subTblCnt && subTblCnt->type == cJSON_Number) {
    //  g_queryInfo.subQueryInfo.childTblCount = subTblCnt->valueint;
    //} else if (!subTblCnt) {
    //  g_queryInfo.subQueryInfo.childTblCount = 0;
    //}
3707

3708 3709
    cJSON* stblname = cJSON_GetObjectItem(subQuery, "stblname");
    if (stblname && stblname->type == cJSON_String && stblname->valuestring != NULL) {
3710
      tstrncpy(g_queryInfo.subQueryInfo.sTblName, stblname->valuestring, MAX_TB_NAME_SIZE);
3711
    } else {
3712
      printf("ERROR: failed to read json, super table name not found\n");
3713 3714
      goto PARSE_OVER;
    }
3715

3716 3717 3718 3719 3720 3721 3722
    cJSON* submode = cJSON_GetObjectItem(subQuery, "mode");
    if (submode && submode->type == cJSON_String && submode->valuestring != NULL) {
      if (0 == strcmp("sync", submode->valuestring)) {      
        g_queryInfo.subQueryInfo.subscribeMode = 0;
      } else if (0 == strcmp("async", submode->valuestring)) {      
        g_queryInfo.subQueryInfo.subscribeMode = 1;
      } else {
3723
        printf("ERROR: failed to read json, subscribe mod error\n");
3724 3725 3726 3727 3728
        goto PARSE_OVER;
      }
    } else {
      g_queryInfo.subQueryInfo.subscribeMode = 0;
    }
3729

3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745
    cJSON* subinterval = cJSON_GetObjectItem(subQuery, "interval");
    if (subinterval && subinterval->type == cJSON_Number) {
      g_queryInfo.subQueryInfo.subscribeInterval = subinterval->valueint;
    } else if (!subinterval) {    
      //printf("failed to read json, subscribe interval no found\n");
      //goto PARSE_OVER;
      g_queryInfo.subQueryInfo.subscribeInterval = 10000;
    }
  
    cJSON* subrestart = cJSON_GetObjectItem(subQuery, "restart");
    if (subrestart && subrestart->type == cJSON_String && subrestart->valuestring != NULL) {
      if (0 == strcmp("yes", subrestart->valuestring)) {      
        g_queryInfo.subQueryInfo.subscribeRestart = 1;
      } else if (0 == strcmp("no", subrestart->valuestring)) {      
        g_queryInfo.subQueryInfo.subscribeRestart = 0;
      } else {
3746
        printf("ERROR: failed to read json, subscribe restart error\n");
3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759
        goto PARSE_OVER;
      }
    } else {
      g_queryInfo.subQueryInfo.subscribeRestart = 1;
    }
  
    cJSON* subkeepProgress = cJSON_GetObjectItem(subQuery, "keepProgress");
    if (subkeepProgress && subkeepProgress->type == cJSON_String && subkeepProgress->valuestring != NULL) {
      if (0 == strcmp("yes", subkeepProgress->valuestring)) {      
        g_queryInfo.subQueryInfo.subscribeKeepProgress = 1;
      } else if (0 == strcmp("no", subkeepProgress->valuestring)) {      
        g_queryInfo.subQueryInfo.subscribeKeepProgress = 0;
      } else {
3760
        printf("ERROR: failed to read json, subscribe keepProgress error\n");
3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771
        goto PARSE_OVER;
      }
    } else {
      g_queryInfo.subQueryInfo.subscribeKeepProgress = 0;
    }  

    // sqls     
    cJSON* subsqls = cJSON_GetObjectItem(subQuery, "sqls");
    if (!subsqls) {
      g_queryInfo.subQueryInfo.sqlCount = 0;
    } else if (subsqls->type != cJSON_Array) {
3772
      printf("ERROR: failed to read json, super sqls not found\n");
3773 3774 3775 3776
      goto PARSE_OVER;
    } else {  
      int superSqlSize = cJSON_GetArraySize(subsqls);
      if (superSqlSize > MAX_QUERY_SQL_COUNT) {
3777
        printf("ERROR: failed to read json, query sql size overflow, max is %d\n", MAX_QUERY_SQL_COUNT);
3778 3779 3780 3781 3782 3783 3784 3785 3786 3787
        goto PARSE_OVER;
      }
    
      g_queryInfo.subQueryInfo.sqlCount = superSqlSize;
      for (int j = 0; j < superSqlSize; ++j) {      
        cJSON* sql = cJSON_GetArrayItem(subsqls, j);
        if (sql == NULL) continue;
        
        cJSON *sqlStr = cJSON_GetObjectItem(sql, "sql");
        if (!sqlStr || sqlStr->type != cJSON_String || sqlStr->valuestring == NULL) {
3788
          printf("ERROR: failed to read json, sql not found\n");
3789 3790
          goto PARSE_OVER;
        }
3791
        tstrncpy(g_queryInfo.subQueryInfo.sql[j], sqlStr->valuestring, MAX_QUERY_SQL_LENGTH);
3792 3793 3794

        cJSON *result = cJSON_GetObjectItem(sql, "result");
        if (result != NULL && result->type == cJSON_String && result->valuestring != NULL){
3795
          tstrncpy(g_queryInfo.subQueryInfo.result[j], result->valuestring, MAX_FILE_NAME_LEN);
3796 3797 3798
        } else if (NULL == result) {
          memset(g_queryInfo.subQueryInfo.result[j], 0, MAX_FILE_NAME_LEN);
        }  else {
3799
          printf("ERROR: failed to read json, sub query result file not found\n");
3800 3801 3802 3803
          goto PARSE_OVER;
        } 
      }
    }
H
hzcheng 已提交
3804 3805
  }

3806
  ret = true;
H
hzcheng 已提交
3807

3808 3809 3810 3811 3812 3813
PARSE_OVER:
  //free(content);
  //cJSON_Delete(root);
  //fclose(fp);
  return ret;
}
H
hzcheng 已提交
3814

3815
static bool getInfoFromJsonFile(char* file) {
3816
    debugPrint("%s %d %s\n", __func__, __LINE__, file);
3817

3818 3819 3820 3821 3822
  FILE *fp = fopen(file, "r");
  if (!fp) {
    printf("failed to read %s, reason:%s\n", file, strerror(errno));
    return false;
  }
H
Hui Li 已提交
3823

3824 3825 3826 3827 3828 3829 3830 3831 3832
  bool  ret = false;
  int   maxLen = 64000;
  char *content = calloc(1, maxLen + 1);
  int   len = fread(content, 1, maxLen, fp);
  if (len <= 0) {
    free(content);
    fclose(fp);
    printf("failed to read %s, content is null", file);
    return false;
H
hzcheng 已提交
3833
  }
H
Hui Li 已提交
3834

3835 3836 3837
  content[len] = 0;
  cJSON* root = cJSON_Parse(content);
  if (root == NULL) {
3838
    printf("ERROR: failed to cjson parse %s, invalid json format\n", file);
3839 3840
    goto PARSE_OVER;
  }
H
Hui Li 已提交
3841

3842 3843 3844
  cJSON* filetype = cJSON_GetObjectItem(root, "filetype");
  if (filetype && filetype->type == cJSON_String && filetype->valuestring != NULL) {
    if (0 == strcasecmp("insert", filetype->valuestring)) {
3845
      g_args.test_mode = INSERT_MODE;
3846
    } else if (0 == strcasecmp("query", filetype->valuestring)) {
3847
      g_args.test_mode = QUERY_MODE;
3848
    } else if (0 == strcasecmp("subscribe", filetype->valuestring)) {
3849
      g_args.test_mode = SUBSCRIBE_MODE;
3850
    } else {
3851
      printf("ERROR: failed to read json, filetype not support\n");
3852 3853 3854
      goto PARSE_OVER;
    }
  } else if (!filetype) {
3855
    g_args.test_mode = INSERT_MODE;
3856
  } else {
3857
    printf("ERROR: failed to read json, filetype not found\n");
3858 3859
    goto PARSE_OVER;
  }
H
hzcheng 已提交
3860

3861
  if (INSERT_MODE == g_args.test_mode) {
3862
    ret = getMetaFromInsertJsonFile(root);
3863
  } else if (QUERY_MODE == g_args.test_mode) {
3864
    ret = getMetaFromQueryJsonFile(root);
3865
  } else if (SUBSCRIBE_MODE == g_args.test_mode) {
3866 3867
    ret = getMetaFromQueryJsonFile(root);
  } else {
3868
    printf("ERROR: input json file type error! please input correct file type: insert or query or subscribe\n");
3869
    goto PARSE_OVER;
3870
  } 
3871 3872 3873 3874

PARSE_OVER:
  free(content);
  cJSON_Delete(root);
H
hzcheng 已提交
3875
  fclose(fp);
3876 3877
  return ret;
}
H
hzcheng 已提交
3878

3879
void prepareSampleData() {
3880 3881 3882 3883 3884
  for (int i = 0; i < g_Dbs.dbCount; i++) {    
    for (int j = 0; j < g_Dbs.db[i].superTblCount; j++) {
      //if (0 == strncasecmp(g_Dbs.db[i].superTbls[j].dataSource, "sample", 6)) {
      //  readSampleFromFileToMem(&g_Dbs.db[i].superTbls[j]);
      //}
3885

3886 3887
      if (g_Dbs.db[i].superTbls[j].tagsFile[0] != 0) {
        (void)readTagFromCsvFileToMem(&g_Dbs.db[i].superTbls[j]);
S
Shuaiqiang Chang 已提交
3888
      }
3889 3890 3891 3892 3893 3894 3895 3896
    }
  }
}

void postFreeResource() {
  tmfclose(g_fpOfInsertResult);
  for (int i = 0; i < g_Dbs.dbCount; i++) {    
    for (int j = 0; j < g_Dbs.db[i].superTblCount; j++) {
3897 3898 3899
      if (0 != g_Dbs.db[i].superTbls[j].colsOfCreateChildTable) {
        free(g_Dbs.db[i].superTbls[j].colsOfCreateChildTable);
        g_Dbs.db[i].superTbls[j].colsOfCreateChildTable = NULL;
S
Shuaiqiang Chang 已提交
3900
      }
3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912
      if (0 != g_Dbs.db[i].superTbls[j].sampleDataBuf) {
        free(g_Dbs.db[i].superTbls[j].sampleDataBuf);
        g_Dbs.db[i].superTbls[j].sampleDataBuf = NULL;
      }
      if (0 != g_Dbs.db[i].superTbls[j].tagDataBuf) {
        free(g_Dbs.db[i].superTbls[j].tagDataBuf);
        g_Dbs.db[i].superTbls[j].tagDataBuf = NULL;
      }
      if (0 != g_Dbs.db[i].superTbls[j].childTblName) {
        free(g_Dbs.db[i].superTbls[j].childTblName);
        g_Dbs.db[i].superTbls[j].childTblName = NULL;
      }
S
Shuaiqiang Chang 已提交
3913
    }
3914 3915
  }
}
S
Shuaiqiang Chang 已提交
3916

3917 3918
static int getRowDataFromSample(char*  dataBuf, int maxLen, int64_t timestamp,
      SSuperTable* superTblInfo, int* sampleUsePos) {
3919
  if ((*sampleUsePos) == MAX_SAMPLES_ONCE_FROM_FILE) {
3920
    int ret = readSampleFromCsvFileToMem(superTblInfo);
3921
    if (0 != ret) {
3922
      tmfree(superTblInfo->sampleDataBuf);
3923 3924 3925 3926
      return -1;
    }
    *sampleUsePos = 0;
  }
S
Shuaiqiang Chang 已提交
3927

3928
  int    dataLen = 0;
3929 3930 3931 3932
  dataLen += snprintf(dataBuf + dataLen, maxLen - dataLen,
          "(%" PRId64 ", ", timestamp);
  dataLen += snprintf(dataBuf + dataLen, maxLen - dataLen,
          "%s", superTblInfo->sampleDataBuf + superTblInfo->lenOfOneRow * (*sampleUsePos));
3933
  dataLen += snprintf(dataBuf + dataLen, maxLen - dataLen, ")");
S
Shuaiqiang Chang 已提交
3934

3935
  (*sampleUsePos)++;
3936
 
3937 3938
  return dataLen;
}
S
Shuaiqiang Chang 已提交
3939

3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977
int generateRowData(char*  dataBuf, int maxLen, int64_t timestamp, SSuperTable* stbInfo) {
  int    dataLen = 0;
  dataLen += snprintf(dataBuf + dataLen, maxLen - dataLen, "(%" PRId64 ", ", timestamp);
  for (int i = 0; i < stbInfo->columnCount; i++) {    
    if ((0 == strncasecmp(stbInfo->columns[i].dataType, "binary", 6)) || (0 == strncasecmp(stbInfo->columns[i].dataType, "nchar", 5))) {
      if (stbInfo->columns[i].dataLen > TSDB_MAX_BINARY_LEN) {
        printf("binary or nchar length overflow, max size:%u\n", (uint32_t)TSDB_MAX_BINARY_LEN);
        return (-1);
      }
    
      char* buf = (char*)calloc(stbInfo->columns[i].dataLen+1, 1);
      if (NULL == buf) {
        printf("calloc failed! size:%d\n", stbInfo->columns[i].dataLen);
        return (-1);
      }
      rand_string(buf, stbInfo->columns[i].dataLen);
      dataLen += snprintf(dataBuf + dataLen, maxLen - dataLen, "\'%s\', ", buf);
      tmfree(buf);
    } else if (0 == strncasecmp(stbInfo->columns[i].dataType, "int", 3)) {
      dataLen += snprintf(dataBuf + dataLen, maxLen - dataLen, "%d, ", rand_int());
    } else if (0 == strncasecmp(stbInfo->columns[i].dataType, "bigint", 6)) {
      dataLen += snprintf(dataBuf + dataLen, maxLen - dataLen, "%"PRId64", ", rand_bigint());
    }  else if (0 == strncasecmp(stbInfo->columns[i].dataType, "float", 5)) {
      dataLen += snprintf(dataBuf + dataLen, maxLen - dataLen, "%f, ", rand_float());
    }  else if (0 == strncasecmp(stbInfo->columns[i].dataType, "double", 6)) {
      dataLen += snprintf(dataBuf + dataLen, maxLen - dataLen, "%f, ", rand_double());
    }  else if (0 == strncasecmp(stbInfo->columns[i].dataType, "smallint", 8)) {
      dataLen += snprintf(dataBuf + dataLen, maxLen - dataLen, "%d, ", rand_smallint());
    }  else if (0 == strncasecmp(stbInfo->columns[i].dataType, "tinyint", 7)) {
      dataLen += snprintf(dataBuf + dataLen, maxLen - dataLen, "%d, ", rand_tinyint());
    }  else if (0 == strncasecmp(stbInfo->columns[i].dataType, "bool", 4)) {
      dataLen += snprintf(dataBuf + dataLen, maxLen - dataLen, "%d, ", rand_bool());
    }  else if (0 == strncasecmp(stbInfo->columns[i].dataType, "timestamp", 9)) {
      dataLen += snprintf(dataBuf + dataLen, maxLen - dataLen, "%"PRId64", ", rand_bigint());
    }  else {
      printf("No support data type: %s\n", stbInfo->columns[i].dataType);
      return (-1);
    }
S
Shuaiqiang Chang 已提交
3978
  }
3979

3980 3981
  dataLen -= 2;
  dataLen += snprintf(dataBuf + dataLen, maxLen - dataLen, ")");
3982

3983 3984
  return dataLen;
}
S
Shuaiqiang Chang 已提交
3985

3986
static void syncWriteForNumberOfTblInOneSql(
3987
        threadInfo *winfo, char* sampleDataBuf) {
3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006
  SSuperTable* superTblInfo = winfo->superTblInfo;

  int   samplePos = 0;

  //printf("========threadID[%d], table rang: %d - %d \n", winfo->threadID, winfo->start_table_id, winfo->end_table_id);
  int64_t    lastPrintTime = taosGetTimestampMs();

  char* buffer = calloc(superTblInfo->maxSqlLen+1, 1);
  if (NULL == buffer) {
    printf("========calloc size[ %d ] fail!\n", superTblInfo->maxSqlLen);
    return;
  }

  int32_t  numberOfTblInOneSql = superTblInfo->numberOfTblInOneSql;
  int32_t  tbls = winfo->end_table_id - winfo->start_table_id + 1;
  if (numberOfTblInOneSql > tbls) {
    numberOfTblInOneSql = tbls;
  }

4007
  uint64_t time_counter = winfo->start_time;
4008 4009
  int sampleUsePos;

4010
  int insert_interval = superTblInfo?superTblInfo->insertInterval:g_args.insert_interval;
4011
  int64_t st = 0;
4012
  int64_t et = 0xffffffff;
4013 4014
  for (int i = 0; i < superTblInfo->insertRows;) {
    int32_t  tbl_id = 0;
4015
    for (int tableSeq = winfo->start_table_id; tableSeq <= winfo->end_table_id; ) {
4016
      int64_t start_time = 0;
4017 4018
      int inserted = i;

4019
      for (int k = 0; k < g_args.num_of_RPR;) {
4020 4021 4022 4023
        int len = 0;
        memset(buffer, 0, superTblInfo->maxSqlLen);
        char *pstr = buffer;

4024
        int32_t  end_tbl_id = tableSeq + numberOfTblInOneSql;
4025 4026 4027
        if (end_tbl_id > winfo->end_table_id) {
          end_tbl_id = winfo->end_table_id+1;
        }
4028

4029
        for (tbl_id = tableSeq ; tbl_id < end_tbl_id; tbl_id++) {  
4030 4031 4032 4033 4034 4035
          sampleUsePos = samplePos;
          if (AUTO_CREATE_SUBTBL == superTblInfo->autoCreateTable) {
            char* tagsValBuf = NULL;
            if (0 == superTblInfo->tagSource) {
              tagsValBuf = generateTagVaulesForStb(superTblInfo);
            } else {
4036 4037
              tagsValBuf = getTagValueFromTagSample(
                      superTblInfo, tbl_id % superTblInfo->tagSampleCount);
4038 4039 4040 4041 4042 4043
            }
            if (NULL == tagsValBuf) {
              goto free_and_statistics;
            }

            if (0 == len) {
4044 4045
              len += snprintf(pstr + len, 
                      superTblInfo->maxSqlLen - len, 
4046
                      "insert into %s.%s%d using %s.%s tags %s values ",
4047 4048 4049 4050 4051 4052
                      winfo->db_name, 
                      superTblInfo->childTblPrefix, 
                      tbl_id, 
                      winfo->db_name, 
                      superTblInfo->sTblName, 
                      tagsValBuf);
4053
            } else {
4054 4055
              len += snprintf(pstr + len, 
                      superTblInfo->maxSqlLen - len, 
4056
                      " %s.%s%d using %s.%s tags %s values ",
4057 4058 4059 4060 4061 4062
                      winfo->db_name, 
                      superTblInfo->childTblPrefix, 
                      tbl_id, 
                      winfo->db_name, 
                      superTblInfo->sTblName, 
                      tagsValBuf);
4063 4064 4065 4066
            }
            tmfree(tagsValBuf);
          } else if (TBL_ALREADY_EXISTS == superTblInfo->childTblExists) {
            if (0 == len) {
4067 4068
              len += snprintf(pstr + len, 
                      superTblInfo->maxSqlLen - len, 
4069
                      "insert into %s.%s values ",
4070 4071
                      winfo->db_name, 
                      superTblInfo->childTblName + tbl_id * TSDB_TABLE_NAME_LEN);
4072
            } else {
4073 4074
              len += snprintf(pstr + len, 
                      superTblInfo->maxSqlLen - len, 
4075
                      " %s.%s values ",
4076 4077
                      winfo->db_name, 
                      superTblInfo->childTblName + tbl_id * TSDB_TABLE_NAME_LEN);
4078 4079 4080
            }
          } else {  // pre-create child table
            if (0 == len) {
4081 4082
              len += snprintf(pstr + len, 
                      superTblInfo->maxSqlLen - len, 
4083
                      "insert into %s.%s%d values ",
4084 4085 4086
                      winfo->db_name, 
                      superTblInfo->childTblPrefix, 
                      tbl_id);
4087
            } else {
4088 4089
              len += snprintf(pstr + len, 
                      superTblInfo->maxSqlLen - len, 
4090
                      " %s.%s%d values ",
4091 4092 4093
                      winfo->db_name, 
                      superTblInfo->childTblPrefix, 
                      tbl_id);
4094 4095
            }            
          }
4096

4097
          start_time = time_counter;
4098
          for (int j = 0; j < superTblInfo->rowsPerTbl;) {
4099
            int retLen = 0;
4100 4101
            if (0 == strncasecmp(superTblInfo->dataSource, 
                        "sample", strlen("sample"))) {
4102 4103 4104 4105
              retLen = getRowDataFromSample(pstr + len,
                      superTblInfo->maxSqlLen - len,
                      start_time += superTblInfo->timeStampStep,
                      superTblInfo,
4106
                      &sampleUsePos);
4107 4108 4109
              if (retLen < 0) {
                goto free_and_statistics;
              }
4110 4111
            } else if (0 == strncasecmp(
                        superTblInfo->dataSource, "rand", strlen("rand"))) {
4112
              int rand_num = rand_tinyint() % 100;            
4113 4114
              if (0 != superTblInfo->disorderRatio 
                      && rand_num < superTblInfo->disorderRatio) {
4115
                int64_t d = start_time - rand() % superTblInfo->disorderRange;
4116 4117 4118
                retLen = generateRowData(pstr + len,
                        superTblInfo->maxSqlLen - len,
                        d,
4119
                        superTblInfo);
4120
              } else {
4121 4122
                retLen = generateRowData(pstr + len,
                        superTblInfo->maxSqlLen - len,
4123
                        start_time += superTblInfo->timeStampStep,
4124
                        superTblInfo);
4125 4126 4127 4128 4129 4130 4131
              }
              if (retLen < 0) {
                goto free_and_statistics;
              }
            }
            len += retLen;
            //inserted++;
4132
            j++;
4133
            winfo->totalInsertRows++;
4134

4135 4136
            if (inserted >= superTblInfo->insertRows || 
                    (superTblInfo->maxSqlLen - len) < (superTblInfo->lenOfOneRow + 128)) {
4137
              tableSeq = tbl_id + 1;
4138 4139
              printf("config rowsPerTbl and numberOfTblInOneSql not match with max_sql_lenth, please reconfig![lenOfOneRow:%d]\n", 
                      superTblInfo->lenOfOneRow);
4140 4141 4142 4143 4144
              goto send_to_server;
            }
          }
        }

4145
        tableSeq = tbl_id;
4146 4147
        inserted += superTblInfo->rowsPerTbl;

4148
send_to_server:
4149 4150
        if (insert_interval) {
            st = taosGetTimestampUs();
4151

4152 4153
          if (insert_interval > ((et - st)/1000)) {
            int sleep_time = insert_interval - (et -st);
4154
            printf("sleep: %d ms insert interval\n", sleep_time);
4155
            taosMsleep(sleep_time); // ms
4156
          }
4157 4158
        }

4159 4160 4161
        if (0 == strncasecmp(superTblInfo->insertMode, 
                    "taosc", 
                    strlen("taosc"))) {    
4162 4163
          //printf("multi table===== sql: %s \n\n", buffer);
          //int64_t t1 = taosGetTimestampMs();
4164 4165 4166 4167
          int64_t startTs;
          int64_t endTs;
          startTs = taosGetTimestampUs();

4168
          debugPrint("%s() LN%d buff: %s\n", __func__, __LINE__, buffer);
4169 4170
          int affectedRows = queryDbExec(
                  winfo->taos, buffer, INSERT_TYPE);
4171

4172
          if (0 < affectedRows) {
4173 4174 4175 4176 4177 4178
            endTs = taosGetTimestampUs();
            int64_t delay = endTs - startTs;
            if (delay > winfo->maxDelay) winfo->maxDelay = delay;
            if (delay < winfo->minDelay) winfo->minDelay = delay;
            winfo->cntDelay++;
            winfo->totalDelay += delay;
4179 4180
            winfo->avgDelay = (double)winfo->totalDelay / winfo->cntDelay;
            winfo->totalAffectedRows += affectedRows;
4181 4182 4183
          } else {
            fprintf(stderr, "queryDbExec() buffer:\n%s\naffected rows is %d", buffer, affectedRows);
            goto free_and_statistics;
4184
          }
4185 4186 4187

          int64_t  currentPrintTime = taosGetTimestampMs();
          if (currentPrintTime - lastPrintTime > 30*1000) {
4188 4189
            printf("thread[%d] has currently inserted rows: %"PRId64 ", affected rows: %"PRId64 "\n",
                    winfo->threadID,
4190
                    winfo->totalInsertRows,
4191
                    winfo->totalAffectedRows);
4192 4193 4194
            lastPrintTime = currentPrintTime;
          }
          //int64_t t2 = taosGetTimestampMs();          
4195
          //printf("taosc insert sql return, Spent %.4f seconds \n", (double)(t2 - t1)/1000.0); 
4196 4197
        } else {
          //int64_t t1 = taosGetTimestampMs();
4198
          int retCode = postProceSql(g_Dbs.host, g_Dbs.port, buffer);
4199 4200
          //int64_t t2 = taosGetTimestampMs();          
          //printf("http insert sql return, Spent %ld ms \n", t2 - t1);
4201

4202
          if (0 != retCode) {
4203
            printf("========restful return fail, threadID[%d]\n", winfo->threadID);
4204 4205 4206
            goto free_and_statistics;
          }
        }
4207 4208
        if (insert_interval) {
            et = taosGetTimestampUs();
4209 4210
        }

4211 4212 4213
        break;
      }

4214
      if (tableSeq > winfo->end_table_id) {
4215
        if (0 == strncasecmp(superTblInfo->dataSource, "sample", strlen("sample"))) {
4216 4217 4218
          samplePos = sampleUsePos;
        }
        i = inserted;
4219
        time_counter = start_time;
4220 4221 4222 4223
      }
    }   
    
    //printf("========loop %d childTables duration:%"PRId64 "========inserted rows:%d\n", winfo->end_table_id - winfo->start_table_id, et - st, i);
H
hzcheng 已提交
4224 4225
  }

4226
free_and_statistics:
4227
  tmfree(buffer);    
4228 4229
  printf("====thread[%d] completed total inserted rows: %"PRId64 ", affected rows: %"PRId64 "====\n",
          winfo->threadID, winfo->totalInsertRows, winfo->totalAffectedRows);
4230
  return;
H
hzcheng 已提交
4231 4232
}

4233
int32_t generateData(char *res, char **data_type,
4234
        int num_of_cols, int64_t timestamp, int lenOfBinary) {
4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268
  memset(res, 0, MAX_DATA_SIZE);
  char *pstr = res;
  pstr += sprintf(pstr, "(%" PRId64, timestamp);
  int c = 0;

  for (; c < MAX_NUM_DATATYPE; c++) {
    if (data_type[c] == NULL) {
      break;
    }
  }

  if (0 == c) {
    perror("data type error!");
    exit(-1);
  }

  for (int i = 0; i < num_of_cols; i++) {
    if (strcasecmp(data_type[i % c], "tinyint") == 0) {
      pstr += sprintf(pstr, ", %d", rand_tinyint() );
    } else if (strcasecmp(data_type[i % c], "smallint") == 0) {
      pstr += sprintf(pstr, ", %d", rand_smallint());
    } else if (strcasecmp(data_type[i % c], "int") == 0) {
      pstr += sprintf(pstr, ", %d", rand_int()); 
    } else if (strcasecmp(data_type[i % c], "bigint") == 0) {
      pstr += sprintf(pstr, ", %" PRId64, rand_bigint());
    } else if (strcasecmp(data_type[i % c], "float") == 0) {
      pstr += sprintf(pstr, ", %10.4f", rand_float());
    } else if (strcasecmp(data_type[i % c], "double") == 0) {
      double t = rand_double();
      pstr += sprintf(pstr, ", %20.8f", t);
    } else if (strcasecmp(data_type[i % c], "bool") == 0) {
      bool b = rand() & 1;
      pstr += sprintf(pstr, ", %s", b ? "true" : "false");
    } else if (strcasecmp(data_type[i % c], "binary") == 0) {
4269 4270
      char *s = malloc(lenOfBinary);
      rand_string(s, lenOfBinary);
4271 4272 4273
      pstr += sprintf(pstr, ", \"%s\"", s);
      free(s);
    }else if (strcasecmp(data_type[i % c], "nchar") == 0) {
4274 4275
      char *s = malloc(lenOfBinary);
      rand_string(s, lenOfBinary);
4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290
      pstr += sprintf(pstr, ", \"%s\"", s);
      free(s);
    }

    if (pstr - res > MAX_DATA_SIZE) {
      perror("column length too long, abort");
      exit(-1);
    }
  }

  pstr += sprintf(pstr, ")");

  return (int32_t)(pstr - res);
}

4291
static int prepareSampleDataForSTable(SSuperTable *superTblInfo) {
4292 4293 4294
  char* sampleDataBuf = NULL;

  // each thread read sample data from csv file 
4295 4296 4297 4298 4299
  if (0 == strncasecmp(superTblInfo->dataSource, 
              "sample", 
              strlen("sample"))) {
    sampleDataBuf = calloc(
            superTblInfo->lenOfOneRow * MAX_SAMPLES_ONCE_FROM_FILE, 1);
4300
    if (sampleDataBuf == NULL) {
4301
      fprintf(stderr, "Failed to calloc %d Bytes, reason:%s\n", 
4302 4303
              superTblInfo->lenOfOneRow * MAX_SAMPLES_ONCE_FROM_FILE, 
              strerror(errno));
4304
      return -1;
4305
    }
4306

4307
    int ret = readSampleFromCsvFileToMem(superTblInfo);
4308
    if (0 != ret) {
4309 4310
      tmfree(superTblInfo->sampleDataBuf);
      return -1;
4311
    }
H
Hui Li 已提交
4312
  }
4313

4314 4315 4316 4317 4318
  superTblInfo->sampleDataBuf = sampleDataBuf;

  return 0;
}

4319 4320 4321 4322 4323 4324
static int execInsert(threadInfo *winfo, char *buffer, int k)
{
  int affectedRows;
  SSuperTable* superTblInfo = winfo->superTblInfo;

  if (superTblInfo) {
4325
    if (0 == strncasecmp(superTblInfo->insertMode, "taosc", strlen("taosc"))) {
4326 4327
          verbosePrint("%s() LN%d %s\n", __func__, __LINE__, buffer);
          affectedRows = queryDbExec(winfo->taos, buffer, INSERT_TYPE);
4328
    } else {
4329 4330 4331 4332 4333 4334 4335 4336 4337
          verbosePrint("%s() LN%d %s\n", __func__, __LINE__, buffer);
          int retCode = postProceSql(g_Dbs.host, g_Dbs.port, buffer);

          if (0 != retCode) {
            affectedRows = -1;
            printf("========restful return fail, threadID[%d]\n", winfo->threadID);
          } else {
          affectedRows = k;
          }
4338
    }
4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350
  } else {
        verbosePrint("%s() LN%d %s\n", __func__, __LINE__, buffer);
        affectedRows = queryDbExec(winfo->taos, buffer, 1);
  }

  if (0 > affectedRows){
            return affectedRows;
  }

  return affectedRows;
}

4351 4352
static int generateDataBuffer(int32_t tableSeq,
        threadInfo *pThreadInfo, char *buffer,
4353 4354 4355 4356
        int64_t insertRows,
        int64_t startFrom, int64_t startTime, int *pSampleUsePos)
{
  SSuperTable* superTblInfo = pThreadInfo->superTblInfo;
4357

4358 4359
  int ncols_per_record = 1; // count first col ts

4360
  if (superTblInfo == NULL) {
4361 4362 4363 4364 4365
    int datatypeSeq = 0;
    while(g_args.datatype[datatypeSeq]) {
        datatypeSeq ++;
        ncols_per_record ++;
    }
4366 4367
  }

4368 4369
  assert(buffer != NULL);

4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389
  char *pChildTblName;
  int childTblCount;

  if (superTblInfo && (superTblInfo->childTblOffset > 0)) {
      // TODO
      // select tbname from stb limit 1 offset tableSeq
    getChildNameOfSuperTableWithLimitAndOffset(pThreadInfo->taos,
            pThreadInfo->db_name, superTblInfo->sTblName,
            &pChildTblName, &childTblCount,
            1, tableSeq);
  } else {
      pChildTblName = calloc(TSDB_TABLE_NAME_LEN, 1);
      if (NULL == pChildTblName) {
          fprintf(stderr, "failed to alloc memory %d\n", TSDB_TABLE_NAME_LEN);
          return -1;
      }
      snprintf(pChildTblName, TSDB_TABLE_NAME_LEN, "%s%d",
        superTblInfo?superTblInfo->childTblPrefix:g_args.tb_prefix, tableSeq);
  }

4390
  memset(buffer, 0, superTblInfo?superTblInfo->maxSqlLen:g_args.max_sql_len);
4391

4392
  char *pstr = buffer;
4393

4394 4395 4396 4397
  if (superTblInfo) {
    if (AUTO_CREATE_SUBTBL == superTblInfo->autoCreateTable) {
      char* tagsValBuf = NULL;
      if (0 == superTblInfo->tagSource) {
4398
            tagsValBuf = generateTagVaulesForStb(superTblInfo);
4399
      } else {
4400
            tagsValBuf = getTagValueFromTagSample(
4401
                    superTblInfo,
4402
                    tableSeq % superTblInfo->tagSampleCount);
4403 4404 4405
      }
      if (NULL == tagsValBuf) {
         fprintf(stderr, "tag buf failed to allocate  memory\n");
4406
         free(pChildTblName);
4407 4408
         return -1;
      }
4409

4410
      pstr += snprintf(pstr,
4411
                  superTblInfo->maxSqlLen,
4412
                  "insert into %s.%s using %s.%s tags %s values",
4413
                  pThreadInfo->db_name,
4414
                  pChildTblName,
4415
                  pThreadInfo->db_name,
4416
                  superTblInfo->sTblName,
4417
                  tagsValBuf);
4418 4419 4420
      tmfree(tagsValBuf);
    } else if (TBL_ALREADY_EXISTS == superTblInfo->childTblExists) {
      pstr += snprintf(pstr,
4421 4422
                  superTblInfo->maxSqlLen,
                  "insert into %s.%s values",
4423
                  pThreadInfo->db_name,
4424
                  superTblInfo->childTblName + tableSeq * TSDB_TABLE_NAME_LEN);
4425 4426
    } else {
      pstr += snprintf(pstr,
4427
                  (superTblInfo?superTblInfo->maxSqlLen:g_args.max_sql_len),
4428
                  "insert into %s.%s values",
4429
                  pThreadInfo->db_name,
4430
                  pChildTblName);
4431 4432 4433
    }
  } else {
      pstr += snprintf(pstr,
4434
                  (superTblInfo?superTblInfo->maxSqlLen:g_args.max_sql_len),
4435
                  "insert into %s.%s values",
4436
                  pThreadInfo->db_name,
4437
                  pChildTblName);
4438
  }
4439

4440 4441
  int k;
  int len = 0;
4442

4443 4444 4445
  verbosePrint("%s() LN%d num_of_RPR=%d\n", __func__, __LINE__, g_args.num_of_RPR);
  for (k = 0; k < g_args.num_of_RPR;) {
    if (superTblInfo) {
4446 4447
          int retLen = 0;

4448 4449 4450
        if (0 == strncasecmp(superTblInfo->dataSource,
                    "sample", strlen("sample"))) {
          retLen = getRowDataFromSample(
4451 4452
                    pstr + len, 
                    superTblInfo->maxSqlLen - len, 
4453
                    startTime + superTblInfo->timeStampStep * startFrom,
4454
                    superTblInfo, 
4455
                    pSampleUsePos);
4456 4457 4458 4459
       } else if (0 == strncasecmp(superTblInfo->dataSource,
                   "rand", strlen("rand"))) {
          int rand_num = rand_tinyint() % 100;
          if (0 != superTblInfo->disorderRatio 
4460
                    && rand_num < superTblInfo->disorderRatio) {
4461 4462
            int64_t d = startTime - rand() % superTblInfo->disorderRange;
            retLen = generateRowData(
4463
                      pstr + len, 
4464 4465
                      superTblInfo->maxSqlLen - len,
                      d, 
4466
                      superTblInfo);
4467
              //printf("disorder rows, rand_num:%d, last ts:%"PRId64" current ts:%"PRId64"\n", rand_num, start_time, d);
4468
        } else {
4469
          retLen = generateRowData(
4470 4471
                      pstr + len, 
                      superTblInfo->maxSqlLen - len, 
4472
                      startTime + superTblInfo->timeStampStep * startFrom,
4473
                      superTblInfo);
4474
        }
4475

4476
        if (retLen < 0) {
4477 4478
          free(pChildTblName);
          return -1;
4479
        }
4480

4481 4482 4483 4484
        len += retLen;
      }
    } else {
      int rand_num = rand() % 100;
4485 4486 4487 4488
          char data[MAX_DATA_SIZE];
          char **data_type = g_args.datatype;
          int lenOfBinary = g_args.len_of_binary;

4489
      if ((g_args.disorderRatio != 0)
4490 4491
                && (rand_num < g_args.disorderRange)) {
             
4492 4493
        int64_t d = startTime - rand() % 1000000 + rand_num;
        len = generateData(data, data_type,
4494
                  ncols_per_record, d, lenOfBinary);
4495
      } else {
4496
            len = generateData(data, data_type,
4497 4498 4499 4500
                  ncols_per_record,
                  startTime + DEFAULT_TIMESTAMP_STEP * startFrom,
                  lenOfBinary);
      }
4501

4502 4503
      //assert(len + pstr - buffer < BUFFER_SIZE);
      if (len + pstr - buffer >= g_args.max_sql_len) { // too long
4504
            break;
4505
      }
4506

4507 4508 4509 4510 4511 4512 4513
      pstr += sprintf(pstr, " %s", data);
    }

    verbosePrint("%s() LN%d len=%d k=%d \nbuffer=%s\n", __func__, __LINE__, len, k, buffer);

    k++;
    startFrom ++;
4514

4515 4516 4517
    if (startFrom >= insertRows)
      break;
  }
4518

4519 4520
  return k;
}
4521

4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536
// sync insertion
/*
   1 thread: 100 tables * 2000  rows/s
   1 thread: 10  tables * 20000 rows/s
   6 thread: 300 tables * 2000  rows/s

   2 taosinsertdata , 1 thread:  10  tables * 20000 rows/s
*/
static void* syncWrite(void *sarg) {

  threadInfo *winfo = (threadInfo *)sarg; 
  SSuperTable* superTblInfo = winfo->superTblInfo;


  if (superTblInfo) {
4537
    if (0 != prepareSampleDataForSTable(superTblInfo))
4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550
        return NULL;

    if (superTblInfo->numberOfTblInOneSql > 0) {
      syncWriteForNumberOfTblInOneSql(winfo, superTblInfo->sampleDataBuf);
      tmfree(superTblInfo->sampleDataBuf);
      return NULL;
    }
  }
 
  int   samplePos     = 0;

  char* buffer = calloc(superTblInfo?superTblInfo->maxSqlLen:g_args.max_sql_len, 1);
  if (NULL == buffer) {
4551
    fprintf(stderr, "Failed to alloc %d Bytes, reason:%s\n",
4552 4553 4554 4555 4556 4557 4558 4559 4560 4561
              superTblInfo->maxSqlLen,
              strerror(errno));
    tmfree(superTblInfo->sampleDataBuf);
    return NULL;
  }

  int64_t lastPrintTime = taosGetTimestampMs();
  int64_t startTs = taosGetTimestampUs();
  int64_t endTs;

4562 4563
  int insert_interval = superTblInfo?superTblInfo->insertInterval:
      g_args.insert_interval;
4564 4565 4566 4567 4568 4569 4570 4571
  uint64_t st = 0;
  uint64_t et = 0xffffffff;

  winfo->totalInsertRows = 0;
  winfo->totalAffectedRows = 0;

  int sampleUsePos;

4572 4573
  for (uint32_t tableSeq = winfo->start_table_id; tableSeq <= winfo->end_table_id;
        tableSeq ++) {
4574 4575 4576 4577 4578 4579 4580 4581
    int64_t start_time = winfo->start_time;

    int64_t insertRows = (superTblInfo)?superTblInfo->insertRows:g_args.num_of_DPT;
    verbosePrint("%s() LN%d insertRows=%"PRId64"\n", __func__, __LINE__, insertRows);

    for (int64_t i = 0; i < insertRows;) {
      if (insert_interval) {
            st = taosGetTimestampUs();
4582
      }
4583 4584 4585

      sampleUsePos = samplePos;

4586
      int generated = generateDataBuffer(tableSeq, winfo, buffer, insertRows,
4587 4588 4589 4590 4591 4592 4593
            i, start_time, &sampleUsePos);
      if (generated > 0)
        i += generated;
      else
        goto free_and_statistics_2;

      int affectedRows = execInsert(winfo, buffer, generated);
4594 4595
      if (affectedRows < 0)
        goto free_and_statistics_2;
4596

4597
      winfo->totalInsertRows += generated;
4598
      winfo->totalAffectedRows += affectedRows;
4599 4600 4601 4602 4603 4604 4605 4606 4607 4608

      endTs = taosGetTimestampUs();
      int64_t delay = endTs - startTs;
      if (delay > winfo->maxDelay) winfo->maxDelay = delay;
      if (delay < winfo->minDelay) winfo->minDelay = delay;
      winfo->cntDelay++;
      winfo->totalDelay += delay;

      int64_t  currentPrintTime = taosGetTimestampMs();
      if (currentPrintTime - lastPrintTime > 30*1000) {
4609 4610
        printf("thread[%d] has currently inserted rows: %"PRId64 ", affected rows: %"PRId64 "\n",
                    winfo->threadID,
4611
                    winfo->totalInsertRows,
4612 4613 4614 4615
                    winfo->totalAffectedRows);
        lastPrintTime = currentPrintTime;
      }

4616
      if (i >= insertRows)
4617
        break;
4618 4619 4620 4621 4622 4623

      if (insert_interval) {
        et = taosGetTimestampUs();

        if (insert_interval > ((et - st)/1000) ) {
            int sleep_time = insert_interval - (et -st)/1000;
4624
            verbosePrint("%s() LN%d sleep: %d ms for insert interval\n", __func__, __LINE__, sleep_time);
4625 4626
            taosMsleep(sleep_time); // ms
        }
4627 4628 4629
      }
    }   // num_of_DPT

4630
    if ((tableSeq == winfo->end_table_id) && superTblInfo &&
4631 4632
        (0 == strncasecmp(
                    superTblInfo->dataSource, "sample", strlen("sample")))) {
4633
          samplePos = sampleUsePos;
4634
    }
4635
  } // tableSeq
4636

4637
free_and_statistics_2:
4638
  tmfree(buffer);
4639 4640
  if (superTblInfo)
    tmfree(superTblInfo->sampleDataBuf);
4641

4642 4643
  printf("====thread[%d] completed total inserted rows: %"PRId64 ", total affected rows: %"PRId64 "====\n", 
          winfo->threadID, 
4644
          winfo->totalInsertRows, 
4645
          winfo->totalAffectedRows);
4646
  return NULL;
H
Hui Li 已提交
4647 4648
}

4649 4650
void callBack(void *param, TAOS_RES *res, int code) {
  threadInfo* winfo = (threadInfo*)param; 
4651
  SSuperTable* superTblInfo = winfo->superTblInfo;
4652

4653 4654 4655 4656 4657
  int insert_interval = superTblInfo?superTblInfo->insertInterval:g_args.insert_interval;
  if (insert_interval) {
    winfo->et = taosGetTimestampUs();
    if (((winfo->et - winfo->st)/1000) < insert_interval) {
      taosMsleep(insert_interval - (winfo->et - winfo->st)/1000); // ms
4658
    }
H
Hui Li 已提交
4659 4660
  }
  
4661 4662 4663 4664
  char *buffer = calloc(1, winfo->superTblInfo->maxSqlLen);
  char *data   = calloc(1, MAX_DATA_SIZE);
  char *pstr = buffer;
  pstr += sprintf(pstr, "insert into %s.%s%d values", winfo->db_name, winfo->tb_prefix, winfo->start_table_id);
4665
//  if (winfo->counter >= winfo->superTblInfo->insertRows) {
4666
  if (winfo->counter >= g_args.num_of_RPR) {
4667 4668 4669 4670 4671 4672 4673 4674 4675 4676
    winfo->start_table_id++;
    winfo->counter = 0;
  }
  if (winfo->start_table_id > winfo->end_table_id) {
    tsem_post(&winfo->lock_sem);
    free(buffer);
    free(data);
    taos_free_result(res);
    return;
  }
H
Hui Li 已提交
4677
  
4678
  for (int i = 0; i < g_args.num_of_RPR; i++) {
4679 4680 4681 4682 4683 4684 4685
    int rand_num = rand() % 100;
    if (0 != winfo->superTblInfo->disorderRatio && rand_num < winfo->superTblInfo->disorderRatio)
    {
      int64_t d = winfo->lastTs - rand() % 1000000 + rand_num;
      //generateData(data, datatype, ncols_per_record, d, len_of_binary);
      (void)generateRowData(data, MAX_DATA_SIZE, d, winfo->superTblInfo);
    } else {
4686
      //generateData(data, datatype, ncols_per_record, start_time += 1000, len_of_binary);
4687
      (void)generateRowData(data, MAX_DATA_SIZE, winfo->lastTs += 1000, winfo->superTblInfo);
H
Hui Li 已提交
4688
    }
4689 4690
    pstr += sprintf(pstr, "%s", data);
    winfo->counter++;
H
Hui Li 已提交
4691

4692 4693
    if (winfo->counter >= winfo->superTblInfo->insertRows) {
      break;
H
Hui Li 已提交
4694 4695
    }
  }
4696
  
4697 4698
  if (insert_interval) {
    winfo->st = taosGetTimestampUs();
4699 4700 4701 4702
  }
  taos_query_a(winfo->taos, buffer, callBack, winfo);
  free(buffer);
  free(data);
H
Hui Li 已提交
4703

4704
  taos_free_result(res);
H
Hui Li 已提交
4705 4706
}

4707 4708
void *asyncWrite(void *sarg) {
  threadInfo *winfo = (threadInfo *)sarg;
4709
  SSuperTable* superTblInfo = winfo->superTblInfo;
4710 4711 4712 4713 4714

  winfo->st = 0;
  winfo->et = 0;
  winfo->lastTs = winfo->start_time;
  
4715 4716 4717
  int insert_interval = superTblInfo?superTblInfo->insertInterval:g_args.insert_interval;
  if (insert_interval) {
    winfo->st = taosGetTimestampUs();
H
Hui Li 已提交
4718
  }
4719 4720 4721
  taos_query_a(winfo->taos, "show databases", callBack, winfo);

  tsem_wait(&(winfo->lock_sem));
H
Hui Li 已提交
4722 4723 4724 4725

  return NULL;
}

4726 4727
static void startMultiThreadInsertData(int threads, char* db_name,
        char* precision,SSuperTable* superTblInfo) {
4728 4729

    pthread_t *pids = malloc(threads * sizeof(pthread_t));
4730 4731
    assert(pids != NULL);

4732
    threadInfo *infos = malloc(threads * sizeof(threadInfo));
4733 4734
    assert(infos != NULL);

4735 4736
    memset(pids, 0, threads * sizeof(pthread_t));
    memset(infos, 0, threads * sizeof(threadInfo));
H
Hui Li 已提交
4737

4738 4739
    int ntables = 0;
    if (superTblInfo)
4740 4741 4742 4743
        if (superTblInfo->childTblOffset)
            ntables = superTblInfo->childTblLimit;
        else
            ntables = superTblInfo->childTblCount;
4744 4745
    else
        ntables = g_args.num_of_tables;
H
Hui Li 已提交
4746

4747 4748 4749 4750 4751 4752 4753 4754 4755 4756
    int a = ntables / threads;
    if (a < 1) {
        threads = ntables;
        a = 1;
    }

    int b = 0;
    if (threads != 0) {
        b = ntables % threads;
    }
4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773

  //TAOS* taos;
  //if (0 == strncasecmp(superTblInfo->insertMode, "taosc", 5)) {
  //  taos = taos_connect(g_Dbs.host, g_Dbs.user, g_Dbs.password, db_name, g_Dbs.port);
  //  if (NULL == taos) {
  //    printf("connect to server fail, reason: %s\n", taos_errstr(NULL));
  //    exit(-1);
  //  }
  //}

  int32_t timePrec = TSDB_TIME_PRECISION_MILLI;
  if (0 != precision[0]) {
    if (0 == strncasecmp(precision, "ms", 2)) {
      timePrec = TSDB_TIME_PRECISION_MILLI;
    }  else if (0 == strncasecmp(precision, "us", 2)) {
      timePrec = TSDB_TIME_PRECISION_MICRO;
    }  else {
4774
      fprintf(stderr, "No support precision: %s\n", precision);
4775 4776 4777 4778
      exit(-1);
    }
  }

4779 4780 4781 4782
  int64_t start_time; 
  if (superTblInfo) {
    if (0 == strncasecmp(superTblInfo->startTimestamp, "now", 3)) {
        start_time = taosGetTimestamp(timePrec);
4783
    } else {
4784
        if (TSDB_CODE_SUCCESS != taosParseTime(
4785 4786 4787
            superTblInfo->startTimestamp,
            &start_time,
            strlen(superTblInfo->startTimestamp),
4788 4789 4790 4791
            timePrec, 0)) {
            printf("ERROR to parse time!\n");
            exit(-1);
        }
4792 4793 4794
    }
  } else {
     start_time = 1500000000000;
4795 4796 4797
  }

  double start = getCurrentTime();
4798
 
4799 4800 4801 4802 4803 4804 4805
  int last;

  if ((superTblInfo) && (superTblInfo->childTblOffset))
      last = superTblInfo->childTblOffset;
  else
      last = 0;

H
Hui Li 已提交
4806
  for (int i = 0; i < threads; i++) {
4807
    threadInfo *t_info = infos + i;
H
Hui Li 已提交
4808 4809
    t_info->threadID = i;
    tstrncpy(t_info->db_name, db_name, MAX_DB_NAME_SIZE);
4810 4811 4812
    t_info->superTblInfo = superTblInfo;

    t_info->start_time = start_time;
4813
    t_info->minDelay = INT16_MAX;
4814

4815 4816
    if ((NULL == superTblInfo) ||
            (0 == strncasecmp(superTblInfo->insertMode, "taosc", 5))) {
4817
      //t_info->taos = taos;
4818
      t_info->taos = taos_connect(
4819
              g_Dbs.host, g_Dbs.user,
4820
              g_Dbs.password, db_name, g_Dbs.port);
4821
      if (NULL == t_info->taos) {
4822 4823
        printf("connect to server fail from insert sub thread, reason: %s\n",
                taos_errstr(NULL));
4824 4825 4826 4827 4828 4829
        exit(-1);
      }
    } else {
      t_info->taos = NULL;
    }

4830 4831
    if ((NULL == superTblInfo)
            || (0 == superTblInfo->multiThreadWriteOneTbl)) {
4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842
      t_info->start_table_id = last;
      t_info->end_table_id = i < b ? last + a : last + a - 1;
      last = t_info->end_table_id + 1;
    } else {
      t_info->start_table_id = 0;
      t_info->end_table_id = superTblInfo->childTblCount - 1;
      t_info->start_time = t_info->start_time + rand_int() % 10000 - rand_tinyint();
    }

    tsem_init(&(t_info->lock_sem), 0, 0);
    if (SYNC == g_Dbs.queryMode) {
4843
      pthread_create(pids + i, NULL, syncWrite, t_info);
4844
    } else {
4845 4846
      pthread_create(pids + i, NULL, asyncWrite, t_info);
    }
H
Hui Li 已提交
4847
  }
4848

H
Hui Li 已提交
4849 4850 4851 4852
  for (int i = 0; i < threads; i++) {
    pthread_join(pids[i], NULL);
  }

4853 4854 4855
  int64_t totalDelay = 0;
  int64_t maxDelay = 0;
  int64_t minDelay = INT16_MAX;
4856
  int64_t cntDelay = 1;
4857 4858
  double  avgDelay = 0;

H
Hui Li 已提交
4859
  for (int i = 0; i < threads; i++) {
4860 4861
    threadInfo *t_info = infos + i;

S
TD-1057  
Shengliang Guan 已提交
4862
    tsem_destroy(&(t_info->lock_sem));
4863 4864
    taos_close(t_info->taos);

4865 4866
    if (superTblInfo) {
        superTblInfo->totalAffectedRows += t_info->totalAffectedRows;
4867
        superTblInfo->totalInsertRows += t_info->totalInsertRows;
4868
    }
4869 4870 4871 4872

    totalDelay  += t_info->totalDelay;
    cntDelay   += t_info->cntDelay;
    if (t_info->maxDelay > maxDelay) maxDelay = t_info->maxDelay;
4873
    if (t_info->minDelay < minDelay) minDelay = t_info->minDelay;
H
Hui Li 已提交
4874
  }
4875
  cntDelay -= 1;
H
Hui Li 已提交
4876

4877
  if (cntDelay == 0)    cntDelay = 1;
4878 4879
  avgDelay = (double)totalDelay / cntDelay;

4880
  double end = getCurrentTime();
4881
  double t = end - start;
4882 4883

  if (superTblInfo) {
4884
    printf("Spent %.4f seconds to insert rows: %"PRId64", affected rows: %"PRId64" with %d thread(s) into %s.%s. %2.f records/second\n\n",
4885
          t, superTblInfo->totalInsertRows,
4886 4887
          superTblInfo->totalAffectedRows,
          threads, db_name, superTblInfo->sTblName,
4888
          superTblInfo->totalInsertRows / t);
4889
    fprintf(g_fpOfInsertResult,
4890
          "Spent %.4f seconds to insert rows: %"PRId64", affected rows: %"PRId64" with %d thread(s) into %s.%s. %2.f records/second\n\n",
4891
          t, superTblInfo->totalInsertRows,
4892 4893
          superTblInfo->totalAffectedRows,
          threads, db_name, superTblInfo->sTblName,
4894
          superTblInfo->totalInsertRows/ t);
4895
  }
4896 4897 4898 4899 4900

  printf("insert delay, avg: %10.6fms, max: %10.6fms, min: %10.6fms\n\n",
          avgDelay/1000.0, (double)maxDelay/1000.0, (double)minDelay/1000.0);
  fprintf(g_fpOfInsertResult, "insert delay, avg:%10.6fms, max: %10.6fms, min: %10.6fms\n\n",
          avgDelay/1000.0, (double)maxDelay/1000.0, (double)minDelay/1000.0);
4901 4902 4903
  
  //taos_close(taos);

H
Hui Li 已提交
4904
  free(pids);
4905
  free(infos);
H
Hui Li 已提交
4906 4907
}

H
hzcheng 已提交
4908
void *readTable(void *sarg) {
4909 4910
#if 1  
  threadInfo *rinfo = (threadInfo *)sarg;
H
hzcheng 已提交
4911 4912
  TAOS *taos = rinfo->taos;
  char command[BUFFER_SIZE] = "\0";
4913
  uint64_t sTime = rinfo->start_time;
H
hzcheng 已提交
4914 4915
  char *tb_prefix = rinfo->tb_prefix;
  FILE *fp = fopen(rinfo->fp, "a");
H
Hui Li 已提交
4916 4917 4918 4919
  if (NULL == fp) {
    printf("fopen %s fail, reason:%s.\n", rinfo->fp, strerror(errno));
    return NULL;
  }
4920

4921
    int num_of_DPT;
4922
/*  if (rinfo->superTblInfo) {
4923 4924
    num_of_DPT = rinfo->superTblInfo->insertRows; //  nrecords_per_table;
  } else {
4925
  */
4926
      num_of_DPT = g_args.num_of_DPT;
4927
//  }
4928

H
hzcheng 已提交
4929 4930
  int num_of_tables = rinfo->end_table_id - rinfo->start_table_id + 1;
  int totalData = num_of_DPT * num_of_tables;
4931
  bool do_aggreFunc = g_Dbs.do_aggreFunc;
H
hzcheng 已提交
4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943

  int n = do_aggreFunc ? (sizeof(aggreFunc) / sizeof(aggreFunc[0])) : 2;
  if (!do_aggreFunc) {
    printf("\nThe first field is either Binary or Bool. Aggregation functions are not supported.\n");
  }
  printf("%d records:\n", totalData);
  fprintf(fp, "| QFunctions |    QRecords    |   QSpeed(R/s)   |  QLatency(ms) |\n");

  for (int j = 0; j < n; j++) {
    double totalT = 0;
    int count = 0;
    for (int i = 0; i < num_of_tables; i++) {
L
lihui 已提交
4944
      sprintf(command, "select %s from %s%d where ts>= %" PRId64, aggreFunc[j], tb_prefix, i, sTime);
H
hzcheng 已提交
4945 4946

      double t = getCurrentTime();
S
Shuaiqiang Chang 已提交
4947 4948
      TAOS_RES *pSql = taos_query(taos, command);
      int32_t code = taos_errno(pSql);
H
hzcheng 已提交
4949

S
Shuaiqiang Chang 已提交
4950
      if (code != 0) {
H
Haojun Liao 已提交
4951
        fprintf(stderr, "Failed to query:%s\n", taos_errstr(pSql));
S
Shuaiqiang Chang 已提交
4952
        taos_free_result(pSql);
H
hzcheng 已提交
4953
        taos_close(taos);
4954
        fclose(fp);
4955
        return NULL;
H
hzcheng 已提交
4956 4957
      }

S
Shuaiqiang Chang 已提交
4958
      while (taos_fetch_row(pSql) != NULL) {
H
hzcheng 已提交
4959 4960 4961 4962 4963 4964
        count++;
      }

      t = getCurrentTime() - t;
      totalT += t;

S
Shuaiqiang Chang 已提交
4965
      taos_free_result(pSql);
H
hzcheng 已提交
4966 4967 4968
    }

    fprintf(fp, "|%10s  |   %10d   |  %12.2f   |   %10.2f  |\n",
S
slguan 已提交
4969
            aggreFunc[j][0] == '*' ? "   *   " : aggreFunc[j], totalData,
H
hzcheng 已提交
4970 4971 4972 4973 4974
            (double)(num_of_tables * num_of_DPT) / totalT, totalT * 1000);
    printf("select %10s took %.6f second(s)\n", aggreFunc[j], totalT);
  }
  fprintf(fp, "\n");
  fclose(fp);
4975
#endif
H
hzcheng 已提交
4976 4977 4978 4979
  return NULL;
}

void *readMetric(void *sarg) {
4980 4981
#if 1  
  threadInfo *rinfo = (threadInfo *)sarg;
H
hzcheng 已提交
4982 4983 4984
  TAOS *taos = rinfo->taos;
  char command[BUFFER_SIZE] = "\0";
  FILE *fp = fopen(rinfo->fp, "a");
H
Hui Li 已提交
4985 4986 4987 4988
  if (NULL == fp) {
    printf("fopen %s fail, reason:%s.\n", rinfo->fp, strerror(errno));
    return NULL;
  }
4989 4990

  int num_of_DPT = rinfo->superTblInfo->insertRows;
H
hzcheng 已提交
4991 4992
  int num_of_tables = rinfo->end_table_id - rinfo->start_table_id + 1;
  int totalData = num_of_DPT * num_of_tables;
4993
  bool do_aggreFunc = g_Dbs.do_aggreFunc;
H
hzcheng 已提交
4994 4995 4996 4997 4998 4999 5000 5001 5002

  int n = do_aggreFunc ? (sizeof(aggreFunc) / sizeof(aggreFunc[0])) : 2;
  if (!do_aggreFunc) {
    printf("\nThe first field is either Binary or Bool. Aggregation functions are not supported.\n");
  }
  printf("%d records:\n", totalData);
  fprintf(fp, "Querying On %d records:\n", totalData);

  for (int j = 0; j < n; j++) {
sangshuduo's avatar
sangshuduo 已提交
5003
    char condition[BUFFER_SIZE - 30] = "\0";
B
Bomin Zhang 已提交
5004
    char tempS[64] = "\0";
H
hzcheng 已提交
5005 5006 5007 5008 5009

    int m = 10 < num_of_tables ? 10 : num_of_tables;

    for (int i = 1; i <= m; i++) {
      if (i == 1) {
5010
        sprintf(tempS, "t1 = %d", i);
H
hzcheng 已提交
5011
      } else {
5012
        sprintf(tempS, " or t1 = %d ", i);
H
hzcheng 已提交
5013 5014 5015
      }
      strcat(condition, tempS);

L
liu0x54 已提交
5016
      sprintf(command, "select %s from meters where %s", aggreFunc[j], condition);
H
hzcheng 已提交
5017 5018 5019 5020 5021 5022

      printf("Where condition: %s\n", condition);
      fprintf(fp, "%s\n", command);

      double t = getCurrentTime();

S
Shuaiqiang Chang 已提交
5023 5024 5025 5026
      TAOS_RES *pSql = taos_query(taos, command);
      int32_t code = taos_errno(pSql);

      if (code != 0) {
H
Haojun Liao 已提交
5027
        fprintf(stderr, "Failed to query:%s\n", taos_errstr(pSql));
S
Shuaiqiang Chang 已提交
5028
        taos_free_result(pSql);
H
hzcheng 已提交
5029
        taos_close(taos);
5030
        fclose(fp);
5031
        return NULL;
H
hzcheng 已提交
5032 5033
      }
      int count = 0;
S
Shuaiqiang Chang 已提交
5034
      while (taos_fetch_row(pSql) != NULL) {
H
hzcheng 已提交
5035 5036 5037 5038 5039 5040 5041
        count++;
      }
      t = getCurrentTime() - t;

      fprintf(fp, "| Speed: %12.2f(per s) | Latency: %.4f(ms) |\n", num_of_tables * num_of_DPT / t, t * 1000);
      printf("select %10s took %.6f second(s)\n\n", aggreFunc[j], t);

S
Shuaiqiang Chang 已提交
5042
      taos_free_result(pSql);
H
hzcheng 已提交
5043 5044 5045 5046
    }
    fprintf(fp, "\n");
  }
  fclose(fp);
5047
#endif
H
hzcheng 已提交
5048 5049 5050
  return NULL;
}

H
Hui Li 已提交
5051

5052
static int insertTestProcess() {
5053

5054 5055 5056
  setupForAnsiEscape();
  int ret = printfInsertMeta();
  resetAfterAnsiEscape();
5057

5058 5059 5060
  if (ret == -1)
    exit(EXIT_FAILURE);

5061
  debugPrint("%d result file: %s\n", __LINE__, g_Dbs.resultFile);
5062 5063 5064 5065 5066
  g_fpOfInsertResult = fopen(g_Dbs.resultFile, "a");
  if (NULL == g_fpOfInsertResult) {
    fprintf(stderr, "Failed to open %s for save result\n", g_Dbs.resultFile);
    return -1;
  }
5067

5068 5069
  printfInsertMetaToFile(g_fpOfInsertResult);

5070 5071 5072 5073
  if (!g_args.answer_yes) {
    printf("Press enter key to continue\n\n");
    (void)getchar();
  }
5074
 
5075 5076 5077
  init_rand_data();

  // create database and super tables
5078
  if(createDatabases() != 0) {
5079 5080 5081
    fclose(g_fpOfInsertResult);
    return -1;
  }
5082 5083

  // pretreatement
5084
  prepareSampleData();
5085

5086 5087 5088 5089 5090 5091 5092
  double start;
  double end;

  // create child tables
  start = getCurrentTime();
  createChildTables();
  end = getCurrentTime();
5093

5094
  if (g_totalChildTables > 0) {
5095
    printf("Spent %.4f seconds to create %d tables with %d thread(s)\n\n",
5096
            end - start, g_totalChildTables, g_Dbs.threadCount);
5097 5098
    fprintf(g_fpOfInsertResult,
            "Spent %.4f seconds to create %d tables with %d thread(s)\n\n",
5099
            end - start, g_totalChildTables, g_Dbs.threadCount);
5100
  }
5101

5102
  taosMsleep(1000);
5103 5104
  // create sub threads for inserting data
  //start = getCurrentTime();
5105 5106 5107 5108 5109 5110
  for (int i = 0; i < g_Dbs.dbCount; i++) {
    if (g_Dbs.db[i].superTblCount > 0) {
      for (int j = 0; j < g_Dbs.db[i].superTblCount; j++) {
        SSuperTable* superTblInfo = &g_Dbs.db[i].superTbls[j];
        if (0 == g_Dbs.db[i].superTbls[j].insertRows) {
          continue;
5111
        }
5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123
        startMultiThreadInsertData(
          g_Dbs.threadCount, 
          g_Dbs.db[i].dbName, 
          g_Dbs.db[i].dbCfg.precision, 
          superTblInfo);
        }
    } else {
        startMultiThreadInsertData(
          g_Dbs.threadCount, 
          g_Dbs.db[i].dbName, 
          g_Dbs.db[i].dbCfg.precision, 
          NULL);
H
Hui Li 已提交
5124
    }
5125
  }
5126
  //end = getCurrentTime();
5127

5128
  //int64_t    totalInsertRows = 0;
5129 5130 5131
  //int64_t    totalAffectedRows = 0;
  //for (int i = 0; i < g_Dbs.dbCount; i++) {    
  //  for (int j = 0; j < g_Dbs.db[i].superTblCount; j++) {
5132
  //  totalInsertRows+= g_Dbs.db[i].superTbls[j].totalInsertRows;
5133 5134
  //  totalAffectedRows += g_Dbs.db[i].superTbls[j].totalAffectedRows;
  //}
5135
  //printf("Spent %.4f seconds to insert rows: %"PRId64", affected rows: %"PRId64" with %d thread(s)\n\n", end - start, totalInsertRows, totalAffectedRows, g_Dbs.threadCount);
5136
  postFreeResource();
5137

5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150
  return 0;
}

void *superQueryProcess(void *sarg) {
  threadInfo *winfo = (threadInfo *)sarg; 

  //char sqlStr[MAX_TB_NAME_SIZE*2];
  //sprintf(sqlStr, "use %s", g_queryInfo.dbName);
  //queryDB(winfo->taos, sqlStr);
  
  int64_t st = 0;
  int64_t et = 0;
  while (1) {
5151
    if (g_queryInfo.superQueryInfo.rate && (et - st) < (int64_t)g_queryInfo.superQueryInfo.rate*1000) {
5152 5153 5154 5155
      taosMsleep(g_queryInfo.superQueryInfo.rate*1000 - (et - st)); // ms
      //printf("========sleep duration:%"PRId64 "========inserted rows:%d, table range:%d - %d\n", (1000 - (et - st)), i, winfo->start_table_id, winfo->end_table_id);
    }

5156
    st = taosGetTimestampUs();
5157 5158 5159 5160 5161 5162 5163 5164 5165
    for (int i = 0; i < g_queryInfo.superQueryInfo.sqlCount; i++) {
      if (0 == strncasecmp(g_queryInfo.queryMode, "taosc", 5)) {          
        int64_t t1 = taosGetTimestampUs();
        char tmpFile[MAX_FILE_NAME_LEN*2] = {0};
        if (g_queryInfo.superQueryInfo.result[i][0] != 0) {
          sprintf(tmpFile, "%s-%d", g_queryInfo.superQueryInfo.result[i], winfo->threadID);
        }
        selectAndGetResult(winfo->taos, g_queryInfo.superQueryInfo.sql[i], tmpFile); 
        int64_t t2 = taosGetTimestampUs();          
5166 5167
        printf("=[taosc] thread[%"PRId64"] complete one sql, Spent %f s\n", 
                taosGetSelfPthreadId(), (t2 - t1)/1000000.0);
5168 5169
      } else {
        int64_t t1 = taosGetTimestampUs();
5170 5171
        int retCode = postProceSql(g_queryInfo.host, 
                g_queryInfo.port, g_queryInfo.superQueryInfo.sql[i]);
5172
        int64_t t2 = taosGetTimestampUs();          
5173 5174
        printf("=[restful] thread[%"PRId64"] complete one sql, Spent %f s\n", 
                taosGetSelfPthreadId(), (t2 - t1)/1000000.0);
5175 5176
        
        if (0 != retCode) {
5177
          printf("====restful return fail, threadID[%d]\n", winfo->threadID);
5178 5179 5180 5181
          return NULL;
        }
      }   
    }
5182
    et = taosGetTimestampUs();
5183 5184
    printf("==thread[%"PRId64"] complete all sqls to specify tables once queries duration:%.6fs\n\n", 
            taosGetSelfPthreadId(), (double)(et - st)/1000.0);
H
Hui Li 已提交
5185
  }
5186 5187
  return NULL;
}
H
Hui Li 已提交
5188

5189
static void replaceSubTblName(char* inSql, char* outSql, int tblIndex) {
5190 5191
  char sourceString[32] = "xxxx";
  char subTblName[MAX_TB_NAME_SIZE*3];
5192 5193 5194
  sprintf(subTblName, "%s.%s", 
          g_queryInfo.dbName, 
          g_queryInfo.subQueryInfo.childTblName + tblIndex*TSDB_TABLE_NAME_LEN);
5195 5196 5197 5198 5199 5200

  //printf("inSql: %s\n", inSql);
  
  char* pos = strstr(inSql, sourceString);
  if (0 == pos) {
    return; 
H
Hui Li 已提交
5201 5202
  }
  
5203
  tstrncpy(outSql, inSql, pos - inSql + 1);
5204 5205 5206 5207 5208
  //printf("1: %s\n", outSql);
  strcat(outSql, subTblName);  
  //printf("2: %s\n", outSql);  
  strcat(outSql, pos+strlen(sourceString));  
  //printf("3: %s\n", outSql); 
H
Hui Li 已提交
5209 5210
}

5211
static void *subQueryProcess(void *sarg) {
5212 5213 5214
  char sqlstr[1024];
  threadInfo *winfo = (threadInfo *)sarg; 
  int64_t st = 0;
5215
  int64_t et = (int64_t)g_queryInfo.subQueryInfo.rate*1000;
5216
  while (1) {
5217
    if (g_queryInfo.subQueryInfo.rate && (et - st) < (int64_t)g_queryInfo.subQueryInfo.rate*1000) {
5218 5219 5220
      taosMsleep(g_queryInfo.subQueryInfo.rate*1000 - (et - st)); // ms
      //printf("========sleep duration:%"PRId64 "========inserted rows:%d, table range:%d - %d\n", (1000 - (et - st)), i, winfo->start_table_id, winfo->end_table_id);
    }
H
Hui Li 已提交
5221

5222
    st = taosGetTimestampUs();
5223
    for (int i = winfo->start_table_id; i <= winfo->end_table_id; i++) {
5224
      for (int j = 0; j < g_queryInfo.subQueryInfo.sqlCount; j++) {
5225
        memset(sqlstr,0,sizeof(sqlstr));
5226
        replaceSubTblName(g_queryInfo.subQueryInfo.sql[j], sqlstr, i);
5227 5228
        char tmpFile[MAX_FILE_NAME_LEN*2] = {0};
        if (g_queryInfo.subQueryInfo.result[i][0] != 0) {
5229 5230 5231
          sprintf(tmpFile, "%s-%d", 
                  g_queryInfo.subQueryInfo.result[i], 
                  winfo->threadID);
5232 5233 5234
        }
        selectAndGetResult(winfo->taos, sqlstr, tmpFile); 
      }
H
Hui Li 已提交
5235
    }
5236
    et = taosGetTimestampUs();
5237 5238 5239 5240
    printf("####thread[%"PRId64"] complete all sqls to allocate all sub-tables[%d - %d] once queries duration:%.4fs\n\n", 
            taosGetSelfPthreadId(), 
            winfo->start_table_id, 
            winfo->end_table_id, 
5241
            (double)(et - st)/1000000.0);
5242 5243 5244 5245
  }
  return NULL;
}

5246
static int queryTestProcess() {
5247
  TAOS * taos = NULL;  
5248 5249 5250 5251 5252
  taos = taos_connect(g_queryInfo.host, 
          g_queryInfo.user, 
          g_queryInfo.password, 
          NULL, 
          g_queryInfo.port);
5253 5254 5255 5256 5257 5258
  if (taos == NULL) {
    fprintf(stderr, "Failed to connect to TDengine, reason:%s\n", taos_errstr(NULL));
    exit(-1);
  }

  if (0 != g_queryInfo.subQueryInfo.sqlCount) {
5259 5260 5261 5262
    getAllChildNameOfSuperTable(taos,
            g_queryInfo.dbName,
            g_queryInfo.subQueryInfo.sTblName,
            &g_queryInfo.subQueryInfo.childTblName,
5263
            &g_queryInfo.subQueryInfo.childTblCount);
5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278
  }  
  
  printfQueryMeta();
  
  if (!g_args.answer_yes) {
    printf("Press enter key to continue\n\n");
    (void)getchar();
  }
  
  printfQuerySystemInfo(taos);
  
  pthread_t  *pids  = NULL;
  threadInfo *infos = NULL;
  //==== create sub threads for query from specify table
  if (g_queryInfo.superQueryInfo.sqlCount > 0 && g_queryInfo.superQueryInfo.concurrent > 0) {
5279

5280 5281 5282 5283 5284 5285 5286
    pids  = malloc(g_queryInfo.superQueryInfo.concurrent * sizeof(pthread_t));
    infos = malloc(g_queryInfo.superQueryInfo.concurrent * sizeof(threadInfo));
    if ((NULL == pids) || (NULL == infos)) {
      printf("malloc failed for create threads\n");
      taos_close(taos);
      exit(-1);
    }
5287 5288

    for (int i = 0; i < g_queryInfo.superQueryInfo.concurrent; i++) {
5289
      threadInfo *t_info = infos + i;
5290
      t_info->threadID = i;
5291 5292 5293
  
      if (0 == strncasecmp(g_queryInfo.queryMode, "taosc", 5)) {
        t_info->taos = taos;
5294

5295 5296
        char sqlStr[MAX_TB_NAME_SIZE*2];
        sprintf(sqlStr, "use %s", g_queryInfo.dbName);
5297
        verbosePrint("%s() %d sqlStr: %s\n", __func__, __LINE__, sqlStr);
5298 5299 5300 5301 5302
        (void)queryDbExec(t_info->taos, sqlStr, NO_INSERT_TYPE);
      } else {
        t_info->taos = NULL;
      }
  
5303 5304
      pthread_create(pids + i, NULL, superQueryProcess, t_info);
    }
5305 5306 5307
  }else {
    g_queryInfo.superQueryInfo.concurrent = 0;
  }
5308

5309 5310 5311
  pthread_t  *pidsOfSub  = NULL;
  threadInfo *infosOfSub = NULL;
  //==== create sub threads for query from all sub table of the super table
5312 5313
  if ((g_queryInfo.subQueryInfo.sqlCount > 0)
          && (g_queryInfo.subQueryInfo.threadCnt > 0)) {
5314 5315 5316 5317 5318 5319 5320
    pidsOfSub  = malloc(g_queryInfo.subQueryInfo.threadCnt * sizeof(pthread_t));
    infosOfSub = malloc(g_queryInfo.subQueryInfo.threadCnt * sizeof(threadInfo));
    if ((NULL == pidsOfSub) || (NULL == infosOfSub)) {
      printf("malloc failed for create threads\n");
      taos_close(taos);
      exit(-1);
    }
5321

5322 5323 5324 5325 5326 5327 5328 5329
    int ntables = g_queryInfo.subQueryInfo.childTblCount;
    int threads = g_queryInfo.subQueryInfo.threadCnt;
  
    int a = ntables / threads;
    if (a < 1) {
      threads = ntables;
      a = 1;
    }
5330
 
5331 5332 5333 5334
    int b = 0;
    if (threads != 0) {
      b = ntables % threads;
    }
5335

5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354
    int last = 0;
    for (int i = 0; i < threads; i++) {  
      threadInfo *t_info = infosOfSub + i;
      t_info->threadID = i;
      
      t_info->start_table_id = last;
      t_info->end_table_id = i < b ? last + a : last + a - 1;
      last = t_info->end_table_id + 1;
      t_info->taos = taos;
      pthread_create(pidsOfSub + i, NULL, subQueryProcess, t_info);
    }

    g_queryInfo.subQueryInfo.threadCnt = threads;
  }else {
    g_queryInfo.subQueryInfo.threadCnt = 0;
  }  
  
  for (int i = 0; i < g_queryInfo.superQueryInfo.concurrent; i++) {
    pthread_join(pids[i], NULL);
5355
  }
S
Shuaiqiang Chang 已提交
5356

5357 5358 5359 5360 5361
  tmfree((char*)pids);
  tmfree((char*)infos);  
  
  for (int i = 0; i < g_queryInfo.subQueryInfo.threadCnt; i++) {
    pthread_join(pidsOfSub[i], NULL);
H
hzcheng 已提交
5362
  }
H
Hui Li 已提交
5363

5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378
  tmfree((char*)pidsOfSub);
  tmfree((char*)infosOfSub);  
  
  taos_close(taos);
  return 0;
}

static void subscribe_callback(TAOS_SUB* tsub, TAOS_RES *res, void* param, int code) {  
  if (res == NULL || taos_errno(res) != 0) {
    printf("failed to subscribe result, code:%d, reason:%s\n", code, taos_errstr(res));
    return;
  }
  
  getResult(res, (char*)param);
  taos_free_result(res);
H
hzcheng 已提交
5379 5380
}

5381 5382
static TAOS_SUB* subscribeImpl(TAOS *taos, char *sql, char* topic, char* resultFileName) {
  TAOS_SUB* tsub = NULL;  
H
hzcheng 已提交
5383

5384
  if (g_queryInfo.superQueryInfo.subscribeMode) {
5385 5386 5387 5388
    tsub = taos_subscribe(taos, 
            g_queryInfo.superQueryInfo.subscribeRestart, 
            topic, sql, subscribe_callback, (void*)resultFileName, 
            g_queryInfo.superQueryInfo.subscribeInterval);
5389
  } else {
5390 5391 5392
    tsub = taos_subscribe(taos, 
            g_queryInfo.superQueryInfo.subscribeRestart, 
            topic, sql, NULL, NULL, 0);
5393
  }
5394

5395 5396 5397 5398
  if (tsub == NULL) {
    printf("failed to create subscription. topic:%s, sql:%s\n", topic, sql);
    return NULL;
  } 
5399

5400 5401
  return tsub;
}
H
hzcheng 已提交
5402

5403 5404 5405
void *subSubscribeProcess(void *sarg) {
  threadInfo *winfo = (threadInfo *)sarg; 
  char subSqlstr[1024];
H
hzcheng 已提交
5406

5407 5408
  char sqlStr[MAX_TB_NAME_SIZE*2];
  sprintf(sqlStr, "use %s", g_queryInfo.dbName);
5409
  debugPrint("%s() %d sqlStr: %s\n", __func__, __LINE__, sqlStr);
5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437
  if (0 != queryDbExec(winfo->taos, sqlStr, NO_INSERT_TYPE)){
    return NULL;
  }
  
  //int64_t st = 0;
  //int64_t et = 0;
  do {
    //if (g_queryInfo.superQueryInfo.rate && (et - st) < g_queryInfo.superQueryInfo.rate*1000) {
    //  taosMsleep(g_queryInfo.superQueryInfo.rate*1000 - (et - st)); // ms
    //  //printf("========sleep duration:%"PRId64 "========inserted rows:%d, table range:%d - %d\n", (1000 - (et - st)), i, winfo->start_table_id, winfo->end_table_id);
    //}

    //st = taosGetTimestampMs();
    char topic[32] = {0};
    for (int i = 0; i < g_queryInfo.subQueryInfo.sqlCount; i++) {
      sprintf(topic, "taosdemo-subscribe-%d", i);
      memset(subSqlstr,0,sizeof(subSqlstr));
      replaceSubTblName(g_queryInfo.subQueryInfo.sql[i], subSqlstr, i);
      char tmpFile[MAX_FILE_NAME_LEN*2] = {0};
      if (g_queryInfo.subQueryInfo.result[i][0] != 0) {
        sprintf(tmpFile, "%s-%d", g_queryInfo.subQueryInfo.result[i], winfo->threadID);
      }
      g_queryInfo.subQueryInfo.tsub[i] = subscribeImpl(winfo->taos, subSqlstr, topic, tmpFile); 
      if (NULL == g_queryInfo.subQueryInfo.tsub[i]) {
        return NULL;
      }
    }
    //et = taosGetTimestampMs();
5438
    //printf("========thread[%"PRId64"] complete all sqls to super table once queries duration:%.4fs\n", taosGetSelfPthreadId(), (double)(et - st)/1000.0);
5439 5440 5441 5442 5443 5444 5445 5446 5447
  } while (0);

  // start loop to consume result
  TAOS_RES* res = NULL;
  while (1) {
    for (int i = 0; i < g_queryInfo.subQueryInfo.sqlCount; i++) {
      if (1 == g_queryInfo.subQueryInfo.subscribeMode) {
        continue;
      }
H
Hui Li 已提交
5448
      
5449 5450 5451 5452
      res = taos_consume(g_queryInfo.subQueryInfo.tsub[i]);
      if (res) {
        char tmpFile[MAX_FILE_NAME_LEN*2] = {0};
        if (g_queryInfo.subQueryInfo.result[i][0] != 0) {
5453 5454 5455
          sprintf(tmpFile, "%s-%d", 
                  g_queryInfo.subQueryInfo.result[i], 
                  winfo->threadID);
5456 5457
        }
        getResult(res, tmpFile);
H
hzcheng 已提交
5458 5459 5460
      }
    }
  }
5461 5462 5463
  taos_free_result(res);
  
  for (int i = 0; i < g_queryInfo.subQueryInfo.sqlCount; i++) {
5464 5465
    taos_unsubscribe(g_queryInfo.subQueryInfo.tsub[i], 
            g_queryInfo.subQueryInfo.subscribeKeepProgress);
5466
  }
H
hzcheng 已提交
5467 5468 5469
  return NULL;
}

5470 5471
void *superSubscribeProcess(void *sarg) {
  threadInfo *winfo = (threadInfo *)sarg; 
H
hzcheng 已提交
5472

5473 5474
  char sqlStr[MAX_TB_NAME_SIZE*2];
  sprintf(sqlStr, "use %s", g_queryInfo.dbName);
5475
  debugPrint("%s() %d sqlStr: %s\n", __func__, __LINE__, sqlStr);
5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493
  if (0 != queryDbExec(winfo->taos, sqlStr, NO_INSERT_TYPE)) {
    return NULL;
  }
  
  //int64_t st = 0;
  //int64_t et = 0;
  do {
    //if (g_queryInfo.superQueryInfo.rate && (et - st) < g_queryInfo.superQueryInfo.rate*1000) {
    //  taosMsleep(g_queryInfo.superQueryInfo.rate*1000 - (et - st)); // ms
    //  //printf("========sleep duration:%"PRId64 "========inserted rows:%d, table range:%d - %d\n", (1000 - (et - st)), i, winfo->start_table_id, winfo->end_table_id);
    //}

    //st = taosGetTimestampMs();
    char topic[32] = {0};
    for (int i = 0; i < g_queryInfo.superQueryInfo.sqlCount; i++) {
      sprintf(topic, "taosdemo-subscribe-%d", i);
      char tmpFile[MAX_FILE_NAME_LEN*2] = {0};
      if (g_queryInfo.subQueryInfo.result[i][0] != 0) {
5494 5495
        sprintf(tmpFile, "%s-%d", 
                g_queryInfo.superQueryInfo.result[i], winfo->threadID);
5496
      }
5497 5498 5499 5500
      g_queryInfo.superQueryInfo.tsub[i] = 
          subscribeImpl(winfo->taos, 
                  g_queryInfo.superQueryInfo.sql[i], 
                  topic, tmpFile); 
5501 5502 5503 5504 5505
      if (NULL == g_queryInfo.superQueryInfo.tsub[i]) {
        return NULL;
      }
    }
    //et = taosGetTimestampMs();
5506
    //printf("========thread[%"PRId64"] complete all sqls to super table once queries duration:%.4fs\n", taosGetSelfPthreadId(), (double)(et - st)/1000.0);
5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520
  } while (0);

  // start loop to consume result
  TAOS_RES* res = NULL;
  while (1) {
    for (int i = 0; i < g_queryInfo.superQueryInfo.sqlCount; i++) {
      if (1 == g_queryInfo.superQueryInfo.subscribeMode) {
        continue;
      }
      
      res = taos_consume(g_queryInfo.superQueryInfo.tsub[i]);
      if (res) {
        char tmpFile[MAX_FILE_NAME_LEN*2] = {0};
        if (g_queryInfo.superQueryInfo.result[i][0] != 0) {
5521 5522
          sprintf(tmpFile, "%s-%d", 
                  g_queryInfo.superQueryInfo.result[i], winfo->threadID);
5523 5524 5525 5526 5527 5528
        }
        getResult(res, tmpFile);
      }
    }
  }
  taos_free_result(res);
5529

5530
  for (int i = 0; i < g_queryInfo.superQueryInfo.sqlCount; i++) {
5531 5532
    taos_unsubscribe(g_queryInfo.superQueryInfo.tsub[i], 
            g_queryInfo.superQueryInfo.subscribeKeepProgress);
5533
  }
H
hzcheng 已提交
5534 5535 5536
  return NULL;
}

5537
static int subscribeTestProcess() {
5538
  printfQueryMeta();
H
hzcheng 已提交
5539

5540 5541 5542
  if (!g_args.answer_yes) {
    printf("Press enter key to continue\n\n");
    (void)getchar();
Y
yihaoDeng 已提交
5543
  }
5544 5545

  TAOS * taos = NULL;  
5546 5547 5548 5549 5550
  taos = taos_connect(g_queryInfo.host, 
          g_queryInfo.user, 
          g_queryInfo.password, 
          g_queryInfo.dbName, 
          g_queryInfo.port);
5551 5552 5553 5554 5555 5556
  if (taos == NULL) {
    fprintf(stderr, "Failed to connect to TDengine, reason:%s\n", taos_errstr(NULL));
    exit(-1);
  }

  if (0 != g_queryInfo.subQueryInfo.sqlCount) {
5557
    getAllChildNameOfSuperTable(taos, 
5558 5559 5560 5561
            g_queryInfo.dbName, 
            g_queryInfo.subQueryInfo.sTblName, 
            &g_queryInfo.subQueryInfo.childTblName, 
            &g_queryInfo.subQueryInfo.childTblCount);
5562 5563 5564 5565 5566
  }

  pthread_t  *pids = NULL;
  threadInfo *infos = NULL;
  //==== create sub threads for query from super table
5567 5568
  if (g_queryInfo.superQueryInfo.sqlCount > 0 
          && g_queryInfo.superQueryInfo.concurrent > 0) {
5569 5570 5571
    pids  = malloc(g_queryInfo.superQueryInfo.concurrent * sizeof(pthread_t));
    infos = malloc(g_queryInfo.superQueryInfo.concurrent * sizeof(threadInfo));
    if ((NULL == pids) || (NULL == infos)) {
5572
      printf("malloc failed for create threads\n");
5573 5574 5575
      taos_close(taos);
      exit(-1);
    }
5576 5577

    for (int i = 0; i < g_queryInfo.superQueryInfo.concurrent; i++) {
5578 5579 5580 5581 5582
      threadInfo *t_info = infos + i;
      t_info->threadID = i;
      t_info->taos = taos;
      pthread_create(pids + i, NULL, superSubscribeProcess, t_info);
    }
H
hzcheng 已提交
5583
  }
5584
 
5585 5586 5587
  //==== create sub threads for query from sub table  
  pthread_t  *pidsOfSub  = NULL;
  threadInfo *infosOfSub = NULL;
5588
  if ((g_queryInfo.subQueryInfo.sqlCount > 0)
5589
          && (g_queryInfo.subQueryInfo.threadCnt > 0)) {
5590
    pidsOfSub  = malloc(g_queryInfo.subQueryInfo.threadCnt *
5591 5592 5593
            sizeof(pthread_t));
    infosOfSub = malloc(g_queryInfo.subQueryInfo.threadCnt * 
            sizeof(threadInfo));
5594
    if ((NULL == pidsOfSub) || (NULL == infosOfSub)) {
5595
      printf("malloc failed for create threads\n");
5596 5597
      taos_close(taos);
      exit(-1);
S
Shuaiqiang Chang 已提交
5598
    }
5599

5600 5601
    int ntables = g_queryInfo.subQueryInfo.childTblCount;
    int threads = g_queryInfo.subQueryInfo.threadCnt;
5602
 
5603 5604 5605 5606 5607
    int a = ntables / threads;
    if (a < 1) {
      threads = ntables;
      a = 1;
    }
5608
 
5609 5610 5611 5612
    int b = 0;
    if (threads != 0) {
      b = ntables % threads;
    }
5613
 
5614
    int last = 0;
5615
    for (int i = 0; i < threads; i++) {
5616 5617
      threadInfo *t_info = infosOfSub + i;
      t_info->threadID = i;
5618

5619 5620 5621 5622
      t_info->start_table_id = last;
      t_info->end_table_id = i < b ? last + a : last + a - 1;
      t_info->taos = taos;
      pthread_create(pidsOfSub + i, NULL, subSubscribeProcess, t_info);
H
hzcheng 已提交
5623
    }
5624
    g_queryInfo.subQueryInfo.threadCnt = threads;
H
hzcheng 已提交
5625
  }
5626
 
5627 5628 5629
  for (int i = 0; i < g_queryInfo.superQueryInfo.concurrent; i++) {
    pthread_join(pids[i], NULL);
  }  
H
hzcheng 已提交
5630

5631
  tmfree((char*)pids);
5632
  tmfree((char*)infos);
H
hzcheng 已提交
5633

5634 5635
  for (int i = 0; i < g_queryInfo.subQueryInfo.threadCnt; i++) {
    pthread_join(pidsOfSub[i], NULL);
H
hzcheng 已提交
5636 5637
  }

5638
  tmfree((char*)pidsOfSub);
5639
  tmfree((char*)infosOfSub);
5640 5641
  taos_close(taos);
  return 0;
H
hzcheng 已提交
5642 5643
}

5644 5645 5646
void initOfInsertMeta() {
  memset(&g_Dbs, 0, sizeof(SDbs));
   
5647 5648 5649 5650 5651 5652 5653
  // set default values
  tstrncpy(g_Dbs.host, "127.0.0.1", MAX_DB_NAME_SIZE);
  g_Dbs.port = 6030;
  tstrncpy(g_Dbs.user, TSDB_DEFAULT_USER, MAX_DB_NAME_SIZE);
  tstrncpy(g_Dbs.password, TSDB_DEFAULT_PASS, MAX_DB_NAME_SIZE);
  g_Dbs.threadCount = 2;
  g_Dbs.use_metric = true;
L
Liu Tao 已提交
5654 5655
}

5656 5657 5658
void initOfQueryMeta() {
  memset(&g_queryInfo, 0, sizeof(SQueryMetaInfo));
   
5659 5660 5661 5662 5663
  // set default values
  tstrncpy(g_queryInfo.host, "127.0.0.1", MAX_DB_NAME_SIZE);
  g_queryInfo.port = 6030;
  tstrncpy(g_queryInfo.user, TSDB_DEFAULT_USER, MAX_DB_NAME_SIZE);
  tstrncpy(g_queryInfo.password, TSDB_DEFAULT_PASS, MAX_DB_NAME_SIZE);
L
Liu Tao 已提交
5664 5665
}

5666 5667 5668 5669
void setParaFromArg(){
  if (g_args.host) {
    strcpy(g_Dbs.host, g_args.host);
  } else {
5670
    tstrncpy(g_Dbs.host, "127.0.0.1", MAX_DB_NAME_SIZE);
5671
  }
L
Liu Tao 已提交
5672

5673 5674 5675 5676 5677 5678 5679
  if (g_args.user) {
    strcpy(g_Dbs.user, g_args.user);
  } 

  if (g_args.password) {
    strcpy(g_Dbs.password, g_args.password);
  } 
L
Liu Tao 已提交
5680
  
5681 5682 5683
  if (g_args.port) {
    g_Dbs.port = g_args.port;
  } 
L
Liu Tao 已提交
5684

5685 5686 5687
  g_Dbs.threadCount = g_args.num_of_threads;
  g_Dbs.threadCountByCreateTbl = g_args.num_of_threads;

5688 5689
  g_Dbs.dbCount = 1;
  g_Dbs.db[0].drop = 1;
5690

5691
  tstrncpy(g_Dbs.db[0].dbName, g_args.database, MAX_DB_NAME_SIZE);
5692
  g_Dbs.db[0].dbCfg.replica = g_args.replica;
5693
  tstrncpy(g_Dbs.db[0].dbCfg.precision, "ms", MAX_DB_NAME_SIZE);
L
Liu Tao 已提交
5694

5695
  tstrncpy(g_Dbs.resultFile, g_args.output_file, MAX_FILE_NAME_LEN);
5696 5697 5698 5699 5700

  g_Dbs.use_metric = g_args.use_metric;
  g_Dbs.insert_only = g_args.insert_only;

  g_Dbs.do_aggreFunc = true;
L
Liu Tao 已提交
5701

5702 5703 5704 5705
  char dataString[STRING_LEN];
  char **data_type = g_args.datatype;
  
  memset(dataString, 0, STRING_LEN);
L
Liu Tao 已提交
5706

5707 5708 5709
  if (strcasecmp(data_type[0], "BINARY") == 0 
          || strcasecmp(data_type[0], "BOOL") == 0 
          || strcasecmp(data_type[0], "NCHAR") == 0 ) {
5710
    g_Dbs.do_aggreFunc = false;
L
Liu Tao 已提交
5711
  }
H
hzcheng 已提交
5712

5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731
  if (g_args.use_metric) {
    g_Dbs.db[0].superTblCount = 1;
    tstrncpy(g_Dbs.db[0].superTbls[0].sTblName, "meters", MAX_TB_NAME_SIZE);
    g_Dbs.db[0].superTbls[0].childTblCount = g_args.num_of_tables;
    g_Dbs.threadCount = g_args.num_of_threads;
    g_Dbs.threadCountByCreateTbl = 1;
    g_Dbs.queryMode = g_args.mode;
  
    g_Dbs.db[0].superTbls[0].autoCreateTable = PRE_CREATE_SUBTBL;
    g_Dbs.db[0].superTbls[0].superTblExists = TBL_NO_EXISTS;
    g_Dbs.db[0].superTbls[0].childTblExists = TBL_NO_EXISTS;
    g_Dbs.db[0].superTbls[0].disorderRange = g_args.disorderRange;
    g_Dbs.db[0].superTbls[0].disorderRatio = g_args.disorderRatio;
    tstrncpy(g_Dbs.db[0].superTbls[0].childTblPrefix, 
            g_args.tb_prefix, MAX_TB_NAME_SIZE);
    tstrncpy(g_Dbs.db[0].superTbls[0].dataSource, "rand", MAX_TB_NAME_SIZE);
    tstrncpy(g_Dbs.db[0].superTbls[0].insertMode, "taosc", MAX_TB_NAME_SIZE);
    tstrncpy(g_Dbs.db[0].superTbls[0].startTimestamp, 
            "2017-07-14 10:40:00.000", MAX_TB_NAME_SIZE);
5732
    g_Dbs.db[0].superTbls[0].timeStampStep = DEFAULT_TIMESTAMP_STEP;
5733
  
5734
    g_Dbs.db[0].superTbls[0].insertRows = g_args.num_of_DPT;
5735
    g_Dbs.db[0].superTbls[0].maxSqlLen = TSDB_PAYLOAD_SIZE;
5736

5737 5738 5739 5740 5741 5742 5743 5744 5745
    g_Dbs.db[0].superTbls[0].columnCount = 0;
    for (int i = 0; i < MAX_NUM_DATATYPE; i++) {
      if (data_type[i] == NULL) {
        break;
      }
  
      tstrncpy(g_Dbs.db[0].superTbls[0].columns[i].dataType, 
              data_type[i], MAX_TB_NAME_SIZE);
      g_Dbs.db[0].superTbls[0].columns[i].dataLen = g_args.len_of_binary;    
5746 5747
      g_Dbs.db[0].superTbls[0].columnCount++;
    }
5748 5749 5750 5751 5752 5753 5754 5755 5756 5757
  
    if (g_Dbs.db[0].superTbls[0].columnCount > g_args.num_of_CPR) {
      g_Dbs.db[0].superTbls[0].columnCount = g_args.num_of_CPR;
    } else {
      for (int i = g_Dbs.db[0].superTbls[0].columnCount; i < g_args.num_of_CPR; i++) {
        tstrncpy(g_Dbs.db[0].superTbls[0].columns[i].dataType, "INT", MAX_TB_NAME_SIZE);
        g_Dbs.db[0].superTbls[0].columns[i].dataLen = 0;    
        g_Dbs.db[0].superTbls[0].columnCount++;
      }
    }
5758

5759
    tstrncpy(g_Dbs.db[0].superTbls[0].tags[0].dataType, "INT", MAX_TB_NAME_SIZE);
5760 5761
    g_Dbs.db[0].superTbls[0].tags[0].dataLen = 0;    
  
5762
    tstrncpy(g_Dbs.db[0].superTbls[0].tags[1].dataType, "BINARY", MAX_TB_NAME_SIZE);
5763 5764 5765
    g_Dbs.db[0].superTbls[0].tags[1].dataLen = g_args.len_of_binary;    
    g_Dbs.db[0].superTbls[0].tagCount = 2;  
  } else {
5766
    g_Dbs.threadCountByCreateTbl = 1;
5767
    g_Dbs.db[0].superTbls[0].tagCount = 0; 
H
hzcheng 已提交
5768
  }
5769

5770 5771 5772 5773 5774 5775
}

/* Function to do regular expression check */
static int regexMatch(const char *s, const char *reg, int cflags) {
  regex_t regex;
  char    msgbuf[100] = {0};
H
hzcheng 已提交
5776

5777 5778 5779
  /* Compile regular expression */
  if (regcomp(&regex, reg, cflags) != 0) {
    printf("Fail to compile regex\n");
H
Hui Li 已提交
5780 5781 5782
    exit(-1);
  }

5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813
  /* Execute regular expression */
  int reti = regexec(&regex, s, 0, NULL, 0);
  if (!reti) {
    regfree(&regex);
    return 1;
  } else if (reti == REG_NOMATCH) {
    regfree(&regex);
    return 0;
  } else {
    regerror(reti, &regex, msgbuf, sizeof(msgbuf));
    printf("Regex match failed: %s\n", msgbuf);
    regfree(&regex);
    exit(-1);
  }

  return 0;
}

static int isCommentLine(char *line) {
  if (line == NULL) return 1;

  return regexMatch(line, "^\\s*#.*", REG_EXTENDED);
}

void querySqlFile(TAOS* taos, char* sqlFile)
{
  FILE *fp = fopen(sqlFile, "r");
  if (fp == NULL) {
    printf("failed to open file %s, reason:%s\n", sqlFile, strerror(errno));
    return;
  }
5814

5815 5816 5817 5818 5819 5820 5821
  int       read_len = 0;
  char *    cmd = calloc(1, MAX_SQL_SIZE);
  size_t    cmd_len = 0;
  char *    line = NULL;
  size_t    line_len = 0;

  double t = getCurrentTime();
5822

5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835
  while ((read_len = tgetline(&line, &line_len, fp)) != -1) {
    if (read_len >= MAX_SQL_SIZE) continue;
    line[--read_len] = '\0';

    if (read_len == 0 || isCommentLine(line)) {  // line starts with #
      continue;
    }

    if (line[read_len - 1] == '\\') {
      line[read_len - 1] = ' ';
      memcpy(cmd + cmd_len, line, read_len);
      cmd_len += read_len;
      continue;
5836
    }
5837 5838

    memcpy(cmd + cmd_len, line, read_len);
5839
    verbosePrint("%s() LN%d cmd: %s\n", __func__, __LINE__, cmd);
5840
    queryDbExec(taos, cmd, NO_INSERT_TYPE);
5841 5842 5843 5844 5845 5846 5847
    if (0 != queryDbExec(taos, cmd, NO_INSERT_TYPE)) {
        printf("queryDbExec %s failed!\n", cmd);
        tmfree(cmd);
        tmfree(line);
        tmfclose(fp);
        return;
    }
5848 5849
    memset(cmd, 0, MAX_SQL_SIZE);
    cmd_len = 0;
H
hzcheng 已提交
5850 5851
  }

5852 5853
  t = getCurrentTime() - t;
  printf("run %s took %.6f second(s)\n\n", sqlFile, t);
5854

5855 5856 5857 5858
  tmfree(cmd);
  tmfree(line);
  tmfclose(fp);
  return;
H
hzcheng 已提交
5859 5860
}

5861
static void testMetaFile() {
5862
    if (INSERT_MODE == g_args.test_mode) {
5863
      if (g_Dbs.cfgDir[0]) taos_options(TSDB_OPTION_CONFIGDIR, g_Dbs.cfgDir);
5864
      insertTestProcess();
5865
    } else if (QUERY_MODE == g_args.test_mode) {
5866 5867
      if (g_queryInfo.cfgDir[0])
          taos_options(TSDB_OPTION_CONFIGDIR, g_queryInfo.cfgDir);
5868
      queryTestProcess();
5869
    } else if (SUBSCRIBE_MODE == g_args.test_mode) {
5870 5871
      if (g_queryInfo.cfgDir[0])
          taos_options(TSDB_OPTION_CONFIGDIR, g_queryInfo.cfgDir);
5872
      subscribeTestProcess();
5873 5874 5875
    }  else {
      ;
    }
5876
}
5877

5878
static void queryResult() {
5879 5880 5881
    // select
    if (false == g_Dbs.insert_only) {
      // query data
5882

5883 5884 5885 5886
      pthread_t read_id;
      threadInfo *rInfo = malloc(sizeof(threadInfo));
      rInfo->start_time = 1500000000000;  // 2017-07-14 10:40:00.000
      rInfo->start_table_id = 0;
5887

5888
      //rInfo->do_aggreFunc = g_Dbs.do_aggreFunc;
5889 5890 5891 5892 5893 5894 5895 5896 5897 5898
      if (g_args.use_metric) {
        rInfo->end_table_id = g_Dbs.db[0].superTbls[0].childTblCount - 1;
        rInfo->superTblInfo = &g_Dbs.db[0].superTbls[0];
        strcpy(rInfo->tb_prefix, 
              g_Dbs.db[0].superTbls[0].childTblPrefix);
      } else {
        rInfo->end_table_id = g_args.num_of_tables -1;
        strcpy(rInfo->tb_prefix, g_args.tb_prefix);
      }

5899 5900 5901 5902 5903 5904
      rInfo->taos = taos_connect(
              g_Dbs.host, 
              g_Dbs.user, 
              g_Dbs.password, 
              g_Dbs.db[0].dbName, 
              g_Dbs.port);
5905 5906 5907 5908 5909 5910
      if (rInfo->taos == NULL) {
        fprintf(stderr, "Failed to connect to TDengine, reason:%s\n", taos_errstr(NULL));
        free(rInfo);
        exit(-1);
      }

5911 5912 5913 5914 5915 5916 5917 5918 5919 5920
      strcpy(rInfo->fp, g_Dbs.resultFile);

      if (!g_Dbs.use_metric) {
        pthread_create(&read_id, NULL, readTable, rInfo);
      } else {
        pthread_create(&read_id, NULL, readMetric, rInfo);
      }
      pthread_join(read_id, NULL);
      taos_close(rInfo->taos);
      free(rInfo);
H
hzcheng 已提交
5921
    }
5922 5923
}

5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934
static void testCmdLine() {

    g_args.test_mode = INSERT_MODE;
    insertTestProcess();

    if (g_Dbs.insert_only)
      return;
    else
        queryResult();
}

5935 5936 5937
int main(int argc, char *argv[]) {
  parse_args(argc, argv, &g_args);

5938
  debugPrint("meta file: %s\n", g_args.metaFile);
5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966

  if (g_args.metaFile) {
    initOfInsertMeta();
    initOfQueryMeta();    

    if (false == getInfoFromJsonFile(g_args.metaFile)) {
      printf("Failed to read %s\n", g_args.metaFile);
      return 1;
    }

    testMetaFile();
  } else {
    memset(&g_Dbs, 0, sizeof(SDbs));
    setParaFromArg();

    if (NULL != g_args.sqlFile) {
      TAOS* qtaos = taos_connect(
          g_Dbs.host, 
          g_Dbs.user, 
          g_Dbs.password, 
          g_Dbs.db[0].dbName, 
          g_Dbs.port);
      querySqlFile(qtaos, g_args.sqlFile);  
      taos_close(qtaos);

    } else {
      testCmdLine();
    }
H
hzcheng 已提交
5967
  }
5968 5969

  return 0;
H
hzcheng 已提交
5970
}
5971