shellEngine.c 30.4 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)) {
65 66 67 68
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-result"
          system("clear");
#pragma GCC diagnostic pop
69 70
    return 0;
  }
71

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

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

108
void shellRecordCommandToHistory(char *command) {
109 110 111 112 113 114
  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]);
115
    }
116
    pHistory->hist[pHistory->hend] = strdup(command);
117

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

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

  if (recordHistory) shellRecordCommandToHistory(command);
131

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

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

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

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

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

174 175 176 177 178 179 180 181 182 183
  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 已提交
184 185
  st = taosGetTimestampUs();

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

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

S
Shengliang Guan 已提交
196 197
    taos_free_result(pSql);

H
hzcheng 已提交
198 199 200
    return;
  }

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

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

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

wafwerar's avatar
wafwerar 已提交
222
  printf("\r\n");
H
hzcheng 已提交
223 224
}

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

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

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

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

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

  return buf;
}

wafwerar's avatar
wafwerar 已提交
270
void shellDumpFieldToFile(TdFilePtr pFile, const char *val, TAOS_FIELD *field, int32_t length, int32_t precision) {
271 272 273 274
  if (val == NULL) {
    return;
  }

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

353
int32_t shellDumpResultToFile(const char *fname, TAOS_RES *tres) {
354 355 356 357 358
  char fullname[PATH_MAX] = {0};
  if (taosExpandDir(fname, fullname, PATH_MAX) != 0) {
    tstrncpy(fullname, fname, PATH_MAX);
  }

359
  TAOS_ROW row = taos_fetch_row(tres);
360 361 362 363
  if (row == NULL) {
    return 0;
  }

364
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_TRUNC | TD_FILE_STREAM);
365
  if (pFile == NULL) {
wafwerar's avatar
wafwerar 已提交
366
    fprintf(stderr, "failed to open file: %s\r\n", fullname);
367 368 369
    return -1;
  }

370
  TAOS_FIELD *fields = taos_fetch_fields(tres);
371 372
  int32_t     num_fields = taos_num_fields(tres);
  int32_t     precision = taos_result_precision(tres);
373

374
  for (int32_t col = 0; col < num_fields; col++) {
375
    if (col > 0) {
376
      taosFprintfFile(pFile, ",");
377
    }
378
    taosFprintfFile(pFile, "%s", fields[col].name);
379
  }
wafwerar's avatar
wafwerar 已提交
380
  taosFprintfFile(pFile, "\r\n");
381

382
  int32_t numOfRows = 0;
383
  do {
S
Shengliang Guan 已提交
384
    int32_t *length = taos_fetch_lengths(tres);
385
    for (int32_t i = 0; i < num_fields; i++) {
386
      if (i > 0) {
X
Xiaoyu Wang 已提交
387
        taosFprintfFile(pFile, ",");
388
      }
wafwerar's avatar
wafwerar 已提交
389
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision);
H
hzcheng 已提交
390
    }
wafwerar's avatar
wafwerar 已提交
391
    taosFprintfFile(pFile, "\r\n");
392 393

    numOfRows++;
394
    row = taos_fetch_row(tres);
S
Shengliang Guan 已提交
395
  } while (row != NULL);
396

397
  taosCloseFile(&pFile);
398

399 400 401
  return numOfRows;
}

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

406
  while (pos < length) {
wafwerar's avatar
wafwerar 已提交
407
    TdWchar wc;
408
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
wmmhello's avatar
wmmhello 已提交
409
    if (bytes <= 0) {
410 411
      break;
    }
wmmhello's avatar
wmmhello 已提交
412 413

    if (pos + bytes > length) {
414 415
      break;
    }
wmmhello's avatar
wmmhello 已提交
416
    int w = 0;
X
Xiaoyu Wang 已提交
417
    if (*(str + pos) == '\t' || *(str + pos) == '\n' || *(str + pos) == '\r') {
wmmhello's avatar
wmmhello 已提交
418
      w = bytes;
X
Xiaoyu Wang 已提交
419
    } else {
wmmhello's avatar
wmmhello 已提交
420 421 422 423
      w = taosWcharWidth(wc);
    }
    pos += bytes;

424 425 426 427 428 429 430 431 432 433 434 435 436 437
    if (w <= 0) {
      continue;
    }

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

    totalCols += w;
    if (totalCols > width) {
      break;
    }
    if (totalCols <= (width - 3)) {
438 439
      printf("%lc", wc);
      cols += w;
440 441 442
    } else {
      tail[tailLen] = wc;
      tailLen++;
443 444 445
    }
  }

446 447
  if (totalCols > width) {
    // width could be 1 or 2, so printf("...") cannot be used
448
    for (int32_t i = 0; i < 3; i++) {
449 450 451 452 453 454 455
      if (cols >= width) {
        break;
      }
      putchar('.');
      ++cols;
    }
  } else {
456
    for (int32_t i = 0; i < tailLen; i++) {
457 458 459 460 461
      printf("%lc", tail[i]);
    }
    cols = totalCols;
  }

462 463 464 465 466
  for (; cols < width; cols++) {
    putchar(' ');
  }
}

467
void shellPrintField(const char *val, TAOS_FIELD *field, int32_t width, int32_t length, int32_t precision) {
468
  if (val == NULL) {
469
    int32_t w = width;
470 471
    if (field->type < TSDB_DATA_TYPE_TINYINT || field->type > TSDB_DATA_TYPE_DOUBLE) {
      w = 0;
H
hzcheng 已提交
472
    }
473 474 475 476 477 478
    w = printf("%*s", w, TSDB_DATA_NULL_STR);
    for (; w < width; w++) {
      putchar(' ');
    }
    return;
  }
H
hzcheng 已提交
479

S
Shengliang Guan 已提交
480
  int  n;
481 482 483
  char buf[TSDB_MAX_BYTES_PER_ROW];
  switch (field->type) {
    case TSDB_DATA_TYPE_BOOL:
S
TD-1530  
Shengliang Guan 已提交
484
      printf("%*s", width, ((((int32_t)(*((char *)val))) == 1) ? "true" : "false"));
485 486
      break;
    case TSDB_DATA_TYPE_TINYINT:
S
TD-1530  
Shengliang Guan 已提交
487
      printf("%*d", width, *((int8_t *)val));
488
      break;
489 490 491
    case TSDB_DATA_TYPE_UTINYINT:
      printf("%*u", width, *((uint8_t *)val));
      break;
492
    case TSDB_DATA_TYPE_SMALLINT:
S
TD-1530  
Shengliang Guan 已提交
493
      printf("%*d", width, *((int16_t *)val));
494
      break;
495 496 497
    case TSDB_DATA_TYPE_USMALLINT:
      printf("%*u", width, *((uint16_t *)val));
      break;
498
    case TSDB_DATA_TYPE_INT:
S
TD-1530  
Shengliang Guan 已提交
499
      printf("%*d", width, *((int32_t *)val));
500
      break;
501 502 503
    case TSDB_DATA_TYPE_UINT:
      printf("%*u", width, *((uint32_t *)val));
      break;
504 505 506
    case TSDB_DATA_TYPE_BIGINT:
      printf("%*" PRId64, width, *((int64_t *)val));
      break;
507 508 509
    case TSDB_DATA_TYPE_UBIGINT:
      printf("%*" PRIu64, width, *((uint64_t *)val));
      break;
510 511 512 513
    case TSDB_DATA_TYPE_FLOAT:
      printf("%*.5f", width, GET_FLOAT_VAL(val));
      break;
    case TSDB_DATA_TYPE_DOUBLE:
S
Shengliang Guan 已提交
514
      n = snprintf(buf, TSDB_MAX_BYTES_PER_ROW, "%*.9f", width, GET_DOUBLE_VAL(val));
515
      if (n > TMAX(25, width)) {
S
Shengliang Guan 已提交
516 517 518 519
        printf("%*.15e", width, GET_DOUBLE_VAL(val));
      } else {
        printf("%s", buf);
      }
520 521 522
      break;
    case TSDB_DATA_TYPE_BINARY:
    case TSDB_DATA_TYPE_NCHAR:
wmmhello's avatar
wmmhello 已提交
523
    case TSDB_DATA_TYPE_JSON:
B
Bomin Zhang 已提交
524
      shellPrintNChar(val, length, width);
525 526
      break;
    case TSDB_DATA_TYPE_TIMESTAMP:
527
      shellFormatTimestamp(buf, *(int64_t *)val, precision);
528 529 530 531
      printf("%s", buf);
      break;
    default:
      break;
H
hzcheng 已提交
532
  }
533
}
H
hzcheng 已提交
534

S
Shengliang Guan 已提交
535
bool shellIsLimitQuery(const char *sql) {
X
Xiaoyu Wang 已提交
536
  // todo refactor
wafwerar's avatar
wafwerar 已提交
537
  if (taosStrCaseStr(sql, " limit ") != NULL) {
S
Shengliang Guan 已提交
538 539 540 541 542 543
    return true;
  }

  return false;
}

D
dapan1121 已提交
544
bool shellIsShowQuery(const char *sql) {
X
Xiaoyu Wang 已提交
545
  // todo refactor
D
dapan1121 已提交
546 547 548 549 550 551 552
  if (taosStrCaseStr(sql, "show ") != NULL) {
    return true;
  }

  return false;
}

S
Shengliang Guan 已提交
553
int32_t shellVerticalPrintResult(TAOS_RES *tres, const char *sql) {
H
Haojun Liao 已提交
554
  TAOS_ROW row = taos_fetch_row(tres);
555 556 557 558
  if (row == NULL) {
    return 0;
  }

559
  int32_t     num_fields = taos_num_fields(tres);
H
Haojun Liao 已提交
560
  TAOS_FIELD *fields = taos_fetch_fields(tres);
561
  int32_t     precision = taos_result_precision(tres);
562

563 564 565
  int32_t maxColNameLen = 0;
  for (int32_t col = 0; col < num_fields; col++) {
    int32_t len = (int32_t)strlen(fields[col].name);
566 567 568 569 570
    if (len > maxColNameLen) {
      maxColNameLen = len;
    }
  }

D
fix bug  
dapan1121 已提交
571 572
  uint64_t resShowMaxNum = UINT64_MAX;

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

577 578
  int32_t numOfRows = 0;
  int32_t showMore = 1;
579
  do {
D
fix bug  
dapan1121 已提交
580
    if (numOfRows < resShowMaxNum) {
wafwerar's avatar
wafwerar 已提交
581
      printf("*************************** %d.row ***************************\r\n", numOfRows + 1);
D
fix bug  
dapan1121 已提交
582

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

585
      for (int32_t i = 0; i < num_fields; i++) {
S
Shengliang Guan 已提交
586
        TAOS_FIELD *field = fields + i;
587

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

591
        shellPrintField((const char *)row[i], field, 0, length[i], precision);
wafwerar's avatar
wafwerar 已提交
592
        putchar('\r');
D
fix bug  
dapan1121 已提交
593 594
        putchar('\n');
      }
D
fix bug  
dapan1121 已提交
595
    } else if (showMore) {
wafwerar's avatar
wafwerar 已提交
596 597 598 599 600 601 602
      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 已提交
603
      showMore = 0;
604 605 606
    }

    numOfRows++;
H
Haojun Liao 已提交
607
    row = taos_fetch_row(tres);
S
Shengliang Guan 已提交
608
  } while (row != NULL);
609 610 611 612

  return numOfRows;
}

613 614
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
  int32_t width = (int32_t)strlen(field->name);
615 616

  switch (field->type) {
D
dapan1121 已提交
617 618
    case TSDB_DATA_TYPE_NULL:
      return TMAX(4, width);  // null
619
    case TSDB_DATA_TYPE_BOOL:
dengyihao's avatar
dengyihao 已提交
620
      return TMAX(5, width);  // 'false'
621 622

    case TSDB_DATA_TYPE_TINYINT:
623
    case TSDB_DATA_TYPE_UTINYINT:
dengyihao's avatar
dengyihao 已提交
624
      return TMAX(4, width);  // '-127'
625 626

    case TSDB_DATA_TYPE_SMALLINT:
627
    case TSDB_DATA_TYPE_USMALLINT:
dengyihao's avatar
dengyihao 已提交
628
      return TMAX(6, width);  // '-32767'
629 630

    case TSDB_DATA_TYPE_INT:
631
    case TSDB_DATA_TYPE_UINT:
dengyihao's avatar
dengyihao 已提交
632
      return TMAX(11, width);  // '-2147483648'
633 634

    case TSDB_DATA_TYPE_BIGINT:
635
    case TSDB_DATA_TYPE_UBIGINT:
dengyihao's avatar
dengyihao 已提交
636
      return TMAX(21, width);  // '-9223372036854775807'
637 638

    case TSDB_DATA_TYPE_FLOAT:
dengyihao's avatar
dengyihao 已提交
639
      return TMAX(20, width);
640 641

    case TSDB_DATA_TYPE_DOUBLE:
dengyihao's avatar
dengyihao 已提交
642
      return TMAX(25, width);
643 644

    case TSDB_DATA_TYPE_BINARY:
645 646
      if (field->bytes > shell.args.displayWidth) {
        return TMAX(shell.args.displayWidth, width);
647
      } else {
dengyihao's avatar
dengyihao 已提交
648
        return TMAX(field->bytes, width);
649 650
      }

wmmhello's avatar
wmmhello 已提交
651 652
    case TSDB_DATA_TYPE_NCHAR:
    case TSDB_DATA_TYPE_JSON: {
653
      int16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
654 655
      if (bytes > shell.args.displayWidth) {
        return TMAX(shell.args.displayWidth, width);
656
      } else {
dengyihao's avatar
dengyihao 已提交
657
        return TMAX(bytes, width);
658 659 660
      }
    }

661
    case TSDB_DATA_TYPE_TIMESTAMP:
662
      if (shell.args.is_raw_time) {
dengyihao's avatar
dengyihao 已提交
663
        return TMAX(14, width);
S
Shengliang Guan 已提交
664 665
      }
      if (precision == TSDB_TIME_PRECISION_NANO) {
dengyihao's avatar
dengyihao 已提交
666
        return TMAX(29, width);
667
      } else if (precision == TSDB_TIME_PRECISION_MICRO) {
dengyihao's avatar
dengyihao 已提交
668
        return TMAX(26, width);  // '2020-01-01 00:00:00.000000'
669
      } else {
dengyihao's avatar
dengyihao 已提交
670
        return TMAX(23, width);  // '2020-01-01 00:00:00.000'
S
slguan 已提交
671
      }
H
hzcheng 已提交
672

673 674
    default:
      assert(false);
H
hzcheng 已提交
675 676
  }

677 678
  return 0;
}
H
hzcheng 已提交
679

680 681 682
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 已提交
683
    TAOS_FIELD *field = fields + col;
684 685
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
    int32_t     left = padding / 2;
686 687 688 689
    printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
    rowWidth += width[col] + 3;
  }

wafwerar's avatar
wafwerar 已提交
690
  putchar('\r');
691
  putchar('\n');
692
  for (int32_t i = 0; i < rowWidth; i++) {
693 694
    putchar('=');
  }
wafwerar's avatar
wafwerar 已提交
695
  putchar('\r');
696 697 698
  putchar('\n');
}

S
Shengliang Guan 已提交
699
int32_t shellHorizontalPrintResult(TAOS_RES *tres, const char *sql) {
H
Haojun Liao 已提交
700
  TAOS_ROW row = taos_fetch_row(tres);
701 702 703 704
  if (row == NULL) {
    return 0;
  }

705
  int32_t     num_fields = taos_num_fields(tres);
H
Haojun Liao 已提交
706
  TAOS_FIELD *fields = taos_fetch_fields(tres);
707
  int32_t     precision = taos_result_precision(tres);
708

709 710 711
  int32_t width[TSDB_MAX_COLUMNS];
  for (int32_t col = 0; col < num_fields; col++) {
    width[col] = shellCalcColWidth(fields + col, precision);
712 713
  }

714
  shellPrintHeader(fields, width, num_fields);
715

D
fix bug  
dapan1121 已提交
716 717
  uint64_t resShowMaxNum = UINT64_MAX;

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

722 723
  int32_t numOfRows = 0;
  int32_t showMore = 1;
724

725
  do {
S
Shengliang Guan 已提交
726
    int32_t *length = taos_fetch_lengths(tres);
D
fix bug  
dapan1121 已提交
727
    if (numOfRows < resShowMaxNum) {
728
      for (int32_t i = 0; i < num_fields; i++) {
D
fix bug  
dapan1121 已提交
729
        putchar(' ');
730
        shellPrintField((const char *)row[i], fields + i, width[i], length[i], precision);
D
fix bug  
dapan1121 已提交
731 732 733
        putchar(' ');
        putchar('|');
      }
wafwerar's avatar
wafwerar 已提交
734
      putchar('\r');
D
fix bug  
dapan1121 已提交
735
      putchar('\n');
D
fix bug  
dapan1121 已提交
736
    } else if (showMore) {
wafwerar's avatar
wafwerar 已提交
737 738
      printf("\r\n");
      printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
wafwerar's avatar
wafwerar 已提交
739 740 741 742 743 744
      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 已提交
745 746 747
      printf("\r\n");
      printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
      printf("\r\n");
S
Shengliang Guan 已提交
748
      showMore = 0;
749
    }
750

751
    numOfRows++;
H
Haojun Liao 已提交
752
    row = taos_fetch_row(tres);
S
Shengliang Guan 已提交
753
  } while (row != NULL);
754 755 756 757

  return numOfRows;
}

S
Shengliang Guan 已提交
758
int32_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
759
  int32_t numOfRows = 0;
H
hzcheng 已提交
760
  if (fname != NULL) {
761
    numOfRows = shellDumpResultToFile(fname, tres);
S
Shengliang Guan 已提交
762
  } else if (vertical) {
S
Shengliang Guan 已提交
763
    numOfRows = shellVerticalPrintResult(tres, sql);
764
  } else {
S
Shengliang Guan 已提交
765
    numOfRows = shellHorizontalPrintResult(tres, sql);
H
hzcheng 已提交
766 767
  }

H
Haojun Liao 已提交
768
  *error_no = taos_errno(tres);
H
hzcheng 已提交
769 770 771
  return numOfRows;
}

772
void shellReadHistory() {
773 774 775
  SShellHistory *pHistory = &shell.history;
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_READ | TD_FILE_STREAM);
  if (pFile == NULL) return;
H
hzcheng 已提交
776

777 778
  char   *line = NULL;
  int32_t read_size = 0;
779
  while ((read_size = taosGetLineFile(pFile, &line)) != -1) {
H
hzcheng 已提交
780
    line[read_size - 1] = '\0';
781
    taosMemoryFree(pHistory->hist[pHistory->hend]);
782
    pHistory->hist[pHistory->hend] = strdup(line);
H
hzcheng 已提交
783

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

786 787
    if (pHistory->hend == pHistory->hstart) {
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
H
hzcheng 已提交
788 789 790
    }
  }

S
Shengliang Guan 已提交
791
  if (line != NULL) taosMemoryFree(line);
792
  taosCloseFile(&pFile);
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
  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 已提交
809
  pHistory->hstart = pHistory->hend;
H
hzcheng 已提交
810 811
}

812
void shellWriteHistory() {
813
  SShellHistory *pHistory = &shell.history;
814
  if (pHistory->hend == pHistory->hstart) return;
S
Shengliang Guan 已提交
815
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_APPEND);
816
  if (pFile == NULL) return;
H
hzcheng 已提交
817

818 819 820
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
    if (pHistory->hist[i] != NULL) {
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
821 822
      taosMemoryFree(pHistory->hist[i]);
      pHistory->hist[i] = NULL;
H
hzcheng 已提交
823
    }
824
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
H
hzcheng 已提交
825
  }
826
  taosFsyncFile(pFile);
827
  taosCloseFile(&pFile);
H
hzcheng 已提交
828 829
}

830 831 832 833 834 835 836 837 838 839
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;
    }
  }
}

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

846 847
bool shellIsCommentLine(char *line) {
  if (line == NULL) return true;
848
  return shellRegexMatch(line, "^\\s*#.*", REG_EXTENDED);
H
hzcheng 已提交
849 850
}

851 852 853 854 855
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;
856
  char    fullname[PATH_MAX] = {0};
857
  char    sourceFileCommand[PATH_MAX + 8] = {0};
H
hzcheng 已提交
858

859 860
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
    tstrncpy(fullname, file, PATH_MAX);
H
hzcheng 已提交
861 862
  }

863 864 865
  sprintf(sourceFileCommand, "source %s;",fullname);
  shellRecordCommandToHistory(sourceFileCommand);

866
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_READ | TD_FILE_STREAM);
867
  if (pFile == NULL) {
wafwerar's avatar
wafwerar 已提交
868
    fprintf(stderr, "failed to open file %s\r\n", fullname);
wafwerar's avatar
wafwerar 已提交
869
    taosMemoryFree(cmd);
H
hzcheng 已提交
870 871 872
    return;
  }

873
  while ((read_len = taosGetLineFile(pFile, &line)) != -1) {
H
Haojun Liao 已提交
874
    if (read_len >= TSDB_MAX_ALLOWED_SQL_LEN) continue;
H
hzcheng 已提交
875 876
    line[--read_len] = '\0';

877
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
H
hzcheng 已提交
878 879 880 881 882 883 884 885 886 887
      continue;
    }

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

888 889 890 891
    if (line[read_len - 1] == '\r') {
      line[read_len - 1] = ' ';
    }

H
hzcheng 已提交
892
    memcpy(cmd + cmd_len, line, read_len);
wafwerar's avatar
wafwerar 已提交
893
    printf("%s%s\r\n", shell.info.promptHeader, cmd);
894
    shellRunCommand(cmd, false);
H
Haojun Liao 已提交
895
    memset(cmd, 0, TSDB_MAX_ALLOWED_SQL_LEN);
H
hzcheng 已提交
896 897 898
    cmd_len = 0;
  }

wafwerar's avatar
wafwerar 已提交
899
  taosMemoryFree(cmd);
S
Shengliang Guan 已提交
900
  if (line != NULL) taosMemoryFree(line);
901
  taosCloseFile(&pFile);
H
hzcheng 已提交
902
}
S
slguan 已提交
903

904
void shellGetGrantInfo() {
905 906
  char sinfo[1024] = {0};
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
wafwerar's avatar
wafwerar 已提交
907
  strtok(sinfo, "\r\n");
908

S
slguan 已提交
909 910
  char sql[] = "show grants";

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

913
  int32_t code = taos_errno(tres);
S
slguan 已提交
914
  if (code != TSDB_CODE_SUCCESS) {
915
    if (code != TSDB_CODE_OPS_NOT_SUPPORT && code != TSDB_CODE_MND_NO_RIGHTS) {
wafwerar's avatar
wafwerar 已提交
916
      fprintf(stderr, "Failed to check Server Edition, Reason:0x%04x:%s\r\n\r\n", code, taos_errstr(tres));
S
slguan 已提交
917
    }
S
slguan 已提交
918 919 920
    return;
  }

921
  int32_t num_fields = taos_field_count(tres);
S
slguan 已提交
922
  if (num_fields == 0) {
wafwerar's avatar
wafwerar 已提交
923
    fprintf(stderr, "\r\nInvalid grant information.\r\n");
S
slguan 已提交
924 925
    exit(0);
  } else {
926
    if (tres == NULL) {
wafwerar's avatar
wafwerar 已提交
927
      fprintf(stderr, "\r\nGrant information is null.\r\n");
S
slguan 已提交
928 929 930
      exit(0);
    }

931
    TAOS_FIELD *fields = taos_fetch_fields(tres);
932
    TAOS_ROW    row = taos_fetch_row(tres);
S
slguan 已提交
933
    if (row == NULL) {
wafwerar's avatar
wafwerar 已提交
934
      fprintf(stderr, "\r\nFailed to get grant information from server. Abort.\r\n");
S
slguan 已提交
935 936 937
      exit(0);
    }

S
slguan 已提交
938
    char serverVersion[32] = {0};
S
slguan 已提交
939 940 941
    char expiretime[32] = {0};
    char expired[32] = {0};

S
slguan 已提交
942
    memcpy(serverVersion, row[0], fields[0].bytes);
S
slguan 已提交
943 944 945
    memcpy(expiretime, row[1], fields[1].bytes);
    memcpy(expired, row[2], fields[2].bytes);

946
    if (strcmp(serverVersion, "community") == 0) {
wafwerar's avatar
wafwerar 已提交
947
      fprintf(stdout, "Server is Community Edition.\r\n");
948
    } else if (strcmp(expiretime, "unlimited") == 0) {
wafwerar's avatar
wafwerar 已提交
949
      fprintf(stdout, "Server is Enterprise %s Edition, %s and will never expire.\r\n", serverVersion, sinfo);
S
slguan 已提交
950
    } else {
wafwerar's avatar
wafwerar 已提交
951
      fprintf(stdout, "Server is Enterprise %s Edition, %s and will expire at %s.\r\n", serverVersion, sinfo, expiretime);
S
slguan 已提交
952 953
    }

954
    taos_free_result(tres);
S
slguan 已提交
955 956
  }

wafwerar's avatar
wafwerar 已提交
957
  fprintf(stdout, "\r\n");
958 959
}

960 961 962 963
#ifdef WINDOWS
BOOL shellQueryInterruptHandler(DWORD fdwCtrlType) {
  tsem_post(&shell.cancelSem);
  return TRUE;
964
}
965 966 967
#else
void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) { tsem_post(&shell.cancelSem); }
#endif
968

969 970 971 972 973
void shellCleanup(void *arg) { taosResetTerminalMode(); }

void *shellCancelHandler(void *arg) {
  setThreadName("shellCancelHandler");
  while (1) {
974 975 976 977
    if (shell.exit == true) {
      break;
    }

978 979 980 981
    if (tsem_wait(&shell.cancelSem) != 0) {
      taosMsleep(10);
      continue;
    }
Y
Yang Zhao 已提交
982 983 984 985 986 987 988 989 990

#ifdef WEBSOCKET
	if (shell.args.restful || shell.args.cloud) {
		shell.stop_query = true;
	} else {
#endif
		taos_kill_query(shell.conn);
#ifdef WEBSOCKET
	}
991
#endif
992 993 994
  #ifdef WINDOWS
    printf("\n%s", shell.info.promptHeader);
  #endif
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006
  }

  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 已提交
1007
    printf("failed to malloc command\r\n");
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    return NULL;
  }

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

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

    taosResetTerminalMode();
1020
  } while (shellRunCommand(command, true) == 0);
1021 1022

  taosMemoryFreeClear(command);
1023 1024
  shellWriteHistory();
  shellExit();
1025

1026 1027 1028 1029 1030
  taosThreadCleanupPop(1);
  return NULL;
}

int32_t shellExecute() {
wafwerar's avatar
wafwerar 已提交
1031
  printf(shell.info.clientVersion, taos_get_client_info());
1032 1033 1034
  fflush(stdout);

  SShellArgs *pArgs = &shell.args;
Y
Yang Zhao 已提交
1035 1036 1037 1038
#ifdef WEBSOCKET
  if (shell.args.restful || shell.args.cloud) {
	if (shell_conn_ws_server(1)) {
		return -1;
1039
	}
1040
  } else {
Y
Yang Zhao 已提交
1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
#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
1053
  }
Y
Yang Zhao 已提交
1054
#endif
1055

1056 1057
  shellReadHistory();

1058
  if (pArgs->commands != NULL || pArgs->file[0] != 0) {
1059
    if (pArgs->commands != NULL) {
wafwerar's avatar
wafwerar 已提交
1060
      printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
1061
      char *cmd = strdup(pArgs->commands);
1062
      shellRunCommand(cmd, true);
1063 1064 1065
      taosMemoryFree(cmd);
    }

1066
    if (pArgs->file[0] != 0) {
1067 1068
      shellSourceFile(pArgs->file);
    }
Y
Yang Zhao 已提交
1069 1070 1071 1072
#ifdef WEBSOCKET
	if (shell.args.restful || shell.args.cloud) {
		ws_close(shell.ws_conn);
	} else {
1073
#endif
Y
Yang Zhao 已提交
1074 1075 1076 1077
		taos_close(shell.conn);
#ifdef WEBSOCKET
	}
#endif
1078 1079

    shellWriteHistory();
1080
    shellCleanupHistory();
1081 1082 1083 1084
    return 0;
  }

  if (tsem_init(&shell.cancelSem, 0, 0) != 0) {
wafwerar's avatar
wafwerar 已提交
1085
    printf("failed to create cancel semphore\r\n");
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
    return -1;
  }

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

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

1096
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
1097

Y
Yang Zhao 已提交
1098 1099 1100 1101 1102 1103 1104
#ifdef WEBSOCKET
  if (!shell.args.restful && !shell.args.cloud) {
#endif
	shellGetGrantInfo();
#ifdef WEBSOCKET
  }
#endif
1105
  while (1) {
Y
Yang Zhao 已提交
1106
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, NULL);
1107
    taosThreadJoin(shell.pid, NULL);
1108
    taosThreadClear(&shell.pid);
1109 1110 1111 1112
    if (shell.exit) {
      tsem_post(&shell.cancelSem);
      break;
    }
1113
  }
1114
  taosThreadJoin(spid, NULL);
1115

1116
  shellCleanupHistory();
1117
  return 0;
S
slguan 已提交
1118
}