taosdemo.c 52.9 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/>.
 */

S
slguan 已提交
16
#define _GNU_SOURCE
H
hzcheng 已提交
17

S
TD-1057  
Shengliang Guan 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#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"
#endif  
H
hzcheng 已提交
43 44

#include "taos.h"
H
Hui Li 已提交
45
#include "tutil.h"
S
slguan 已提交
46 47 48

extern char configDir[];

H
hzcheng 已提交
49 50 51
#define BUFFER_SIZE      65536
#define MAX_DB_NAME_SIZE 64
#define MAX_TB_NAME_SIZE 64
L
Liu Tao 已提交
52 53
#define MAX_DATA_SIZE    16000
#define MAX_NUM_DATATYPE 10
H
hzcheng 已提交
54
#define OPT_ABORT        1 /* –abort */
T
Tao Liu 已提交
55
#define STRING_LEN       60000
L
Liu Tao 已提交
56
#define MAX_PREPARED_RAND 1000000
H
hzcheng 已提交
57 58

/* Used by main to communicate with parse_opt. */
59
typedef struct DemoArguments {
60 61 62 63 64 65 66 67 68 69
  char *   host;
  uint16_t port;
  char *   user;
  char *   password;
  char *   database;
  int      replica;
  char *   tb_prefix;
  char *   sqlFile;
  bool     use_metric;
  bool     insert_only;
70
  bool     answer_yes;
71 72 73 74 75 76 77 78 79 80 81 82 83 84
  char *   output_file;
  int      mode;
  char *   datatype[MAX_NUM_DATATYPE + 1];
  int      len_of_binary;
  int      num_of_CPR;
  int      num_of_threads;
  int      num_of_RPR;
  int      num_of_tables;
  int      num_of_DPT;
  int      abort;
  int      order;
  int      rate;
  int      method_of_delete;
  char **  arg_list;
85
} SDemoArguments;
H
hzcheng 已提交
86

S
TD-1057  
Shengliang Guan 已提交
87 88 89
#ifdef LINUX
  /* The options we understand. */
  static struct argp_option options[] = {
90
    {0, 'h', "host",                     0, "The host to connect to TDengine. Default is localhost.",                                                           0},
S
TD-1057  
Shengliang Guan 已提交
91
    {0, 'p', "port",                     0, "The TCP/IP port number to use for the connection. Default is 0.",                                                  1},
92
    {0, 'u', "user",                     0, "The TDengine user name to use when connecting to the server. Default is 'root'.",                                  2},
H
Hui Li 已提交
93
    #ifdef _TD_POWER_    
H
Hui Li 已提交
94 95
    {0, 'P', "password",                 0, "The password to use when connecting to the server. Default is 'powerdb'.",                                         3},
    #else
S
TD-1057  
Shengliang Guan 已提交
96
    {0, 'P', "password",                 0, "The password to use when connecting to the server. Default is 'taosdata'.",                                        3},
H
Hui Li 已提交
97
    #endif
S
TD-1057  
Shengliang Guan 已提交
98
    {0, 'd', "database",                 0, "Destination database. Default is 'test'.",                                                                         3},
H
Hui Li 已提交
99
    {0, 'a', "replica",                  0, "Set the replica parameters of the database, Default 1, min: 1, max: 3.",                                           3},
S
TD-1057  
Shengliang Guan 已提交
100 101 102 103 104 105 106 107 108 109 110 111
    {0, 'm', "table_prefix",             0, "Table prefix name. Default is 't'.",                                                                               3},
    {0, 's', "sql file",                 0, "The select sql file.",                                                                                             3},
    {0, 'M', 0,                          0, "Use metric flag.",                                                                                                 13},
    {0, 'o', "outputfile",               0, "Direct output to the named file. Default is './output.txt'.",                                                      14},
    {0, 'q', "query_mode",               0, "Query mode--0: SYNC, 1: ASYNC. Default is SYNC.",                                                                  6},
    {0, 'b', "type_of_cols",             0, "The data_type of columns: 'INT', 'TINYINT', 'SMALLINT', 'BIGINT', 'FLOAT', 'DOUBLE', 'BINARY'. Default is 'INT'.", 7},
    {0, 'w', "length_of_binary",         0, "The length of data_type 'BINARY'. Only applicable when type of cols is 'BINARY'. Default is 8",                    8},
    {0, 'l', "num_of_cols_per_record",   0, "The number of columns per record. Default is 3.",                                                                  8},
    {0, 'T', "num_of_threads",           0, "The number of threads. Default is 10.",                                                                            9},
    {0, 'r', "num_of_records_per_req",   0, "The number of records per request. Default is 1000.",                                                              10},
    {0, 't', "num_of_tables",            0, "The number of tables. Default is 10000.",                                                                          11},
    {0, 'n', "num_of_records_per_table", 0, "The number of records per table. Default is 100000.",                                                              12},
H
Hui Li 已提交
112
    #ifdef _TD_POWER_
H
Hui Li 已提交
113 114
    {0, 'c', "config_directory",         0, "Configuration directory. Default is '/etc/power/'.",                                                               14},
    #else
S
TD-1057  
Shengliang Guan 已提交
115
    {0, 'c', "config_directory",         0, "Configuration directory. Default is '/etc/taos/'.",                                                                14},
H
Hui Li 已提交
116
    #endif
S
TD-1057  
Shengliang Guan 已提交
117
    {0, 'x', 0,                          0, "Insert only flag.",                                                                                                13},
118
    {0, 'y', 0,                          0, "Default input yes for prompt",                                                                                                13},
S
TD-1057  
Shengliang Guan 已提交
119 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 175 176 177 178
    {0, 'O', "order",                    0, "Insert mode--0: In order, 1: Out of order. Default is in order.",                                                  14},
    {0, 'R', "rate",                     0, "Out of order data's rate--if order=1 Default 10, min: 0, max: 50.",                                                14},
    {0, 'D', "delete table",             0, "Delete data methods——0: don't delete, 1: delete by table, 2: delete by stable, 3: delete by database",             14},
    {0}};

  /* Parse a single option. */
  static error_t parse_opt(int key, char *arg, struct argp_state *state) {
    /* Get the input argument from argp_parse, which we
      know is a pointer to our arguments structure. */
    SDemoArguments *arguments = state->input;
    wordexp_t full_path;
    char **sptr;
    switch (key) {
      case 'h':
        arguments->host = arg;
        break;
      case 'p':
        arguments->port = atoi(arg);
        break;
      case 'u':
        arguments->user = arg;
        break;
      case 'P':
        arguments->password = arg;
        break;
      case 'o':
        arguments->output_file = arg;
        break;
      case 's':
        arguments->sqlFile = arg;
        break;
      case 'q':
        arguments->mode = atoi(arg);
        break;
      case 'T':
        arguments->num_of_threads = atoi(arg);
        break;
      case 'r':
        arguments->num_of_RPR = atoi(arg);
        break;
      case 't':
        arguments->num_of_tables = atoi(arg);
        break;
      case 'n':
        arguments->num_of_DPT = atoi(arg);
        break;
      case 'd':
        arguments->database = arg;
        break;
      case 'l':
        arguments->num_of_CPR = atoi(arg);
        break;
      case 'b':
        sptr = arguments->datatype;
        if (strstr(arg, ",") == NULL) {
          if (strcasecmp(arg, "INT") != 0 && strcasecmp(arg, "FLOAT") != 0 &&
              strcasecmp(arg, "TINYINT") != 0 && strcasecmp(arg, "BOOL") != 0 &&
              strcasecmp(arg, "SMALLINT") != 0 &&
              strcasecmp(arg, "BIGINT") != 0 && strcasecmp(arg, "DOUBLE") != 0 &&
              strcasecmp(arg, "BINARY") && strcasecmp(arg, "NCHAR")) {
H
hzcheng 已提交
179 180
            argp_error(state, "Invalid data_type!");
          }
S
TD-1057  
Shengliang Guan 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
          sptr[0] = arg;
        } else {
          int index = 0;
          char *dupstr = strdup(arg);
          char *running = dupstr;
          char *token = strsep(&running, ",");
          while (token != NULL) {
            if (strcasecmp(token, "INT") != 0 &&
                strcasecmp(token, "FLOAT") != 0 &&
                strcasecmp(token, "TINYINT") != 0 &&
                strcasecmp(token, "BOOL") != 0 &&
                strcasecmp(token, "SMALLINT") != 0 &&
                strcasecmp(token, "BIGINT") != 0 &&
                strcasecmp(token, "DOUBLE") != 0 && strcasecmp(token, "BINARY") && strcasecmp(token, "NCHAR")) {
              argp_error(state, "Invalid data_type!");
            }
            sptr[index++] = token;
            token = strsep(&running, ",");
            if (index >= MAX_NUM_DATATYPE) break;
          }
H
hzcheng 已提交
201
        }
S
TD-1057  
Shengliang Guan 已提交
202 203 204 205 206 207 208 209
        break;
      case 'w':
        arguments->len_of_binary = atoi(arg);
        break;
      case 'm':
        arguments->tb_prefix = arg;
        break;
      case 'M':
H
Hui Li 已提交
210
        arguments->use_metric = true;
S
TD-1057  
Shengliang Guan 已提交
211 212
        break;
      case 'x':
H
Hui Li 已提交
213
        arguments->insert_only = true;
S
TD-1057  
Shengliang Guan 已提交
214
        break;
215 216 217
      case 'y':
        arguments->answer_yes = true;
        break;
S
TD-1057  
Shengliang Guan 已提交
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
      case 'c':
        if (wordexp(arg, &full_path, 0) != 0) {
          fprintf(stderr, "Invalid path %s\n", arg);
          return -1;
        }
        taos_options(TSDB_OPTION_CONFIGDIR, full_path.we_wordv[0]);
        wordfree(&full_path);
        break;
      case 'O':
        arguments->order = atoi(arg);
        if (arguments->order > 1 || arguments->order < 0)
        {
          arguments->order = 0;
        } else if (arguments->order == 1)
        {
          arguments->rate = 10;
        }
        break;
      case 'R':
        arguments->rate = atoi(arg);
        if (arguments->order == 1 && (arguments->rate > 50 || arguments->rate <= 0))
        {
          arguments->rate = 10;
        }
        break;
243 244 245 246 247 248 249
      case 'a':
        arguments->replica = atoi(arg);
        if (arguments->replica > 3 || arguments->replica < 1)
        {
          arguments->replica = 1;
        }
        break;
S
TD-1057  
Shengliang Guan 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
      case 'D':
        arguments->method_of_delete = atoi(arg);
        if (arguments->method_of_delete < 0 || arguments->method_of_delete > 3)
        {
          arguments->method_of_delete = 0;
        }
        break;
      case OPT_ABORT:
        arguments->abort = 1;
        break;
      case ARGP_KEY_ARG:
        /*arguments->arg_list = &state->argv[state->next-1];
        state->next = state->argc;*/
        argp_usage(state);
        break;
H
hzcheng 已提交
265

S
TD-1057  
Shengliang Guan 已提交
266 267 268 269
      default:
        return ARGP_ERR_UNKNOWN;
    }
    return 0;
H
hzcheng 已提交
270
  }
S
TD-1057  
Shengliang Guan 已提交
271 272 273 274

  static struct argp argp = {options, parse_opt, 0, 0};

  void parse_args(int argc, char *argv[], SDemoArguments *arguments) {
H
Hui Li 已提交
275
    argp_parse(&argp, argc, argv, 0, 0, arguments);
S
TD-1057  
Shengliang Guan 已提交
276
    if (arguments->abort) {
S
TD-1057  
Shengliang Guan 已提交
277 278 279 280 281 282 283 284 285 286 287 288
      #ifndef _ALPINE
        error(10, 0, "ABORTED");
      #else
        abort();
      #endif
    }
  }

#else
  void printHelp() {
    char indent[10] = "        ";
    printf("%s%s\n", indent, "-h");
289
    printf("%s%s%s\n", indent, indent, "host, The host to connect to TDengine. Default is localhost.");
S
TD-1057  
Shengliang Guan 已提交
290 291 292
    printf("%s%s\n", indent, "-p");
    printf("%s%s%s\n", indent, indent, "port, The TCP/IP port number to use for the connection. Default is 0.");
    printf("%s%s\n", indent, "-u");
293
    printf("%s%s%s\n", indent, indent, "user, The user name to use when connecting to the server. Default is 'root'.");
S
TD-1057  
Shengliang Guan 已提交
294
    printf("%s%s\n", indent, "-p");
H
Hui Li 已提交
295
    #ifdef _TD_POWER_    
H
Hui Li 已提交
296 297
    printf("%s%s%s\n", indent, indent, "password, The password to use when connecting to the server. Default is 'powerdb'.");
    #else
S
TD-1057  
Shengliang Guan 已提交
298
    printf("%s%s%s\n", indent, indent, "password, The password to use when connecting to the server. Default is 'taosdata'.");
H
Hui Li 已提交
299
    #endif
S
TD-1057  
Shengliang Guan 已提交
300 301
    printf("%s%s\n", indent, "-d");
    printf("%s%s%s\n", indent, indent, "database, Destination database. Default is 'test'.");
302 303
    printf("%s%s\n", indent, "-a");
    printf("%s%s%s\n", indent, indent, "replica, Set the replica parameters of the database, Default 1, min: 1, max: 3.");
S
TD-1057  
Shengliang Guan 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
    printf("%s%s\n", indent, "-m");
    printf("%s%s%s\n", indent, indent, "table_prefix, Table prefix name. Default is 't'.");
    printf("%s%s\n", indent, "-s");
    printf("%s%s%s\n", indent, indent, "sql file, The select sql file.");
    printf("%s%s\n", indent, "-M");
    printf("%s%s%s\n", indent, indent, "meteric, Use metric flag.");
    printf("%s%s\n", indent, "-o");
    printf("%s%s%s\n", indent, indent, "outputfile, Direct output to the named file. Default is './output.txt'.");
    printf("%s%s\n", indent, "-q");
    printf("%s%s%s\n", indent, indent, "query_mode, Query mode--0: SYNC, 1: ASYNC. Default is SYNC.");
    printf("%s%s\n", indent, "-b");
    printf("%s%s%s\n", indent, indent, "type_of_cols, data_type of columns: 'INT', 'TINYINT', 'SMALLINT', 'BIGINT', 'FLOAT', 'DOUBLE', 'BINARY'. Default is 'INT'.");
    printf("%s%s\n", indent, "-w");
    printf("%s%s%s\n", indent, indent, "length_of_binary, The length of data_type 'BINARY'. Only applicable when type of cols is 'BINARY'. Default is 8");
    printf("%s%s\n", indent, "-l");
    printf("%s%s%s\n", indent, indent, "num_of_cols_per_record, The number of columns per record. Default is 3.");
    printf("%s%s\n", indent, "-T");
    printf("%s%s%s\n", indent, indent, "num_of_threads, The number of threads. Default is 10.");
    printf("%s%s\n", indent, "-r");
    printf("%s%s%s\n", indent, indent, "num_of_records_per_req, The number of records per request. Default is 1000.");
    printf("%s%s\n", indent, "-t");
    printf("%s%s%s\n", indent, indent, "num_of_tables, The number of tables. Default is 10000.");
    printf("%s%s\n", indent, "-n");
    printf("%s%s%s\n", indent, indent, "num_of_records_per_table, The number of records per table. Default is 100000.");
    printf("%s%s\n", indent, "-c");
H
Hui Li 已提交
329
    #ifdef _TD_POWER_
H
Hui Li 已提交
330 331
    printf("%s%s%s\n", indent, indent, "config_directory, Configuration directory. Default is '/etc/power/'.");
    #else
S
TD-1057  
Shengliang Guan 已提交
332
    printf("%s%s%s\n", indent, indent, "config_directory, Configuration directory. Default is '/etc/taos/'.");
H
Hui Li 已提交
333
    #endif
S
TD-1057  
Shengliang Guan 已提交
334 335
    printf("%s%s\n", indent, "-x");
    printf("%s%s%s\n", indent, indent, "flag, Insert only flag.");
336 337
    printf("%s%s\n", indent, "-y");
    printf("%s%s%s\n", indent, indent, "flag, Anser Yes for prompt.");
S
TD-1057  
Shengliang Guan 已提交
338 339 340 341 342
    printf("%s%s\n", indent, "-O");
    printf("%s%s%s\n", indent, indent, "order, Insert mode--0: In order, 1: Out of order. Default is in order.");
    printf("%s%s\n", indent, "-R");
    printf("%s%s%s\n", indent, indent, "rate, Out of order data's rate--if order=1 Default 10, min: 0, max: 50.");
    printf("%s%s\n", indent, "-D");
S
Shengliang Guan 已提交
343
    printf("%s%s%s\n", indent, indent, "Delete data methods 0: don't delete, 1: delete by table, 2: delete by stable, 3: delete by database.");
S
TD-1057  
Shengliang Guan 已提交
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
  }

  void parse_args(int argc, char *argv[], SDemoArguments *arguments) {
    char **sptr;
    for (int i = 1; i < argc; i++) {
      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], "-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) {
        sptr = arguments->datatype;
        ++i;
        if (strstr(argv[i], ",") == NULL) {
          if (strcasecmp(argv[i], "INT") != 0 && strcasecmp(argv[i], "FLOAT") != 0 &&
              strcasecmp(argv[i], "TINYINT") != 0 && strcasecmp(argv[i], "BOOL") != 0 &&
              strcasecmp(argv[i], "SMALLINT") != 0 &&
              strcasecmp(argv[i], "BIGINT") != 0 && strcasecmp(argv[i], "DOUBLE") != 0 &&
              strcasecmp(argv[i], "BINARY") && strcasecmp(argv[i], "NCHAR")) {
            fprintf(stderr, "Invalid data_type!\n");
            printHelp();
            exit(EXIT_FAILURE);
          }
          sptr[0] = argv[i];
        } else {
          int index = 0;
          char *dupstr = strdup(argv[i]);
          char *running = dupstr;
          char *token = strsep(&running, ",");
          while (token != NULL) {
            if (strcasecmp(token, "INT") != 0 &&
                strcasecmp(token, "FLOAT") != 0 &&
                strcasecmp(token, "TINYINT") != 0 &&
                strcasecmp(token, "BOOL") != 0 &&
                strcasecmp(token, "SMALLINT") != 0 &&
                strcasecmp(token, "BIGINT") != 0 &&
                strcasecmp(token, "DOUBLE") != 0 && strcasecmp(token, "BINARY") && strcasecmp(token, "NCHAR")) {
              fprintf(stderr, "Invalid data_type!\n");
              printHelp();
              exit(EXIT_FAILURE);
            }
            sptr[index++] = token;
            token = strsep(&running, ",");
            if (index >= MAX_NUM_DATATYPE) break;
          }
        }
      } 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) {
H
Hui Li 已提交
416
        arguments->use_metric = true;
S
TD-1057  
Shengliang Guan 已提交
417
      } else if (strcmp(argv[i], "-x") == 0) {
H
Hui Li 已提交
418
        arguments->insert_only = true;
419 420
      } else if (strcmp(argv[i], "-y") == 0) {
        arguments->answer_yes = true;
S
TD-1057  
Shengliang Guan 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434
      } else if (strcmp(argv[i], "-c") == 0) {
        strcpy(configDir, argv[++i]);
      } else if (strcmp(argv[i], "-O") == 0) {
        arguments->order = atoi(argv[++i]);
        if (arguments->order > 1 || arguments->order < 0) {
          arguments->order = 0;
        } else if (arguments->order == 1) {
          arguments->rate = 10;
        }
      } else if (strcmp(argv[i], "-R") == 0) {
        arguments->rate = atoi(argv[++i]);
        if (arguments->order == 1 && (arguments->rate > 50 || arguments->rate <= 0)) {
          arguments->rate = 10;
        }
435 436 437 438 439
      } else if (strcmp(argv[i], "-a") == 0) {
        arguments->replica = atoi(argv[++i]);
        if (arguments->rate > 3 || arguments->rate < 1) {
          arguments->rate = 1;
        }
S
TD-1057  
Shengliang Guan 已提交
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
      } 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;
        }
      } else if (strcmp(argv[i], "--help") == 0) {
        printHelp();
        exit(EXIT_FAILURE);
      } else {
        fprintf(stderr, "wrong options\n");
        printHelp();
        exit(EXIT_FAILURE);
      }
    }
  }

#endif
H
hzcheng 已提交
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475

/* ******************************* Structure
 * definition*******************************  */
enum MODE {
  SYNC, ASYNC
};
typedef struct {
  TAOS *taos;
  int threadID;
  char db_name[MAX_DB_NAME_SIZE];
  char fp[4096];
  char **datatype;
  int len_of_binary;
  char tb_prefix[MAX_TB_NAME_SIZE];
  int start_table_id;
  int end_table_id;
  int ncols_per_record;
  int nrecords_per_table;
  int nrecords_per_request;
S
Shuaiqiang Chang 已提交
476 477
  int data_of_order;
  int data_of_rate;
S
slguan 已提交
478
  int64_t start_time;
H
hzcheng 已提交
479
  bool do_aggreFunc;
H
Hui Li 已提交
480 481 482
  
  char* cols;  
  bool  use_metric;
H
hzcheng 已提交
483

S
TD-1057  
Shengliang Guan 已提交
484
  tsem_t mutex_sem;
H
hzcheng 已提交
485
  int notFinished;
S
TD-1057  
Shengliang Guan 已提交
486
  tsem_t lock_sem;
Y
yihaoDeng 已提交
487
  int counter;
H
Hui Li 已提交
488 489 490 491 492 493 494 495

  // insert delay statitics
  int64_t cntDelay;
  int64_t totalDelay;
  int64_t avgDelay;
  int64_t maxDelay;
  int64_t minDelay;
  
H
hzcheng 已提交
496 497 498 499 500 501
} info;

typedef struct {
  TAOS  *taos;

  char   tb_name[MAX_TB_NAME_SIZE];
S
slguan 已提交
502
  int64_t   timestamp;
H
hzcheng 已提交
503 504 505 506 507 508
  int    target;
  int    counter;
  int    nrecords_per_request;
  int    ncols_per_record;
  char **data_type;
  int    len_of_binary;
S
Shuaiqiang Chang 已提交
509 510
  int data_of_order;
  int data_of_rate;
H
hzcheng 已提交
511

S
TD-1057  
Shengliang Guan 已提交
512 513 514
  tsem_t *mutex_sem;
  int    *notFinished;
  tsem_t *lock_sem;
H
hzcheng 已提交
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
} sTable;

/* ******************************* Global
 * variables*******************************  */
char *aggreFunc[] = {"*", "count(*)", "avg(f1)", "sum(f1)", "max(f1)", "min(f1)", "first(f1)", "last(f1)"};


void queryDB(TAOS *taos, char *command);

void *readTable(void *sarg);

void *readMetric(void *sarg);

void *syncWrite(void *sarg);

S
Shuaiqiang Chang 已提交
530 531
void *deleteTable();

H
hzcheng 已提交
532 533
void *asyncWrite(void *sarg);

534
int generateData(char *res, char **data_type, int num_of_cols, int64_t timestamp, int len_of_binary);
H
hzcheng 已提交
535 536 537

void rand_string(char *str, int size);

L
Liu Tao 已提交
538 539
void init_rand_data();

H
hzcheng 已提交
540 541 542
double getCurrentTime();

void callBack(void *param, TAOS_RES *res, int code);
H
Hui Li 已提交
543 544
void multiThreadCreateTable(char* cols, bool use_metric, int threads, int ntables, char* db_name, char* tb_prefix, char *ip_addr, uint16_t port, char *user, char *pass);
void querySqlFile(TAOS* taos, char* sqlFile);
H
hzcheng 已提交
545 546

int main(int argc, char *argv[]) {
547
  SDemoArguments arguments = {  NULL,            // host
H
Hongze Cheng 已提交
548 549
                                0,               // port
                                "root",          // user
H
Hui Li 已提交
550
                                #ifdef _TD_POWER_ 
H
Hui Li 已提交
551 552
                                "powerdb",      // password
                                #else
H
Hongze Cheng 已提交
553
                                "taosdata",      // password
H
Hui Li 已提交
554
                                #endif
H
Hongze Cheng 已提交
555
                                "test",          // database
556
                                1,               // replica
H
Hongze Cheng 已提交
557
                                "t",             // tb_prefix
H
Hui Li 已提交
558
                                NULL,
H
Hongze Cheng 已提交
559 560
                                false,           // use_metric
                                false,           // insert_only
561
                                false,           // answer_yes
H
Hongze Cheng 已提交
562 563 564 565
                                "./output.txt",  // output_file
                                0,               // mode
                                {
                                "int",           // datatype
H
Hui Li 已提交
566 567 568 569 570 571 572
                                "int",
                                "int",
                                "int",
                                "int",
                                "int",
                                "int",
                                "float"
H
Hongze Cheng 已提交
573 574 575
                                },
                                8,               // len_of_binary
                                1,               // num_of_CPR
S
Shuaiqiang Chang 已提交
576
                                1,               // num_of_connections/thread
H
Hongze Cheng 已提交
577 578 579 580
                                1,               // num_of_RPR
                                1,               // num_of_tables
                                50000,           // num_of_DPT
                                0,               // abort
S
Shuaiqiang Chang 已提交
581 582
                                0,               // order
                                0,               // rate
S
Shuaiqiang Chang 已提交
583
                                0,               // method_of_delete
H
Hongze Cheng 已提交
584 585
                                NULL             // arg_list
                                };
H
hzcheng 已提交
586 587 588

  /* Parse our arguments; every option seen by parse_opt will be
     reflected in arguments. */
589
  // For demo use, change default values for some parameters;
590
  arguments.num_of_tables = 10000;
591
  arguments.num_of_CPR = 3; 
S
Shuaiqiang Chang 已提交
592
  arguments.num_of_threads = 10;
593 594
  arguments.num_of_DPT = 100000;
  arguments.num_of_RPR = 1000;
595
  arguments.use_metric = true;
H
Hui Li 已提交
596
  arguments.insert_only = false;
597
  arguments.answer_yes = false;
S
slguan 已提交
598
  // end change
599

S
TD-1057  
Shengliang Guan 已提交
600
  parse_args(argc, argv, &arguments);
H
Hui Li 已提交
601

H
hzcheng 已提交
602 603
  enum MODE query_mode = arguments.mode;
  char *ip_addr = arguments.host;
L
lihui 已提交
604
  uint16_t port = arguments.port;
H
hzcheng 已提交
605 606 607 608 609 610
  char *user = arguments.user;
  char *pass = arguments.password;
  char *db_name = arguments.database;
  char *tb_prefix = arguments.tb_prefix;
  int len_of_binary = arguments.len_of_binary;
  int ncols_per_record = arguments.num_of_CPR;
S
Shuaiqiang Chang 已提交
611 612
  int order = arguments.order;
  int rate = arguments.rate;
S
Shuaiqiang Chang 已提交
613
  int method_of_delete = arguments.method_of_delete;
H
hzcheng 已提交
614
  int ntables = arguments.num_of_tables;
S
Shuaiqiang Chang 已提交
615
  int threads = arguments.num_of_threads;
H
hzcheng 已提交
616 617 618 619
  int nrecords_per_table = arguments.num_of_DPT;
  int nrecords_per_request = arguments.num_of_RPR;
  bool use_metric = arguments.use_metric;
  bool insert_only = arguments.insert_only;
620
  bool answer_yes = arguments.answer_yes;
H
hzcheng 已提交
621 622
  char **data_type = arguments.datatype;
  int count_data_type = 0;
623
  char dataString[STRING_LEN];
H
hzcheng 已提交
624
  bool do_aggreFunc = true;
S
TD-1212  
Shengliang Guan 已提交
625
  int replica = arguments.replica;
626

H
Hui Li 已提交
627 628 629 630 631 632
  if (NULL != arguments.sqlFile) {
    TAOS* qtaos = taos_connect(ip_addr, user, pass, db_name, port);
    querySqlFile(qtaos, arguments.sqlFile);  
    taos_close(qtaos);
    return 0;
  }
L
Liu Tao 已提交
633
  init_rand_data();
H
Hui Li 已提交
634

635 636
  memset(dataString, 0, STRING_LEN);
  int len = 0;
637

L
Liu Tao 已提交
638
  if (strcasecmp(data_type[0], "BINARY") == 0 || strcasecmp(data_type[0], "BOOL") == 0 || strcasecmp(data_type[0], "NCHAR") == 0 ) {
H
hzcheng 已提交
639 640 641
    do_aggreFunc = false;
  }
  for (; count_data_type <= MAX_NUM_DATATYPE; count_data_type++) {
T
Tao Liu 已提交
642
    if (data_type[count_data_type] == NULL) {
H
hzcheng 已提交
643 644
      break;
    }
645 646

    len += snprintf(dataString + len, STRING_LEN - len, "%s ", data_type[count_data_type]);
H
hzcheng 已提交
647 648 649
  }

  FILE *fp = fopen(arguments.output_file, "a");
650 651 652 653 654
  if (NULL == fp) {
    fprintf(stderr, "Failed to open %s for writing\n", arguments.output_file);
    return 1;
  };
  
H
hzcheng 已提交
655 656
  time_t tTime = time(NULL);
  struct tm tm = *localtime(&tTime);
S
Shuaiqiang Chang 已提交
657 658 659 660 661 662 663
  printf("###################################################################\n");
  printf("# Server IP:                         %s:%hu\n", ip_addr == NULL ? "localhost" : ip_addr, port);
  printf("# User:                              %s\n", user);
  printf("# Password:                          %s\n", pass);
  printf("# Use metric:                        %s\n", use_metric ? "true" : "false");
  printf("# Datatype of Columns:               %s\n", dataString);
  printf("# Binary Length(If applicable):      %d\n",
S
TD-1057  
Shengliang Guan 已提交
664
         (strncasecmp(dataString, "BINARY", 6) == 0 || strncasecmp(dataString, "NCHAR", 5) == 0) ? len_of_binary : -1);
S
Shuaiqiang Chang 已提交
665
  printf("# Number of Columns per record:      %d\n", ncols_per_record);
S
Shuaiqiang Chang 已提交
666
  printf("# Number of Threads:                 %d\n", threads);
S
Shuaiqiang Chang 已提交
667 668 669 670 671
  printf("# Number of Tables:                  %d\n", ntables);
  printf("# Number of Data per Table:          %d\n", nrecords_per_table);
  printf("# Records/Request:                   %d\n", nrecords_per_request);
  printf("# Database name:                     %s\n", db_name);
  printf("# Table prefix:                      %s\n", tb_prefix);
S
Shuaiqiang Chang 已提交
672 673
  if (order == 1)
  {
S
Shuaiqiang Chang 已提交
674 675
    printf("# Data order:                        %d\n", order);
    printf("# Data out of order rate:            %d\n", rate);
S
Shuaiqiang Chang 已提交
676 677

  }
S
Shuaiqiang Chang 已提交
678
  printf("# Delete method:                     %d\n", method_of_delete);
S
Shuaiqiang Chang 已提交
679 680
  printf("# Test time:                         %d-%02d-%02d %02d:%02d:%02d\n", tm.tm_year + 1900, tm.tm_mon + 1,
          tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
681 682 683 684 685 686

  if (!answer_yes) {
    printf("###################################################################\n\n");
    printf("Press enter key to continue");
    (void)getchar();
  }
H
hzcheng 已提交
687 688

  fprintf(fp, "###################################################################\n");
L
lihui 已提交
689
  fprintf(fp, "# Server IP:                         %s:%hu\n", ip_addr == NULL ? "localhost" : ip_addr, port);
H
hzcheng 已提交
690 691 692 693 694
  fprintf(fp, "# User:                              %s\n", user);
  fprintf(fp, "# Password:                          %s\n", pass);
  fprintf(fp, "# Use metric:                        %s\n", use_metric ? "true" : "false");
  fprintf(fp, "# Datatype of Columns:               %s\n", dataString);
  fprintf(fp, "# Binary Length(If applicable):      %d\n",
S
TD-1057  
Shengliang Guan 已提交
695
         (strncasecmp(dataString, "BINARY", 6) == 0 || strncasecmp(dataString, "NCHAR", 5) == 0) ? len_of_binary : -1);
H
hzcheng 已提交
696
  fprintf(fp, "# Number of Columns per record:      %d\n", ncols_per_record);
S
Shuaiqiang Chang 已提交
697
  fprintf(fp, "# Number of Threads:                 %d\n", threads);
H
hzcheng 已提交
698 699 700 701 702
  fprintf(fp, "# Number of Tables:                  %d\n", ntables);
  fprintf(fp, "# Number of Data per Table:          %d\n", nrecords_per_table);
  fprintf(fp, "# Records/Request:                   %d\n", nrecords_per_request);
  fprintf(fp, "# Database name:                     %s\n", db_name);
  fprintf(fp, "# Table prefix:                      %s\n", tb_prefix);
S
Shuaiqiang Chang 已提交
703 704 705 706 707 708
  if (order == 1)
  {
    printf("# Data order:                        %d\n", order);
    printf("# Data out of order rate:            %d\n", rate);

  }
H
hzcheng 已提交
709 710 711 712 713 714 715 716
  fprintf(fp, "# Test time:                         %d-%02d-%02d %02d:%02d:%02d\n", tm.tm_year + 1900, tm.tm_mon + 1,
          tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
  fprintf(fp, "###################################################################\n\n");
  fprintf(fp, "|  WRecords  | Records/Second | Requests/Second |  WLatency(ms) |\n");

  taos_init();
  TAOS *taos = taos_connect(ip_addr, user, pass, NULL, port);
  if (taos == NULL) {
S
Shuaiqiang Chang 已提交
717
    fprintf(stderr, "Failed to connect to TDengine, reason:%s\n", taos_errstr(NULL));
H
hzcheng 已提交
718 719 720 721 722
    return 1;
  }
  char command[BUFFER_SIZE] = "\0";

  sprintf(command, "drop database %s;", db_name);
723 724
  TAOS_RES* res = taos_query(taos, command);
  taos_free_result(res);
H
hzcheng 已提交
725

S
TD-1212  
Shengliang Guan 已提交
726
  sprintf(command, "create database %s replica %d;", db_name, replica);
727 728
  res = taos_query(taos, command);
  taos_free_result(res);
H
hzcheng 已提交
729

730
  char cols[STRING_LEN] = "\0";
H
hzcheng 已提交
731
  int colIndex = 0;
732
  len = 0;
H
hzcheng 已提交
733 734

  for (; colIndex < ncols_per_record - 1; colIndex++) {
L
Liu Tao 已提交
735
    if (strcasecmp(data_type[colIndex % count_data_type], "BINARY") != 0 && strcasecmp(data_type[colIndex % count_data_type], "NCHAR") != 0) {
736
      len += snprintf(cols + len, STRING_LEN - len, ",f%d %s", colIndex + 1, data_type[colIndex % count_data_type]);
H
hzcheng 已提交
737
    } else {
738
      len += snprintf(cols + len, STRING_LEN - len, ",f%d %s(%d)", colIndex + 1, data_type[colIndex % count_data_type], len_of_binary);
H
hzcheng 已提交
739 740 741
    }
  }

T
Tao Liu 已提交
742 743
  if (strcasecmp(data_type[colIndex % count_data_type], "BINARY") != 0 && strcasecmp(data_type[colIndex % count_data_type], "NCHAR") != 0){
    len += snprintf(cols + len, STRING_LEN - len, ",f%d %s", colIndex + 1, data_type[colIndex % count_data_type]);
H
hzcheng 已提交
744
  } else {
T
Tao Liu 已提交
745
    len += snprintf(cols + len, STRING_LEN - len, ",f%d %s(%d)", colIndex + 1, data_type[colIndex % count_data_type], len_of_binary);
H
hzcheng 已提交
746 747
  }

H
Hui Li 已提交
748
  if (use_metric) {
H
hzcheng 已提交
749
    /* Create metric table */
750
    printf("Creating meters super table...\n");
T
Tao Liu 已提交
751
    snprintf(command, BUFFER_SIZE, "create table if not exists %s.meters (ts timestamp%s) tags (areaid int, loc binary(10))", db_name, cols);
H
hzcheng 已提交
752
    queryDB(taos, command);
753
    printf("meters created!\n");
H
hzcheng 已提交
754
  }
H
Hui Li 已提交
755
  taos_close(taos);
H
Hui Li 已提交
756
  
H
hzcheng 已提交
757
  /* Wait for table to create  */
H
Hui Li 已提交
758
  multiThreadCreateTable(cols, use_metric, threads, ntables, db_name, tb_prefix, ip_addr, port, user, pass);
S
Shuaiqiang Chang 已提交
759
  
H
hzcheng 已提交
760 761 762
  /* Insert data */
  double ts = getCurrentTime();
  printf("Inserting data......\n");
S
Shuaiqiang Chang 已提交
763 764
  pthread_t *pids = malloc(threads * sizeof(pthread_t));
  info *infos = malloc(threads * sizeof(info));
H
Hui Li 已提交
765 766 767
  
  memset(pids, 0, threads * sizeof(pthread_t));
  memset(infos, 0, threads * sizeof(info));
H
hzcheng 已提交
768

S
Shuaiqiang Chang 已提交
769
  int a = ntables / threads;
H
hzcheng 已提交
770
  if (a < 1) {
S
Shuaiqiang Chang 已提交
771
    threads = ntables;
H
hzcheng 已提交
772 773
    a = 1;
  }
S
Shuduo Sang 已提交
774 775 776 777

  int b = 0;
  if (threads != 0)
    b = ntables % threads;
H
hzcheng 已提交
778
  int last = 0;
S
Shuaiqiang Chang 已提交
779
  for (int i = 0; i < threads; i++) {
H
hzcheng 已提交
780 781
    info *t_info = infos + i;
    t_info->threadID = i;
H
Hui Li 已提交
782 783
    tstrncpy(t_info->db_name, db_name, MAX_DB_NAME_SIZE);
    tstrncpy(t_info->tb_prefix, tb_prefix, MAX_TB_NAME_SIZE);
H
hzcheng 已提交
784 785 786 787 788 789 790 791
    t_info->datatype = data_type;
    t_info->ncols_per_record = ncols_per_record;
    t_info->nrecords_per_table = nrecords_per_table;
    t_info->start_time = 1500000000000;
    t_info->taos = taos_connect(ip_addr, user, pass, db_name, port);
    t_info->len_of_binary = len_of_binary;
    t_info->nrecords_per_request = nrecords_per_request;
    t_info->start_table_id = last;
S
Shuaiqiang Chang 已提交
792 793
    t_info->data_of_order = order;
    t_info->data_of_rate = rate;
H
hzcheng 已提交
794 795
    t_info->end_table_id = i < b ? last + a : last + a - 1;
    last = t_info->end_table_id + 1;
Y
yihaoDeng 已提交
796
    t_info->counter = 0;
H
Hui Li 已提交
797
    t_info->minDelay = INT16_MAX;
H
hzcheng 已提交
798

S
TD-1057  
Shengliang Guan 已提交
799
    tsem_init(&(t_info->mutex_sem), 0, 1);
H
hzcheng 已提交
800
    t_info->notFinished = t_info->end_table_id - t_info->start_table_id + 1;
S
TD-1057  
Shengliang Guan 已提交
801
    tsem_init(&(t_info->lock_sem), 0, 0);
H
hzcheng 已提交
802 803 804 805 806 807 808

    if (query_mode == SYNC) {
      pthread_create(pids + i, NULL, syncWrite, t_info);
    } else {
      pthread_create(pids + i, NULL, asyncWrite, t_info);
    }
  }
S
Shuaiqiang Chang 已提交
809
  for (int i = 0; i < threads; i++) {
H
hzcheng 已提交
810 811 812 813 814
    pthread_join(pids[i], NULL);
  }

  double t = getCurrentTime() - ts;
  if (query_mode == SYNC) {
S
Shuaiqiang Chang 已提交
815
    printf("SYNC Insert with %d connections:\n", threads);
H
hzcheng 已提交
816
  } else {
S
Shuaiqiang Chang 已提交
817
    printf("ASYNC Insert with %d connections:\n", threads);
H
hzcheng 已提交
818 819
  }

Y
yihaoDeng 已提交
820 821 822
  fprintf(fp, "|%"PRIu64"  |  %10.2f    |  %10.2f     |  %10.4f   |\n\n",
          (int64_t)ntables * nrecords_per_table, ntables * nrecords_per_table / t,
          ((int64_t)ntables * nrecords_per_table) / (t * nrecords_per_request),
H
hzcheng 已提交
823 824
          t * 1000);

Y
yihaoDeng 已提交
825 826 827
  printf("Spent %.4f seconds to insert %"PRIu64" records with %d record(s) per request: %.2f records/second\n",
         t, (int64_t)ntables * nrecords_per_table, nrecords_per_request,
         (int64_t)ntables * nrecords_per_table / t);
H
hzcheng 已提交
828

H
Hui Li 已提交
829 830 831 832 833
  int64_t totalDelay = 0;
  int64_t maxDelay = 0;
  int64_t minDelay = INT16_MAX;
  int64_t cntDelay = 0;
  double  avgDelay = 0;
S
Shuaiqiang Chang 已提交
834
  for (int i = 0; i < threads; i++) {
H
hzcheng 已提交
835 836
    info *t_info = infos + i;
    taos_close(t_info->taos);
S
TD-1057  
Shengliang Guan 已提交
837 838
    tsem_destroy(&(t_info->mutex_sem));
    tsem_destroy(&(t_info->lock_sem));
H
Hui Li 已提交
839 840 841 842 843

    totalDelay += t_info->totalDelay;
    cntDelay   += t_info->cntDelay;
    if (t_info->maxDelay > maxDelay) maxDelay = t_info->maxDelay;
    if (t_info->minDelay < minDelay) minDelay = t_info->minDelay;    
H
hzcheng 已提交
844
  }
H
Hui Li 已提交
845 846 847 848 849 850 851
  avgDelay = (double)totalDelay / cntDelay;

  fprintf(fp, "insert delay, avg:%10.6fms, max: %10.6fms, min: %10.6fms\n\n",
          avgDelay/1000.0, (double)maxDelay/1000.0, (double)minDelay/1000.0);

  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);
H
hzcheng 已提交
852 853 854 855 856

  free(pids);
  free(infos);
  fclose(fp);

S
Shuaiqiang Chang 已提交
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
  if (method_of_delete != 0)
  {
    TAOS *dtaos = taos_connect(ip_addr, user, pass, db_name, port);
    double dts = getCurrentTime();
    printf("Deleteing %d table(s)......\n", ntables);

    switch (method_of_delete)
    {
    case 1:
      // delete by table
      /* Create all the tables; */
      for (int i = 0; i < ntables; i++) {
        sprintf(command, "drop table %s.%s%d;", db_name, tb_prefix, i);
        queryDB(dtaos, command);
      }
      break;
    case 2:
      // delete by stable
      if (!use_metric) {
        break;
      }
      else
      {
        sprintf(command, "drop table %s.meters;", db_name);
        queryDB(dtaos, command);
      }
      break;
    case 3:
      // delete by database
      sprintf(command, "drop database %s;", db_name);
      queryDB(dtaos, command);
      break;
    default:
      break;
    }

    printf("Table(s) droped!\n");
    taos_close(dtaos);

    double dt = getCurrentTime() - dts;
    printf("Spent %.4f seconds to drop %d tables\n", dt, ntables);

    FILE *fp = fopen(arguments.output_file, "a");
    fprintf(fp, "Spent %.4f seconds to drop %d tables\n", dt, ntables);
    fclose(fp);

  }
  

H
Hui Li 已提交
906
  if (false == insert_only) {
H
hzcheng 已提交
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
    // query data
    pthread_t read_id;
    info *rInfo = malloc(sizeof(info));
    rInfo->start_time = 1500000000000;
    rInfo->start_table_id = 0;
    rInfo->end_table_id = ntables - 1;
    rInfo->do_aggreFunc = do_aggreFunc;
    rInfo->nrecords_per_table = nrecords_per_table;
    rInfo->taos = taos_connect(ip_addr, user, pass, db_name, port);
    strcpy(rInfo->tb_prefix, tb_prefix);
    strcpy(rInfo->fp, arguments.output_file);

    if (!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);
Y
yihaoDeng 已提交
926
    free(rInfo);
H
hzcheng 已提交
927 928
  }

929
  taos_cleanup();
H
hzcheng 已提交
930 931 932
  return 0;
}

H
Hui Li 已提交
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 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
#define MAX_SQL_SIZE       65536
void selectSql(TAOS* taos, char* sqlcmd)
{    
  TAOS_RES *pSql = taos_query(taos, sqlcmd);
  int32_t code = taos_errno(pSql);
  
  if (code != 0) {
    printf("Failed to sqlcmd:%s, reason:%s\n", sqlcmd, taos_errstr(pSql));
    taos_free_result(pSql);
    exit(1);
  }
  
  int count = 0;
  while (taos_fetch_row(pSql) != NULL) {
    count++;
  }
  
  taos_free_result(pSql);
  return;
}


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

  /* Compile regular expression */
  if (regcomp(&regex, reg, cflags) != 0) {
    printf("Fail to compile regex\n");
    exit(-1);
  }

  /* 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));
    exit(-1);
  }
  
  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();
  
S
TD-1848  
Shengliang Guan 已提交
1006
  while ((read_len = tgetline(&line, &line_len, fp)) != -1) {
H
Hui Li 已提交
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045
    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;
    }

    memcpy(cmd + cmd_len, line, read_len);
    selectSql(taos, cmd);    
    memset(cmd, 0, MAX_SQL_SIZE);
    cmd_len = 0;
  }

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

  free(cmd);
  if (line) free(line);
  fclose(fp);
  return;
}

void * createTable(void *sarg) 
{
  char command[BUFFER_SIZE] = "\0";
  
  info *winfo = (info *)sarg;  

  if (!winfo->use_metric) {
    /* Create all the tables; */
    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++) {
H
Hui Li 已提交
1046
      snprintf(command, BUFFER_SIZE, "create table if not exists %s.%s%d (ts timestamp%s);", winfo->db_name, winfo->tb_prefix, i, winfo->cols);
H
Hui Li 已提交
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
      queryDB(winfo->taos, command);
    }
  } else {
    /* Create all the tables; */
    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++) {
      int j;
      if (i % 10 == 0) {
        j = 10;
      } else {
        j = i % 10;
      }
    if (j % 2 == 0) {
      snprintf(command, BUFFER_SIZE, "create table if not exists %s.%s%d using %s.meters tags (%d,\"%s\");", winfo->db_name, winfo->tb_prefix, i, winfo->db_name, j, "shanghai");
    } else {
      snprintf(command, BUFFER_SIZE, "create table if not exists %s.%s%d using %s.meters tags (%d,\"%s\");", winfo->db_name, winfo->tb_prefix, i, winfo->db_name, j, "beijing");
    }
      queryDB(winfo->taos, command);
    }
  }

  return NULL;
}

void multiThreadCreateTable(char* cols, bool use_metric, int threads, int ntables, char* db_name, char* tb_prefix, char *ip_addr, uint16_t port, char *user, char *pass) {
  double ts = getCurrentTime();
  printf("create table......\n");
  pthread_t *pids = malloc(threads * sizeof(pthread_t));
  info *infos = malloc(threads * sizeof(info));

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

  int b = 0;
  if (threads != 0)
    b = ntables % threads;
  int last = 0;
  for (int i = 0; i < threads; i++) {
    info *t_info = infos + i;
    t_info->threadID = i;
    tstrncpy(t_info->db_name, db_name, MAX_DB_NAME_SIZE);
    tstrncpy(t_info->tb_prefix, tb_prefix, MAX_TB_NAME_SIZE);
    t_info->taos = taos_connect(ip_addr, user, pass, db_name, port);
    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->use_metric = use_metric;
    t_info->cols = cols;
    pthread_create(pids + i, NULL, createTable, t_info);
  }
  
  for (int i = 0; i < threads; i++) {
    pthread_join(pids[i], NULL);
  }

  double t = getCurrentTime() - ts;
  printf("Spent %.4f seconds to create %d tables with %d connections\n", t, ntables, threads);

  for (int i = 0; i < threads; i++) {
    info *t_info = infos + i;
S
TD-1057  
Shengliang Guan 已提交
1110 1111
    tsem_destroy(&(t_info->mutex_sem));
    tsem_destroy(&(t_info->lock_sem));
H
Hui Li 已提交
1112 1113 1114 1115 1116 1117 1118 1119
  }

  free(pids);
  free(infos);  

  return ;
}

H
hzcheng 已提交
1120 1121 1122 1123
void *readTable(void *sarg) {
  info *rinfo = (info *)sarg;
  TAOS *taos = rinfo->taos;
  char command[BUFFER_SIZE] = "\0";
S
slguan 已提交
1124
  int64_t sTime = rinfo->start_time;
H
hzcheng 已提交
1125 1126
  char *tb_prefix = rinfo->tb_prefix;
  FILE *fp = fopen(rinfo->fp, "a");
H
Hui Li 已提交
1127 1128 1129 1130 1131
  if (NULL == fp) {
    printf("fopen %s fail, reason:%s.\n", rinfo->fp, strerror(errno));
    return NULL;
  }
  
H
hzcheng 已提交
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
  int num_of_DPT = rinfo->nrecords_per_table;
  int num_of_tables = rinfo->end_table_id - rinfo->start_table_id + 1;
  int totalData = num_of_DPT * num_of_tables;
  bool do_aggreFunc = rinfo->do_aggreFunc;

  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 已提交
1148
      sprintf(command, "select %s from %s%d where ts>= %" PRId64, aggreFunc[j], tb_prefix, i, sTime);
H
hzcheng 已提交
1149 1150

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

S
Shuaiqiang Chang 已提交
1154
      if (code != 0) {
H
Haojun Liao 已提交
1155
        fprintf(stderr, "Failed to query:%s\n", taos_errstr(pSql));
S
Shuaiqiang Chang 已提交
1156
        taos_free_result(pSql);
H
hzcheng 已提交
1157
        taos_close(taos);
S
Shuaiqiang Chang 已提交
1158
        exit(EXIT_FAILURE);
H
hzcheng 已提交
1159 1160
      }

S
Shuaiqiang Chang 已提交
1161
      while (taos_fetch_row(pSql) != NULL) {
H
hzcheng 已提交
1162 1163 1164 1165 1166 1167
        count++;
      }

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

S
Shuaiqiang Chang 已提交
1168
      taos_free_result(pSql);
H
hzcheng 已提交
1169 1170 1171
    }

    fprintf(fp, "|%10s  |   %10d   |  %12.2f   |   %10.2f  |\n",
S
slguan 已提交
1172
            aggreFunc[j][0] == '*' ? "   *   " : aggreFunc[j], totalData,
H
hzcheng 已提交
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
            (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);
  return NULL;
}

void *readMetric(void *sarg) {
  info *rinfo = (info *)sarg;
  TAOS *taos = rinfo->taos;
  char command[BUFFER_SIZE] = "\0";
  FILE *fp = fopen(rinfo->fp, "a");
H
Hui Li 已提交
1187 1188 1189 1190 1191
  if (NULL == fp) {
    printf("fopen %s fail, reason:%s.\n", rinfo->fp, strerror(errno));
    return NULL;
  }
  
H
hzcheng 已提交
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
  int num_of_DPT = rinfo->nrecords_per_table;
  int num_of_tables = rinfo->end_table_id - rinfo->start_table_id + 1;
  int totalData = num_of_DPT * num_of_tables;
  bool do_aggreFunc = rinfo->do_aggreFunc;

  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 已提交
1205
    char condition[BUFFER_SIZE - 30] = "\0";
B
Bomin Zhang 已提交
1206
    char tempS[64] = "\0";
H
hzcheng 已提交
1207 1208 1209 1210 1211

    int m = 10 < num_of_tables ? 10 : num_of_tables;

    for (int i = 1; i <= m; i++) {
      if (i == 1) {
L
liu0x54 已提交
1212
        sprintf(tempS, "areaid = %d", i);
H
hzcheng 已提交
1213
      } else {
L
liu0x54 已提交
1214
        sprintf(tempS, " or areaid = %d ", i);
H
hzcheng 已提交
1215 1216 1217
      }
      strcat(condition, tempS);

L
liu0x54 已提交
1218
      sprintf(command, "select %s from meters where %s", aggreFunc[j], condition);
H
hzcheng 已提交
1219 1220 1221 1222 1223 1224

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

      double t = getCurrentTime();

S
Shuaiqiang Chang 已提交
1225 1226 1227 1228
      TAOS_RES *pSql = taos_query(taos, command);
      int32_t code = taos_errno(pSql);

      if (code != 0) {
H
Haojun Liao 已提交
1229
        fprintf(stderr, "Failed to query:%s\n", taos_errstr(pSql));
S
Shuaiqiang Chang 已提交
1230
        taos_free_result(pSql);
H
hzcheng 已提交
1231 1232 1233 1234
        taos_close(taos);
        exit(1);
      }
      int count = 0;
S
Shuaiqiang Chang 已提交
1235
      while (taos_fetch_row(pSql) != NULL) {
H
hzcheng 已提交
1236 1237 1238 1239 1240 1241 1242
        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 已提交
1243
      taos_free_result(pSql);
H
hzcheng 已提交
1244 1245 1246 1247 1248 1249 1250 1251
    }
    fprintf(fp, "\n");
  }

  fclose(fp);
  return NULL;
}

H
Hui Li 已提交
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
static int queryDbExec(TAOS *taos, char *command, int type) {
  int i;
  TAOS_RES *res = NULL;
  int32_t   code = -1;

  for (i = 0; i < 5; i++) {
    if (NULL != res) {
      taos_free_result(res);
      res = NULL;
    }
    
    res = taos_query(taos, command);
    code = taos_errno(res);
    if (0 == code) {
      break;
    }    
  }

  if (code != 0) {
    fprintf(stderr, "Failed to run %s, reason: %s\n", command, taos_errstr(res));
    taos_free_result(res);
    //taos_close(taos);
    return -1;
  }

  if (1 == type) {
    int affectedRows = taos_affected_rows(res);
    taos_free_result(res);
    return affectedRows;
  }
  
  taos_free_result(res);
  return 0;
}

H
hzcheng 已提交
1287
void queryDB(TAOS *taos, char *command) {
H
Hui Li 已提交
1288
  int i;
S
Shuaiqiang Chang 已提交
1289
  TAOS_RES *pSql = NULL;
H
Hui Li 已提交
1290 1291 1292 1293 1294 1295 1296 1297
  int32_t   code = -1;

  for (i = 0; i < 5; i++) {
    if (NULL != pSql) {
      taos_free_result(pSql);
      pSql = NULL;
    }
    
S
Shuaiqiang Chang 已提交
1298 1299
    pSql = taos_query(taos, command);
    code = taos_errno(pSql);
H
Hui Li 已提交
1300
    if (0 == code) {
S
Shuaiqiang Chang 已提交
1301
      break;
H
Hui Li 已提交
1302
    }    
1303
  }
S
Shuaiqiang Chang 已提交
1304

dengyihao's avatar
dengyihao 已提交
1305
  if (code != 0) {
H
Haojun Liao 已提交
1306 1307
    fprintf(stderr, "Failed to run %s, reason: %s\n", command, taos_errstr(pSql));
    taos_free_result(pSql);
H
hzcheng 已提交
1308 1309 1310
    taos_close(taos);
    exit(EXIT_FAILURE);
  }
H
Hui Li 已提交
1311 1312

  taos_free_result(pSql);
H
hzcheng 已提交
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
}

// sync insertion
void *syncWrite(void *sarg) {
  info *winfo = (info *)sarg;
  char buffer[BUFFER_SIZE] = "\0";
  char data[MAX_DATA_SIZE];
  char **data_type = winfo->datatype;
  int len_of_binary = winfo->len_of_binary;
  int ncols_per_record = winfo->ncols_per_record;
S
TD-1057  
Shengliang Guan 已提交
1323
  srand((uint32_t)time(NULL));
S
slguan 已提交
1324
  int64_t time_counter = winfo->start_time;
H
hzcheng 已提交
1325 1326 1327
  for (int i = 0; i < winfo->nrecords_per_table;) {
    for (int tID = winfo->start_table_id; tID <= winfo->end_table_id; tID++) {
      int inserted = i;
S
slguan 已提交
1328
      int64_t tmp_time = time_counter;
H
hzcheng 已提交
1329 1330 1331 1332 1333

      char *pstr = buffer;
      pstr += sprintf(pstr, "insert into %s.%s%d values", winfo->db_name, winfo->tb_prefix, tID);
      int k;
      for (k = 0; k < winfo->nrecords_per_request;) {
1334
        int rand_num = rand() % 100;
1335 1336
        int len = -1;
        if (winfo->data_of_order ==1 && rand_num < winfo->data_of_rate) {
S
TD-1057  
Shengliang Guan 已提交
1337
          int64_t d = tmp_time - rand() % 1000000 + rand_num;
1338 1339 1340
          len = generateData(data, data_type, ncols_per_record, d, len_of_binary);
        } else {
          len = generateData(data, data_type, ncols_per_record, tmp_time += 1000, len_of_binary);
S
Shuaiqiang Chang 已提交
1341
        }
1342 1343 1344 1345 1346 1347

        //assert(len + pstr - buffer < BUFFER_SIZE);
        if (len + pstr - buffer >= BUFFER_SIZE) { // too long
          break;
        }

H
hzcheng 已提交
1348 1349 1350 1351 1352 1353 1354 1355
        pstr += sprintf(pstr, " %s", data);
        inserted++;
        k++;

        if (inserted >= winfo->nrecords_per_table) break;
      }

      /* puts(buffer); */
H
Hui Li 已提交
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
      int64_t startTs;
      int64_t endTs;
      startTs = taosGetTimestampUs();
      //queryDB(winfo->taos, buffer);
      int affectedRows = queryDbExec(winfo->taos, buffer, 1);
      
      if (0 <= affectedRows){
        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;
        //winfo->avgDelay = (double)winfo->totalDelay / winfo->cntDelay;      
      }      
H
hzcheng 已提交
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382

      if (tID == winfo->end_table_id) {
        i = inserted;
        time_counter = tmp_time;
      }
    }
  }
  return NULL;
}

void *asyncWrite(void *sarg) {
  info *winfo = (info *)sarg;
Y
yihaoDeng 已提交
1383
  taos_query_a(winfo->taos, "show databases", callBack, winfo);
H
hzcheng 已提交
1384

S
TD-1057  
Shengliang Guan 已提交
1385
  tsem_wait(&(winfo->lock_sem));
H
hzcheng 已提交
1386 1387 1388 1389 1390

  return NULL;
}

void callBack(void *param, TAOS_RES *res, int code) {
Y
yihaoDeng 已提交
1391 1392 1393 1394
  info* winfo = (info*)param; 
  char **datatype = winfo->datatype;
  int ncols_per_record = winfo->ncols_per_record;
  int len_of_binary = winfo->len_of_binary;
H
hzcheng 已提交
1395

Y
yihaoDeng 已提交
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
  int64_t tmp_time = winfo->start_time;
  char *buffer = calloc(1, BUFFER_SIZE);
  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);
  if (winfo->counter >= winfo->nrecords_per_table) {
    winfo->start_table_id++;
    winfo->counter = 0;
  }
  if (winfo->start_table_id > winfo->end_table_id) {
    tsem_post(&winfo->lock_sem);
Y
yihaoDeng 已提交
1407 1408
    free(buffer);
    free(data);
1409
    taos_free_result(res);
H
hzcheng 已提交
1410 1411
    return;
  }
Y
yihaoDeng 已提交
1412 1413
  
  for (int i = 0; i < winfo->nrecords_per_request; i++) {
1414
    int rand_num = rand() % 100;
Y
yihaoDeng 已提交
1415
    if (winfo->data_of_order ==1 && rand_num < winfo->data_of_rate)
S
Shuaiqiang Chang 已提交
1416
    {
S
TD-1057  
Shengliang Guan 已提交
1417
      int64_t d = tmp_time - rand() % 1000000 + rand_num;
S
Shuaiqiang Chang 已提交
1418 1419 1420 1421 1422
      generateData(data, datatype, ncols_per_record, d, len_of_binary);
    } else 
    {
      generateData(data, datatype, ncols_per_record, tmp_time += 1000, len_of_binary);
    }
H
hzcheng 已提交
1423
    pstr += sprintf(pstr, "%s", data);
Y
yihaoDeng 已提交
1424
    winfo->counter++;
H
hzcheng 已提交
1425

Y
yihaoDeng 已提交
1426
    if (winfo->counter >= winfo->nrecords_per_table) {
H
hzcheng 已提交
1427 1428 1429
      break;
    }
  }
Y
yihaoDeng 已提交
1430 1431 1432
  taos_query_a(winfo->taos, buffer, callBack, winfo);
  free(buffer);
  free(data);
H
hzcheng 已提交
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446

  taos_free_result(res);
}

double getCurrentTime() {
  struct timeval tv;
  if (gettimeofday(&tv, NULL) != 0) {
    perror("Failed to get current time in ms");
    exit(EXIT_FAILURE);
  }

  return tv.tv_sec + tv.tv_usec / 1E6;
}

L
Liu Tao 已提交
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
int32_t  randint[MAX_PREPARED_RAND];
int64_t  randbigint[MAX_PREPARED_RAND];
float  randfloat[MAX_PREPARED_RAND];
double  randdouble[MAX_PREPARED_RAND];

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

}

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

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

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

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

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

}

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

1507
int32_t generateData(char *res, char **data_type, int num_of_cols, int64_t timestamp, int len_of_binary) {
H
hzcheng 已提交
1508 1509
  memset(res, 0, MAX_DATA_SIZE);
  char *pstr = res;
L
lihui 已提交
1510
  pstr += sprintf(pstr, "(%" PRId64, timestamp);
H
hzcheng 已提交
1511 1512 1513
  int c = 0;

  for (; c < MAX_NUM_DATATYPE; c++) {
T
Tao Liu 已提交
1514
    if (data_type[c] == NULL) {
H
hzcheng 已提交
1515 1516 1517 1518
      break;
    }
  }

H
Hui Li 已提交
1519 1520 1521 1522 1523
  if (0 == c) {
    perror("data type error!");
    exit(-1);
  }

H
hzcheng 已提交
1524 1525
  for (int i = 0; i < num_of_cols; i++) {
    if (strcasecmp(data_type[i % c], "tinyint") == 0) {
L
Liu Tao 已提交
1526
      pstr += sprintf(pstr, ", %d", rand_tinyint() );
H
hzcheng 已提交
1527
    } else if (strcasecmp(data_type[i % c], "smallint") == 0) {
L
Liu Tao 已提交
1528
      pstr += sprintf(pstr, ", %d", rand_smallint());
H
hzcheng 已提交
1529
    } else if (strcasecmp(data_type[i % c], "int") == 0) {
L
Liu Tao 已提交
1530
      pstr += sprintf(pstr, ", %d", rand_int()); 
H
hzcheng 已提交
1531
    } else if (strcasecmp(data_type[i % c], "bigint") == 0) {
L
Liu Tao 已提交
1532
      pstr += sprintf(pstr, ", %" PRId64, rand_bigint());
H
hzcheng 已提交
1533
    } else if (strcasecmp(data_type[i % c], "float") == 0) {
L
Liu Tao 已提交
1534
      pstr += sprintf(pstr, ", %10.4f", rand_float());
H
hzcheng 已提交
1535
    } else if (strcasecmp(data_type[i % c], "double") == 0) {
L
Liu Tao 已提交
1536
      double t = rand_double();
H
hzcheng 已提交
1537 1538
      pstr += sprintf(pstr, ", %20.8f", t);
    } else if (strcasecmp(data_type[i % c], "bool") == 0) {
1539
      bool b = rand() & 1;
H
hzcheng 已提交
1540 1541
      pstr += sprintf(pstr, ", %s", b ? "true" : "false");
    } else if (strcasecmp(data_type[i % c], "binary") == 0) {
S
TD-1057  
Shengliang Guan 已提交
1542
      char *s = malloc(len_of_binary);
H
hzcheng 已提交
1543
      rand_string(s, len_of_binary);
F
fang 已提交
1544
      pstr += sprintf(pstr, ", \"%s\"", s);
S
TD-1057  
Shengliang Guan 已提交
1545
      free(s);
L
Liu Tao 已提交
1546
    }else if (strcasecmp(data_type[i % c], "nchar") == 0) {
S
TD-1057  
Shengliang Guan 已提交
1547
      char *s = malloc(len_of_binary);
L
Liu Tao 已提交
1548 1549
      rand_string(s, len_of_binary);
      pstr += sprintf(pstr, ", \"%s\"", s);
S
TD-1057  
Shengliang Guan 已提交
1550
      free(s);
H
hzcheng 已提交
1551
    }
1552 1553 1554 1555 1556

    if (pstr - res > MAX_DATA_SIZE) {
      perror("column length too long, abort");
      exit(-1);
    }
H
hzcheng 已提交
1557 1558 1559
  }

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

S
TD-1057  
Shengliang Guan 已提交
1561
  return (int32_t)(pstr - res);
H
hzcheng 已提交
1562 1563
}

S
Shuaiqiang Chang 已提交
1564
static const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJK1234567890";
H
hzcheng 已提交
1565
void rand_string(char *str, int size) {
S
Shuaiqiang Chang 已提交
1566 1567
  str[0] = 0;
  if (size > 0) {
H
hzcheng 已提交
1568
    --size;
S
Shuaiqiang Chang 已提交
1569 1570
    int n;
    for (n = 0; n < size; n++) {
1571
      int key = rand() % (int)(sizeof charset - 1);
S
Shuaiqiang Chang 已提交
1572
      str[n] = charset[key];
H
hzcheng 已提交
1573
    }
S
Shuaiqiang Chang 已提交
1574
    str[n] = 0;
H
hzcheng 已提交
1575 1576
  }
}