shellEngine.c 29.7 KB
Newer Older
H
hzcheng 已提交
1 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/>.
 */

wafwerar's avatar
wafwerar 已提交
16
#define ALLOW_FORBID_FUNC
17 18
#define _BSD_SOURCE
#define _GNU_SOURCE
H
hzcheng 已提交
19
#define _XOPEN_SOURCE
S
slguan 已提交
20
#define _DEFAULT_SOURCE
S
Shengliang Guan 已提交
21
#include "shellInt.h"
H
hzcheng 已提交
22

23 24
static bool    shellIsEmptyCommand(const char *cmd);
static int32_t shellRunSingleCommand(char *command);
25 26
static void    shellRecordCommandToHistory(char *command);
static int32_t shellRunCommand(char *command, bool recordHistory);
27 28 29 30
static void    shellRunSingleCommandImp(char *command);
static char   *shellFormatTimestamp(char *buf, int64_t val, int32_t precision);
static int32_t shellDumpResultToFile(const char *fname, TAOS_RES *tres);
static void    shellPrintNChar(const char *str, int32_t length, int32_t width);
S
Shengliang Guan 已提交
31 32 33
static int32_t shellVerticalPrintResult(TAOS_RES *tres, const char *sql);
static int32_t shellHorizontalPrintResult(TAOS_RES *tres, const char *sql);
static int32_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql);
34 35 36 37 38 39
static void    shellReadHistory();
static void    shellWriteHistory();
static void    shellPrintError(TAOS_RES *tres, int64_t st);
static bool    shellIsCommentLine(char *line);
static void    shellSourceFile(const char *file);
static void    shellGetGrantInfo();
40

41 42 43 44 45
static void    shellCleanup(void *arg);
static void   *shellCancelHandler(void *arg);
static void   *shellThreadLoop(void *arg);

bool shellIsEmptyCommand(const char *cmd) {
46 47 48
  for (char c = *cmd++; c != 0; c = *cmd++) {
    if (c != ' ' && c != '\t' && c != ';') {
      return false;
H
hzcheng 已提交
49 50
    }
  }
51
  return true;
H
hzcheng 已提交
52 53
}

54 55
int32_t shellRunSingleCommand(char *command) {
  if (shellIsEmptyCommand(command)) {
56
    return 0;
H
hzcheng 已提交
57 58
  }

59 60
  if (shellRegexMatch(command, "^[ \t]*(quit|q|exit)[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
    shellWriteHistory();
61
    return -1;
62 63
  }

64
  if (shellRegexMatch(command, "^[\t ]*clear[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
H
hzcheng 已提交
65
    system("clear");
66 67
    return 0;
  }
68

69
  if (shellRegexMatch(command, "^[\t ]*set[ \t]+max_binary_display_width[ \t]+(default|[1-9][0-9]*)[ \t;]*$",
70
                      REG_EXTENDED | REG_ICASE)) {
71 72
    strtok(command, " \t");
    strtok(NULL, " \t");
S
Shengliang Guan 已提交
73
    char *p = strtok(NULL, " \t");
74
    if (strncasecmp(p, "default", 7) == 0) {
75
      shell.args.displayWidth = SHELL_DEFAULT_MAX_BINARY_DISPLAY_WIDTH;
76
    } else {
77 78 79
      int32_t displayWidth = atoi(p);
      displayWidth = TRANGE(displayWidth, 1, 10 * 1024);
      shell.args.displayWidth = displayWidth;
80
    }
81 82
    return 0;
  }
83

84
  if (shellRegexMatch(command, "^[ \t]*source[\t ]+[^ ]+[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
H
hzcheng 已提交
85 86 87 88 89
    /* If source file. */
    char *c_ptr = strtok(command, " ;");
    assert(c_ptr != NULL);
    c_ptr = strtok(NULL, " ;");
    assert(c_ptr != NULL);
90
    shellSourceFile(c_ptr);
91
    return 0;
H
hzcheng 已提交
92
  }
Y
Yang Zhao 已提交
93 94 95 96 97 98 99 100 101
#ifdef WEBSOCKET
  if (shell.args.restful || shell.args.cloud) {
	shellRunSingleCommandWebsocketImp(command);
  } else {
#endif
	shellRunSingleCommandImp(command);
#ifdef WEBSOCKET
  }
#endif
102
  return 0;
H
hzcheng 已提交
103 104
}

105
void shellRecordCommandToHistory(char *command) {
106 107 108 109 110 111
  SShellHistory *pHistory = &shell.history;
  if (pHistory->hstart == pHistory->hend ||
      pHistory->hist[(pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE] == NULL ||
      strcmp(command, pHistory->hist[(pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE]) != 0) {
    if (pHistory->hist[pHistory->hend] != NULL) {
      taosMemoryFreeClear(pHistory->hist[pHistory->hend]);
112
    }
113
    pHistory->hist[pHistory->hend] = strdup(command);
114

115 116 117
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
    if (pHistory->hend == pHistory->hstart) {
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
118 119
    }
  }
120 121 122 123 124 125 126 127
}

int32_t shellRunCommand(char *command, bool recordHistory) {
  if (shellIsEmptyCommand(command)) {
    return 0;
  }

  if (recordHistory) shellRecordCommandToHistory(command);
128

wmmhello's avatar
wmmhello 已提交
129
  char quote = 0, *cmd = command;
130
  for (char c = *command++; c != 0; c = *command++) {
wmmhello's avatar
wmmhello 已提交
131
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
S
Shengliang Guan 已提交
132
      command++;
133 134
      continue;
    }
135

136 137
    if (quote == c) {
      quote = 0;
wmmhello's avatar
wmmhello 已提交
138
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
139
      quote = c;
wmmhello's avatar
wmmhello 已提交
140 141 142
    } else if (c == ';' && quote == 0) {
      c = *command;
      *command = 0;
143
      if (shellRunSingleCommand(cmd) < 0) {
144 145
        return -1;
      }
wmmhello's avatar
wmmhello 已提交
146 147
      *command = c;
      cmd = command;
148 149
    }
  }
150
  return shellRunSingleCommand(cmd);
D
dapan1121 已提交
151 152
}

153
void shellRunSingleCommandImp(char *command) {
154 155 156 157 158
  int64_t st, et;
  char   *sptr = NULL;
  char   *cptr = NULL;
  char   *fname = NULL;
  bool    printMode = false;
H
hzcheng 已提交
159 160 161 162 163 164 165

  if ((sptr = strstr(command, ">>")) != NULL) {
    cptr = strstr(command, ";");
    if (cptr != NULL) {
      *cptr = '\0';
    }

166
    fname = sptr + 2;
wafwerar's avatar
wafwerar 已提交
167
    while (*fname == ' ') fname++;
H
hzcheng 已提交
168 169 170
    *sptr = '\0';
  }

171 172 173 174 175 176 177 178 179 180
  if ((sptr = strstr(command, "\\G")) != NULL) {
    cptr = strstr(command, ";");
    if (cptr != NULL) {
      *cptr = '\0';
    }

    *sptr = '\0';
    printMode = true;  // When output to a file, the switch does not work.
  }

H
hzcheng 已提交
181 182
  st = taosGetTimestampUs();

183
  TAOS_RES *pSql = taos_query(shell.conn, command);
H
Haojun Liao 已提交
184
  if (taos_errno(pSql)) {
185
    shellPrintError(pSql, st);
H
hzcheng 已提交
186 187 188
    return;
  }

189
  if (shellRegexMatch(command, "^\\s*use\\s+[a-zA-Z0-9_]+\\s*;\\s*$", REG_EXTENDED | REG_ICASE)) {
wafwerar's avatar
wafwerar 已提交
190
    fprintf(stdout, "Database changed.\r\n\r\n");
H
hzcheng 已提交
191
    fflush(stdout);
192

S
Shengliang Guan 已提交
193 194
    taos_free_result(pSql);

H
hzcheng 已提交
195 196 197
    return;
  }

S
Shengliang Guan 已提交
198
  TAOS_FIELD *pFields = taos_fetch_fields(pSql);
H
Haojun Liao 已提交
199
  if (pFields != NULL) {  // select and show kinds of commands
200
    int32_t error_no = 0;
201

S
Shengliang Guan 已提交
202
    int32_t numOfRows = shellDumpResult(pSql, fname, &error_no, printMode, command);
203
    if (numOfRows < 0) return;
H
hzcheng 已提交
204 205 206

    et = taosGetTimestampUs();
    if (error_no == 0) {
wafwerar's avatar
wafwerar 已提交
207
      printf("Query OK, %d rows in database (%.6fs)\r\n", numOfRows, (et - st) / 1E6);
H
hzcheng 已提交
208
    } else {
wafwerar's avatar
wafwerar 已提交
209
      printf("Query interrupted (%s), %d rows affected (%.6fs)\r\n", taos_errstr(pSql), numOfRows, (et - st) / 1E6);
H
hzcheng 已提交
210
    }
S
Shengliang Guan 已提交
211
    taos_free_result(pSql);
H
hzcheng 已提交
212
  } else {
213
    int32_t num_rows_affacted = taos_affected_rows(pSql);
214
    taos_free_result(pSql);
H
hzcheng 已提交
215
    et = taosGetTimestampUs();
wafwerar's avatar
wafwerar 已提交
216
    printf("Query OK, %d of %d rows affected (%.6fs)\r\n", num_rows_affacted, num_rows_affacted, (et - st) / 1E6);
H
hzcheng 已提交
217 218
  }

wafwerar's avatar
wafwerar 已提交
219
  printf("\r\n");
H
hzcheng 已提交
220 221
}

222 223
char *shellFormatTimestamp(char *buf, int64_t val, int32_t precision) {
  if (shell.args.is_raw_time) {
224 225 226
    sprintf(buf, "%" PRId64, val);
    return buf;
  }
H
hzcheng 已提交
227

S
Shengliang Guan 已提交
228
  time_t  tt;
D
fix bug  
dapan1121 已提交
229
  int32_t ms = 0;
230 231 232 233
  if (precision == TSDB_TIME_PRECISION_NANO) {
    tt = (time_t)(val / 1000000000);
    ms = val % 1000000000;
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
234
    tt = (time_t)(val / 1000000);
D
fix bug  
dapan1121 已提交
235
    ms = val % 1000000;
236 237
  } else {
    tt = (time_t)(val / 1000);
D
fix bug  
dapan1121 已提交
238
    ms = val % 1000;
239 240
  }

S
Shengliang Guan 已提交
241
  if (tt <= 0 && ms < 0) {
D
fix bug  
dapan1121 已提交
242
    tt--;
243 244 245
    if (precision == TSDB_TIME_PRECISION_NANO) {
      ms += 1000000000;
    } else if (precision == TSDB_TIME_PRECISION_MICRO) {
D
fix bug  
dapan1121 已提交
246 247 248 249 250
      ms += 1000000;
    } else {
      ms += 1000;
    }
  }
251

252 253 254
  struct tm ptm = {0};
  taosLocalTime(&tt, &ptm);
  size_t     pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
255

256 257 258
  if (precision == TSDB_TIME_PRECISION_NANO) {
    sprintf(buf + pos, ".%09d", ms);
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
D
fix bug  
dapan1121 已提交
259
    sprintf(buf + pos, ".%06d", ms);
260
  } else {
D
fix bug  
dapan1121 已提交
261
    sprintf(buf + pos, ".%03d", ms);
262 263 264 265 266
  }

  return buf;
}

267
void shellDumpFieldToFile(TdFilePtr pFile, const char *val, TAOS_FIELD *field, int32_t length, int32_t precision) {
268
  if (val == NULL) {
269
    taosFprintfFile(pFile, "%s", TSDB_DATA_NULL_STR);
270 271 272
    return;
  }

S
Shengliang Guan 已提交
273
  int  n;
274 275 276
  char buf[TSDB_MAX_BYTES_PER_ROW];
  switch (field->type) {
    case TSDB_DATA_TYPE_BOOL:
277
      taosFprintfFile(pFile, "%d", ((((int32_t)(*((char *)val))) == 1) ? 1 : 0));
278 279
      break;
    case TSDB_DATA_TYPE_TINYINT:
280
      taosFprintfFile(pFile, "%d", *((int8_t *)val));
281
      break;
S
Shengliang Guan 已提交
282 283 284
    case TSDB_DATA_TYPE_UTINYINT:
      taosFprintfFile(pFile, "%u", *((uint8_t *)val));
      break;
285
    case TSDB_DATA_TYPE_SMALLINT:
286
      taosFprintfFile(pFile, "%d", *((int16_t *)val));
287
      break;
S
Shengliang Guan 已提交
288 289 290
    case TSDB_DATA_TYPE_USMALLINT:
      taosFprintfFile(pFile, "%u", *((uint16_t *)val));
      break;
291
    case TSDB_DATA_TYPE_INT:
292
      taosFprintfFile(pFile, "%d", *((int32_t *)val));
293
      break;
S
Shengliang Guan 已提交
294 295 296
    case TSDB_DATA_TYPE_UINT:
      taosFprintfFile(pFile, "%u", *((uint32_t *)val));
      break;
297
    case TSDB_DATA_TYPE_BIGINT:
298
      taosFprintfFile(pFile, "%" PRId64, *((int64_t *)val));
299
      break;
S
Shengliang Guan 已提交
300 301 302
    case TSDB_DATA_TYPE_UBIGINT:
      taosFprintfFile(pFile, "%" PRIu64, *((uint64_t *)val));
      break;
303
    case TSDB_DATA_TYPE_FLOAT:
304
      taosFprintfFile(pFile, "%.5f", GET_FLOAT_VAL(val));
305 306
      break;
    case TSDB_DATA_TYPE_DOUBLE:
S
Shengliang Guan 已提交
307
      n = snprintf(buf, TSDB_MAX_BYTES_PER_ROW, "%*.9f", length, GET_DOUBLE_VAL(val));
308
      if (n > TMAX(25, length)) {
S
Shengliang Guan 已提交
309 310 311 312
        taosFprintfFile(pFile, "%*.15e", length, GET_DOUBLE_VAL(val));
      } else {
        taosFprintfFile(pFile, "%s", buf);
      }
313 314 315
      break;
    case TSDB_DATA_TYPE_BINARY:
    case TSDB_DATA_TYPE_NCHAR:
wmmhello's avatar
wmmhello 已提交
316
    case TSDB_DATA_TYPE_JSON:
317 318
      memcpy(buf, val, length);
      buf[length] = 0;
319
      taosFprintfFile(pFile, "\'%s\'", buf);
320 321
      break;
    case TSDB_DATA_TYPE_TIMESTAMP:
322
      shellFormatTimestamp(buf, *(int64_t *)val, precision);
323
      taosFprintfFile(pFile, "'%s'", buf);
324 325 326 327 328 329
      break;
    default:
      break;
  }
}

330
int32_t shellDumpResultToFile(const char *fname, TAOS_RES *tres) {
331 332 333 334 335
  char fullname[PATH_MAX] = {0};
  if (taosExpandDir(fname, fullname, PATH_MAX) != 0) {
    tstrncpy(fullname, fname, PATH_MAX);
  }

336
  TAOS_ROW row = taos_fetch_row(tres);
337 338 339 340
  if (row == NULL) {
    return 0;
  }

341
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_TRUNC | TD_FILE_STREAM);
342
  if (pFile == NULL) {
wafwerar's avatar
wafwerar 已提交
343
    fprintf(stderr, "failed to open file: %s\r\n", fullname);
344 345 346
    return -1;
  }

347
  TAOS_FIELD *fields = taos_fetch_fields(tres);
348 349
  int32_t     num_fields = taos_num_fields(tres);
  int32_t     precision = taos_result_precision(tres);
350

351
  for (int32_t col = 0; col < num_fields; col++) {
352
    if (col > 0) {
353
      taosFprintfFile(pFile, ",");
354
    }
355
    taosFprintfFile(pFile, "%s", fields[col].name);
356
  }
wafwerar's avatar
wafwerar 已提交
357
  taosFprintfFile(pFile, "\r\n");
358

359
  int32_t numOfRows = 0;
360
  do {
S
Shengliang Guan 已提交
361
    int32_t *length = taos_fetch_lengths(tres);
362
    for (int32_t i = 0; i < num_fields; i++) {
363
      if (i > 0) {
X
Xiaoyu Wang 已提交
364
        taosFprintfFile(pFile, ",");
365
      }
366
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision);
H
hzcheng 已提交
367
    }
wafwerar's avatar
wafwerar 已提交
368
    taosFprintfFile(pFile, "\r\n");
369 370

    numOfRows++;
371
    row = taos_fetch_row(tres);
S
Shengliang Guan 已提交
372
  } while (row != NULL);
373

374
  taosCloseFile(&pFile);
375

376 377 378
  return numOfRows;
}

379
void shellPrintNChar(const char *str, int32_t length, int32_t width) {
wafwerar's avatar
wafwerar 已提交
380
  TdWchar tail[3];
381
  int32_t pos = 0, cols = 0, totalCols = 0, tailLen = 0;
382

383
  while (pos < length) {
wafwerar's avatar
wafwerar 已提交
384
    TdWchar wc;
385
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
wmmhello's avatar
wmmhello 已提交
386
    if (bytes <= 0) {
387 388
      break;
    }
wmmhello's avatar
wmmhello 已提交
389 390

    if (pos + bytes > length) {
391 392
      break;
    }
wmmhello's avatar
wmmhello 已提交
393
    int w = 0;
X
Xiaoyu Wang 已提交
394
    if (*(str + pos) == '\t' || *(str + pos) == '\n' || *(str + pos) == '\r') {
wmmhello's avatar
wmmhello 已提交
395
      w = bytes;
X
Xiaoyu Wang 已提交
396
    } else {
wmmhello's avatar
wmmhello 已提交
397 398 399 400
      w = taosWcharWidth(wc);
    }
    pos += bytes;

401 402 403 404 405 406 407 408 409 410 411 412 413 414
    if (w <= 0) {
      continue;
    }

    if (width <= 0) {
      printf("%lc", wc);
      continue;
    }

    totalCols += w;
    if (totalCols > width) {
      break;
    }
    if (totalCols <= (width - 3)) {
415 416
      printf("%lc", wc);
      cols += w;
417 418 419
    } else {
      tail[tailLen] = wc;
      tailLen++;
420 421 422
    }
  }

423 424
  if (totalCols > width) {
    // width could be 1 or 2, so printf("...") cannot be used
425
    for (int32_t i = 0; i < 3; i++) {
426 427 428 429 430 431 432
      if (cols >= width) {
        break;
      }
      putchar('.');
      ++cols;
    }
  } else {
433
    for (int32_t i = 0; i < tailLen; i++) {
434 435 436 437 438
      printf("%lc", tail[i]);
    }
    cols = totalCols;
  }

439 440 441 442 443
  for (; cols < width; cols++) {
    putchar(' ');
  }
}

444
void shellPrintField(const char *val, TAOS_FIELD *field, int32_t width, int32_t length, int32_t precision) {
445
  if (val == NULL) {
446
    int32_t w = width;
447 448
    if (field->type < TSDB_DATA_TYPE_TINYINT || field->type > TSDB_DATA_TYPE_DOUBLE) {
      w = 0;
H
hzcheng 已提交
449
    }
450 451 452 453 454 455
    w = printf("%*s", w, TSDB_DATA_NULL_STR);
    for (; w < width; w++) {
      putchar(' ');
    }
    return;
  }
H
hzcheng 已提交
456

S
Shengliang Guan 已提交
457
  int  n;
458 459 460
  char buf[TSDB_MAX_BYTES_PER_ROW];
  switch (field->type) {
    case TSDB_DATA_TYPE_BOOL:
S
TD-1530  
Shengliang Guan 已提交
461
      printf("%*s", width, ((((int32_t)(*((char *)val))) == 1) ? "true" : "false"));
462 463
      break;
    case TSDB_DATA_TYPE_TINYINT:
S
TD-1530  
Shengliang Guan 已提交
464
      printf("%*d", width, *((int8_t *)val));
465
      break;
466 467 468
    case TSDB_DATA_TYPE_UTINYINT:
      printf("%*u", width, *((uint8_t *)val));
      break;
469
    case TSDB_DATA_TYPE_SMALLINT:
S
TD-1530  
Shengliang Guan 已提交
470
      printf("%*d", width, *((int16_t *)val));
471
      break;
472 473 474
    case TSDB_DATA_TYPE_USMALLINT:
      printf("%*u", width, *((uint16_t *)val));
      break;
475
    case TSDB_DATA_TYPE_INT:
S
TD-1530  
Shengliang Guan 已提交
476
      printf("%*d", width, *((int32_t *)val));
477
      break;
478 479 480
    case TSDB_DATA_TYPE_UINT:
      printf("%*u", width, *((uint32_t *)val));
      break;
481 482 483
    case TSDB_DATA_TYPE_BIGINT:
      printf("%*" PRId64, width, *((int64_t *)val));
      break;
484 485 486
    case TSDB_DATA_TYPE_UBIGINT:
      printf("%*" PRIu64, width, *((uint64_t *)val));
      break;
487 488 489 490
    case TSDB_DATA_TYPE_FLOAT:
      printf("%*.5f", width, GET_FLOAT_VAL(val));
      break;
    case TSDB_DATA_TYPE_DOUBLE:
S
Shengliang Guan 已提交
491
      n = snprintf(buf, TSDB_MAX_BYTES_PER_ROW, "%*.9f", width, GET_DOUBLE_VAL(val));
492
      if (n > TMAX(25, width)) {
S
Shengliang Guan 已提交
493 494 495 496
        printf("%*.15e", width, GET_DOUBLE_VAL(val));
      } else {
        printf("%s", buf);
      }
497 498 499
      break;
    case TSDB_DATA_TYPE_BINARY:
    case TSDB_DATA_TYPE_NCHAR:
wmmhello's avatar
wmmhello 已提交
500
    case TSDB_DATA_TYPE_JSON:
B
Bomin Zhang 已提交
501
      shellPrintNChar(val, length, width);
502 503
      break;
    case TSDB_DATA_TYPE_TIMESTAMP:
504
      shellFormatTimestamp(buf, *(int64_t *)val, precision);
505 506 507 508
      printf("%s", buf);
      break;
    default:
      break;
H
hzcheng 已提交
509
  }
510
}
H
hzcheng 已提交
511

S
Shengliang Guan 已提交
512
bool shellIsLimitQuery(const char *sql) {
X
Xiaoyu Wang 已提交
513
  // todo refactor
wafwerar's avatar
wafwerar 已提交
514
  if (taosStrCaseStr(sql, " limit ") != NULL) {
S
Shengliang Guan 已提交
515 516 517 518 519 520
    return true;
  }

  return false;
}

D
dapan1121 已提交
521
bool shellIsShowQuery(const char *sql) {
X
Xiaoyu Wang 已提交
522
  // todo refactor
D
dapan1121 已提交
523 524 525 526 527 528 529
  if (taosStrCaseStr(sql, "show ") != NULL) {
    return true;
  }

  return false;
}

S
Shengliang Guan 已提交
530
int32_t shellVerticalPrintResult(TAOS_RES *tres, const char *sql) {
H
Haojun Liao 已提交
531
  TAOS_ROW row = taos_fetch_row(tres);
532 533 534 535
  if (row == NULL) {
    return 0;
  }

536
  int32_t     num_fields = taos_num_fields(tres);
H
Haojun Liao 已提交
537
  TAOS_FIELD *fields = taos_fetch_fields(tres);
538
  int32_t     precision = taos_result_precision(tres);
539

540 541 542
  int32_t maxColNameLen = 0;
  for (int32_t col = 0; col < num_fields; col++) {
    int32_t len = (int32_t)strlen(fields[col].name);
543 544 545 546 547
    if (len > maxColNameLen) {
      maxColNameLen = len;
    }
  }

D
fix bug  
dapan1121 已提交
548 549
  uint64_t resShowMaxNum = UINT64_MAX;

S
Shengliang Guan 已提交
550
  if (shell.args.commands == NULL && shell.args.file[0] == 0 && !shellIsLimitQuery(sql)) {
551
    resShowMaxNum = SHELL_DEFAULT_RES_SHOW_NUM;
D
fix bug  
dapan1121 已提交
552 553
  }

554 555
  int32_t numOfRows = 0;
  int32_t showMore = 1;
556
  do {
D
fix bug  
dapan1121 已提交
557
    if (numOfRows < resShowMaxNum) {
wafwerar's avatar
wafwerar 已提交
558
      printf("*************************** %d.row ***************************\r\n", numOfRows + 1);
D
fix bug  
dapan1121 已提交
559

S
Shengliang Guan 已提交
560
      int32_t *length = taos_fetch_lengths(tres);
D
fix bug  
dapan1121 已提交
561

562
      for (int32_t i = 0; i < num_fields; i++) {
S
Shengliang Guan 已提交
563
        TAOS_FIELD *field = fields + i;
564

565
        int32_t padding = (int32_t)(maxColNameLen - strlen(field->name));
D
fix bug  
dapan1121 已提交
566
        printf("%*.s%s: ", padding, " ", field->name);
567

568
        shellPrintField((const char *)row[i], field, 0, length[i], precision);
wafwerar's avatar
wafwerar 已提交
569
        putchar('\r');
D
fix bug  
dapan1121 已提交
570 571
        putchar('\n');
      }
D
fix bug  
dapan1121 已提交
572
    } else if (showMore) {
wafwerar's avatar
wafwerar 已提交
573 574 575 576 577 578 579
      printf("\r\n");
      printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
      printf("         You can use the `LIMIT` clause to get fewer result to show.\r\n");
      printf("           Or use '>>' to redirect the whole set of the result to a specified file.\r\n");
      printf("\r\n");
      printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
      printf("\r\n");
S
Shengliang Guan 已提交
580
      showMore = 0;
581 582 583
    }

    numOfRows++;
H
Haojun Liao 已提交
584
    row = taos_fetch_row(tres);
S
Shengliang Guan 已提交
585
  } while (row != NULL);
586 587 588 589

  return numOfRows;
}

590 591
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
  int32_t width = (int32_t)strlen(field->name);
592 593

  switch (field->type) {
D
dapan1121 已提交
594 595
    case TSDB_DATA_TYPE_NULL:
      return TMAX(4, width);  // null
596
    case TSDB_DATA_TYPE_BOOL:
dengyihao's avatar
dengyihao 已提交
597
      return TMAX(5, width);  // 'false'
598 599

    case TSDB_DATA_TYPE_TINYINT:
600
    case TSDB_DATA_TYPE_UTINYINT:
dengyihao's avatar
dengyihao 已提交
601
      return TMAX(4, width);  // '-127'
602 603

    case TSDB_DATA_TYPE_SMALLINT:
604
    case TSDB_DATA_TYPE_USMALLINT:
dengyihao's avatar
dengyihao 已提交
605
      return TMAX(6, width);  // '-32767'
606 607

    case TSDB_DATA_TYPE_INT:
608
    case TSDB_DATA_TYPE_UINT:
dengyihao's avatar
dengyihao 已提交
609
      return TMAX(11, width);  // '-2147483648'
610 611

    case TSDB_DATA_TYPE_BIGINT:
612
    case TSDB_DATA_TYPE_UBIGINT:
dengyihao's avatar
dengyihao 已提交
613
      return TMAX(21, width);  // '-9223372036854775807'
614 615

    case TSDB_DATA_TYPE_FLOAT:
dengyihao's avatar
dengyihao 已提交
616
      return TMAX(20, width);
617 618

    case TSDB_DATA_TYPE_DOUBLE:
dengyihao's avatar
dengyihao 已提交
619
      return TMAX(25, width);
620 621

    case TSDB_DATA_TYPE_BINARY:
622 623
      if (field->bytes > shell.args.displayWidth) {
        return TMAX(shell.args.displayWidth, width);
624
      } else {
dengyihao's avatar
dengyihao 已提交
625
        return TMAX(field->bytes, width);
626 627
      }

wmmhello's avatar
wmmhello 已提交
628 629
    case TSDB_DATA_TYPE_NCHAR:
    case TSDB_DATA_TYPE_JSON: {
630
      int16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
631 632
      if (bytes > shell.args.displayWidth) {
        return TMAX(shell.args.displayWidth, width);
633
      } else {
dengyihao's avatar
dengyihao 已提交
634
        return TMAX(bytes, width);
635 636 637
      }
    }

638
    case TSDB_DATA_TYPE_TIMESTAMP:
639
      if (shell.args.is_raw_time) {
dengyihao's avatar
dengyihao 已提交
640
        return TMAX(14, width);
S
Shengliang Guan 已提交
641 642
      }
      if (precision == TSDB_TIME_PRECISION_NANO) {
dengyihao's avatar
dengyihao 已提交
643
        return TMAX(29, width);
644
      } else if (precision == TSDB_TIME_PRECISION_MICRO) {
dengyihao's avatar
dengyihao 已提交
645
        return TMAX(26, width);  // '2020-01-01 00:00:00.000000'
646
      } else {
dengyihao's avatar
dengyihao 已提交
647
        return TMAX(23, width);  // '2020-01-01 00:00:00.000'
S
slguan 已提交
648
      }
H
hzcheng 已提交
649

650 651
    default:
      assert(false);
H
hzcheng 已提交
652 653
  }

654 655
  return 0;
}
H
hzcheng 已提交
656

657 658 659
void shellPrintHeader(TAOS_FIELD *fields, int32_t *width, int32_t num_fields) {
  int32_t rowWidth = 0;
  for (int32_t col = 0; col < num_fields; col++) {
S
Shengliang Guan 已提交
660
    TAOS_FIELD *field = fields + col;
661 662
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
    int32_t     left = padding / 2;
663 664 665 666
    printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
    rowWidth += width[col] + 3;
  }

wafwerar's avatar
wafwerar 已提交
667
  putchar('\r');
668
  putchar('\n');
669
  for (int32_t i = 0; i < rowWidth; i++) {
670 671
    putchar('=');
  }
wafwerar's avatar
wafwerar 已提交
672
  putchar('\r');
673 674 675
  putchar('\n');
}

S
Shengliang Guan 已提交
676
int32_t shellHorizontalPrintResult(TAOS_RES *tres, const char *sql) {
H
Haojun Liao 已提交
677
  TAOS_ROW row = taos_fetch_row(tres);
678 679 680 681
  if (row == NULL) {
    return 0;
  }

682
  int32_t     num_fields = taos_num_fields(tres);
H
Haojun Liao 已提交
683
  TAOS_FIELD *fields = taos_fetch_fields(tres);
684
  int32_t     precision = taos_result_precision(tres);
685

686 687 688
  int32_t width[TSDB_MAX_COLUMNS];
  for (int32_t col = 0; col < num_fields; col++) {
    width[col] = shellCalcColWidth(fields + col, precision);
689 690
  }

691
  shellPrintHeader(fields, width, num_fields);
692

D
fix bug  
dapan1121 已提交
693 694
  uint64_t resShowMaxNum = UINT64_MAX;

wafwerar's avatar
wafwerar 已提交
695
  if (shell.args.commands == NULL && shell.args.file[0] == 0 && !shellIsLimitQuery(sql)) {
696
    resShowMaxNum = SHELL_DEFAULT_RES_SHOW_NUM;
D
fix bug  
dapan1121 已提交
697 698
  }

699 700
  int32_t numOfRows = 0;
  int32_t showMore = 1;
701

702
  do {
S
Shengliang Guan 已提交
703
    int32_t *length = taos_fetch_lengths(tres);
D
fix bug  
dapan1121 已提交
704
    if (numOfRows < resShowMaxNum) {
705
      for (int32_t i = 0; i < num_fields; i++) {
D
fix bug  
dapan1121 已提交
706
        putchar(' ');
707
        shellPrintField((const char *)row[i], fields + i, width[i], length[i], precision);
D
fix bug  
dapan1121 已提交
708 709 710
        putchar(' ');
        putchar('|');
      }
wafwerar's avatar
wafwerar 已提交
711
      putchar('\r');
D
fix bug  
dapan1121 已提交
712
      putchar('\n');
D
fix bug  
dapan1121 已提交
713
    } else if (showMore) {
wafwerar's avatar
wafwerar 已提交
714 715
      printf("\r\n");
      printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
wafwerar's avatar
wafwerar 已提交
716 717 718 719 720 721
      if (shellIsShowQuery(sql)) {
        printf("         You can use '>>' to redirect the whole set of the result to a specified file.\r\n");
      } else {
        printf("         You can use the `LIMIT` clause to get fewer result to show.\r\n");
        printf("           Or use '>>' to redirect the whole set of the result to a specified file.\r\n");
      }
wafwerar's avatar
wafwerar 已提交
722 723 724
      printf("\r\n");
      printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
      printf("\r\n");
S
Shengliang Guan 已提交
725
      showMore = 0;
726
    }
727

728
    numOfRows++;
H
Haojun Liao 已提交
729
    row = taos_fetch_row(tres);
S
Shengliang Guan 已提交
730
  } while (row != NULL);
731 732 733 734

  return numOfRows;
}

S
Shengliang Guan 已提交
735
int32_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
736
  int32_t numOfRows = 0;
H
hzcheng 已提交
737
  if (fname != NULL) {
738
    numOfRows = shellDumpResultToFile(fname, tres);
S
Shengliang Guan 已提交
739
  } else if (vertical) {
S
Shengliang Guan 已提交
740
    numOfRows = shellVerticalPrintResult(tres, sql);
741
  } else {
S
Shengliang Guan 已提交
742
    numOfRows = shellHorizontalPrintResult(tres, sql);
H
hzcheng 已提交
743 744
  }

H
Haojun Liao 已提交
745
  *error_no = taos_errno(tres);
H
hzcheng 已提交
746 747 748
  return numOfRows;
}

749
void shellReadHistory() {
750 751 752
  SShellHistory *pHistory = &shell.history;
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_READ | TD_FILE_STREAM);
  if (pFile == NULL) return;
H
hzcheng 已提交
753

754 755
  char   *line = NULL;
  int32_t read_size = 0;
756
  while ((read_size = taosGetLineFile(pFile, &line)) != -1) {
H
hzcheng 已提交
757
    line[read_size - 1] = '\0';
758
    taosMemoryFree(pHistory->hist[pHistory->hend]);
759
    pHistory->hist[pHistory->hend] = strdup(line);
H
hzcheng 已提交
760

761
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
H
hzcheng 已提交
762

763 764
    if (pHistory->hend == pHistory->hstart) {
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
H
hzcheng 已提交
765 766 767
    }
  }

S
Shengliang Guan 已提交
768
  if (line != NULL) taosMemoryFree(line);
769
  taosCloseFile(&pFile);
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
  int64_t file_size;
  if (taosStatFile(pHistory->file, &file_size, NULL) == 0 && file_size > SHELL_MAX_COMMAND_SIZE) {
    TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_TRUNC);
    if (pFile == NULL) return;
    int32_t endIndex = pHistory->hstart;
    if (endIndex != 0) {
      endIndex = pHistory->hend;
    }
    for (int32_t i = (pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE; i != endIndex;) {
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
      i = (i + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE;
    }
    taosFprintfFile(pFile, "%s\n", pHistory->hist[endIndex]);
    taosFsyncFile(pFile);
    taosCloseFile(&pFile);
  }
wafwerar's avatar
wafwerar 已提交
786
  pHistory->hstart = pHistory->hend;
H
hzcheng 已提交
787 788
}

789
void shellWriteHistory() {
790
  SShellHistory *pHistory = &shell.history;
791
  if (pHistory->hend == pHistory->hstart) return;
S
Shengliang Guan 已提交
792
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_APPEND);
793
  if (pFile == NULL) return;
H
hzcheng 已提交
794

795 796 797
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
    if (pHistory->hist[i] != NULL) {
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
798 799
      taosMemoryFree(pHistory->hist[i]);
      pHistory->hist[i] = NULL;
H
hzcheng 已提交
800
    }
801
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
H
hzcheng 已提交
802
  }
803
  taosFsyncFile(pFile);
804
  taosCloseFile(&pFile);
H
hzcheng 已提交
805 806
}

807 808 809 810 811 812 813 814 815 816
void shellCleanupHistory() {
  SShellHistory *pHistory = &shell.history;
  for (int32_t i = 0; i < SHELL_MAX_HISTORY_SIZE; ++i) {
    if (pHistory->hist[i] != NULL) {
      taosMemoryFree(pHistory->hist[i]);
      pHistory->hist[i] = NULL;
    }
  }
}

817
void shellPrintError(TAOS_RES *tres, int64_t st) {
S
TD-1793  
Shengliang Guan 已提交
818
  int64_t et = taosGetTimestampUs();
wafwerar's avatar
wafwerar 已提交
819
  fprintf(stderr, "\r\nDB error: %s (%.6fs)\r\n", taos_errstr(tres), (et - st) / 1E6);
H
Haojun Liao 已提交
820
  taos_free_result(tres);
H
hzcheng 已提交
821 822
}

823 824
bool shellIsCommentLine(char *line) {
  if (line == NULL) return true;
825
  return shellRegexMatch(line, "^\\s*#.*", REG_EXTENDED);
H
hzcheng 已提交
826 827
}

828 829 830 831 832
void shellSourceFile(const char *file) {
  int32_t read_len = 0;
  char   *cmd = taosMemoryCalloc(1, TSDB_MAX_ALLOWED_SQL_LEN + 1);
  size_t  cmd_len = 0;
  char   *line = NULL;
833
  char    fullname[PATH_MAX] = {0};
834
  char    sourceFileCommand[PATH_MAX + 8] = {0};
H
hzcheng 已提交
835

836 837
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
    tstrncpy(fullname, file, PATH_MAX);
H
hzcheng 已提交
838 839
  }

840 841 842
  sprintf(sourceFileCommand, "source %s;",fullname);
  shellRecordCommandToHistory(sourceFileCommand);

843
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_READ | TD_FILE_STREAM);
844
  if (pFile == NULL) {
wafwerar's avatar
wafwerar 已提交
845
    fprintf(stderr, "failed to open file %s\r\n", fullname);
wafwerar's avatar
wafwerar 已提交
846
    taosMemoryFree(cmd);
H
hzcheng 已提交
847 848 849
    return;
  }

850
  while ((read_len = taosGetLineFile(pFile, &line)) != -1) {
H
Haojun Liao 已提交
851
    if (read_len >= TSDB_MAX_ALLOWED_SQL_LEN) continue;
H
hzcheng 已提交
852 853
    line[--read_len] = '\0';

854
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
H
hzcheng 已提交
855 856 857 858 859 860 861 862 863 864
      continue;
    }

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

865 866 867 868
    if (line[read_len - 1] == '\r') {
      line[read_len - 1] = ' ';
    }

H
hzcheng 已提交
869
    memcpy(cmd + cmd_len, line, read_len);
wafwerar's avatar
wafwerar 已提交
870
    printf("%s%s\r\n", shell.info.promptHeader, cmd);
871
    shellRunCommand(cmd, false);
H
Haojun Liao 已提交
872
    memset(cmd, 0, TSDB_MAX_ALLOWED_SQL_LEN);
H
hzcheng 已提交
873 874 875
    cmd_len = 0;
  }

wafwerar's avatar
wafwerar 已提交
876
  taosMemoryFree(cmd);
S
Shengliang Guan 已提交
877
  if (line != NULL) taosMemoryFree(line);
878
  taosCloseFile(&pFile);
H
hzcheng 已提交
879
}
S
slguan 已提交
880

881
void shellGetGrantInfo() {
882 883
  char sinfo[1024] = {0};
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
wafwerar's avatar
wafwerar 已提交
884
  strtok(sinfo, "\r\n");
885

S
slguan 已提交
886 887
  char sql[] = "show grants";

888
  TAOS_RES *tres = taos_query(shell.conn, sql);
H
Haojun Liao 已提交
889

890
  int32_t code = taos_errno(tres);
S
slguan 已提交
891
  if (code != TSDB_CODE_SUCCESS) {
892
    if (code != TSDB_CODE_OPS_NOT_SUPPORT && code != TSDB_CODE_MND_NO_RIGHTS) {
wafwerar's avatar
wafwerar 已提交
893
      fprintf(stderr, "Failed to check Server Edition, Reason:0x%04x:%s\r\n\r\n", code, taos_errstr(tres));
S
slguan 已提交
894
    }
S
slguan 已提交
895 896 897
    return;
  }

898
  int32_t num_fields = taos_field_count(tres);
S
slguan 已提交
899
  if (num_fields == 0) {
wafwerar's avatar
wafwerar 已提交
900
    fprintf(stderr, "\r\nInvalid grant information.\r\n");
S
slguan 已提交
901 902
    exit(0);
  } else {
903
    if (tres == NULL) {
wafwerar's avatar
wafwerar 已提交
904
      fprintf(stderr, "\r\nGrant information is null.\r\n");
S
slguan 已提交
905 906 907
      exit(0);
    }

908
    TAOS_FIELD *fields = taos_fetch_fields(tres);
909
    TAOS_ROW    row = taos_fetch_row(tres);
S
slguan 已提交
910
    if (row == NULL) {
wafwerar's avatar
wafwerar 已提交
911
      fprintf(stderr, "\r\nFailed to get grant information from server. Abort.\r\n");
S
slguan 已提交
912 913 914
      exit(0);
    }

S
slguan 已提交
915
    char serverVersion[32] = {0};
S
slguan 已提交
916 917 918
    char expiretime[32] = {0};
    char expired[32] = {0};

S
slguan 已提交
919
    memcpy(serverVersion, row[0], fields[0].bytes);
S
slguan 已提交
920 921 922
    memcpy(expiretime, row[1], fields[1].bytes);
    memcpy(expired, row[2], fields[2].bytes);

923
    if (strcmp(serverVersion, "community") == 0) {
wafwerar's avatar
wafwerar 已提交
924
      fprintf(stdout, "Server is Community Edition.\r\n");
925
    } else if (strcmp(expiretime, "unlimited") == 0) {
wafwerar's avatar
wafwerar 已提交
926
      fprintf(stdout, "Server is Enterprise %s Edition, %s and will never expire.\r\n", serverVersion, sinfo);
S
slguan 已提交
927
    } else {
wafwerar's avatar
wafwerar 已提交
928
      fprintf(stdout, "Server is Enterprise %s Edition, %s and will expire at %s.\r\n", serverVersion, sinfo, expiretime);
S
slguan 已提交
929 930
    }

931
    taos_free_result(tres);
S
slguan 已提交
932 933
  }

wafwerar's avatar
wafwerar 已提交
934
  fprintf(stdout, "\r\n");
935 936
}

937 938 939 940
#ifdef WINDOWS
BOOL shellQueryInterruptHandler(DWORD fdwCtrlType) {
  tsem_post(&shell.cancelSem);
  return TRUE;
941
}
942 943 944
#else
void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) { tsem_post(&shell.cancelSem); }
#endif
945

946 947 948 949 950 951 952 953 954
void shellCleanup(void *arg) { taosResetTerminalMode(); }

void *shellCancelHandler(void *arg) {
  setThreadName("shellCancelHandler");
  while (1) {
    if (tsem_wait(&shell.cancelSem) != 0) {
      taosMsleep(10);
      continue;
    }
Y
Yang Zhao 已提交
955 956 957 958 959 960 961 962 963 964

#ifdef WEBSOCKET
	if (shell.args.restful || shell.args.cloud) {
		shell.stop_query = true;
	} else {
#endif
		taos_kill_query(shell.conn);
#ifdef WEBSOCKET
	}
#endif 
965 966 967
  #ifdef WINDOWS
    printf("\n%s", shell.info.promptHeader);
  #endif
968 969 970 971 972 973 974 975 976 977 978 979
  }

  return NULL;
}

void *shellThreadLoop(void *arg) {
  setThreadName("shellThreadLoop");
  taosGetOldTerminalMode();
  taosThreadCleanupPush(shellCleanup, NULL);

  char *command = taosMemoryMalloc(SHELL_MAX_COMMAND_SIZE);
  if (command == NULL) {
wafwerar's avatar
wafwerar 已提交
980
    printf("failed to malloc command\r\n");
981 982 983 984 985 986 987 988 989 990 991 992
    return NULL;
  }

  do {
    memset(command, 0, SHELL_MAX_COMMAND_SIZE);
    taosSetTerminalMode();

    if (shellReadCommand(command) != 0) {
      break;
    }

    taosResetTerminalMode();
993
  } while (shellRunCommand(command, true) == 0);
994 995

  taosMemoryFreeClear(command);
996 997
  shellWriteHistory();
  shellExit();
998

999 1000 1001 1002 1003
  taosThreadCleanupPop(1);
  return NULL;
}

int32_t shellExecute() {
wafwerar's avatar
wafwerar 已提交
1004
  printf(shell.info.clientVersion, taos_get_client_info());
1005 1006 1007
  fflush(stdout);

  SShellArgs *pArgs = &shell.args;
Y
Yang Zhao 已提交
1008 1009 1010 1011 1012
#ifdef WEBSOCKET
  if (shell.args.restful || shell.args.cloud) {
	if (shell_conn_ws_server(1)) {
		return -1;
	}	
1013
  } else {
Y
Yang Zhao 已提交
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
#endif
	if (shell.args.auth == NULL) {
		shell.conn = taos_connect(pArgs->host, pArgs->user, pArgs->password, pArgs->database, pArgs->port);
	} else {
		shell.conn = taos_connect_auth(pArgs->host, pArgs->user, pArgs->auth, pArgs->database, pArgs->port);
	}

	if (shell.conn == NULL) {
		fflush(stdout);
		return -1;
	}
#ifdef WEBSOCKET
1026
  }
Y
Yang Zhao 已提交
1027
#endif
1028

1029 1030
  shellReadHistory();

1031
  if (pArgs->commands != NULL || pArgs->file[0] != 0) {
1032
    if (pArgs->commands != NULL) {
wafwerar's avatar
wafwerar 已提交
1033
      printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
1034
      char *cmd = strdup(pArgs->commands);
1035
      shellRunCommand(cmd, true);
1036 1037 1038
      taosMemoryFree(cmd);
    }

1039
    if (pArgs->file[0] != 0) {
1040 1041
      shellSourceFile(pArgs->file);
    }
Y
Yang Zhao 已提交
1042 1043 1044 1045 1046 1047 1048 1049 1050
#ifdef WEBSOCKET
	if (shell.args.restful || shell.args.cloud) {
		ws_close(shell.ws_conn);
	} else {
#endif	
		taos_close(shell.conn);
#ifdef WEBSOCKET
	}
#endif
1051 1052

    shellWriteHistory();
1053
    shellCleanupHistory();
1054 1055 1056 1057
    return 0;
  }

  if (tsem_init(&shell.cancelSem, 0, 0) != 0) {
wafwerar's avatar
wafwerar 已提交
1058
    printf("failed to create cancel semphore\r\n");
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
    return -1;
  }

  TdThread spid = {0};
  taosThreadCreate(&spid, NULL, shellCancelHandler, NULL);

  taosSetSignal(SIGTERM, shellQueryInterruptHandler);
  taosSetSignal(SIGHUP, shellQueryInterruptHandler);
  taosSetSignal(SIGABRT, shellQueryInterruptHandler);

1069
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
1070

Y
Yang Zhao 已提交
1071 1072 1073 1074 1075 1076 1077
#ifdef WEBSOCKET
  if (!shell.args.restful && !shell.args.cloud) {
#endif
	shellGetGrantInfo();
#ifdef WEBSOCKET
  }
#endif
1078
  while (1) {
Y
Yang Zhao 已提交
1079
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, NULL);
1080
    taosThreadJoin(shell.pid, NULL);
1081
    taosThreadClear(&shell.pid);
1082 1083
  }

1084
  shellCleanupHistory();
1085
  return 0;
S
slguan 已提交
1086
}