shellEngine.c 31.1 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"
A
Alex Duan 已提交
22
#include "shellAuto.h"
H
hzcheng 已提交
23

24 25
static bool    shellIsEmptyCommand(const char *cmd);
static int32_t shellRunSingleCommand(char *command);
26 27
static void    shellRecordCommandToHistory(char *command);
static int32_t shellRunCommand(char *command, bool recordHistory);
28 29 30 31
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 已提交
32 33 34
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);
35 36 37 38 39 40
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();
41

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

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

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

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

65
  if (shellRegexMatch(command, "^[\t ]*clear[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
66 67 68 69
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-result"
          system("clear");
#pragma GCC diagnostic pop
70 71
    return 0;
  }
72

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

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

115
void shellRecordCommandToHistory(char *command) {
116 117 118 119 120 121
  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]);
122
    }
123
    pHistory->hist[pHistory->hend] = strdup(command);
124

125 126 127
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
    if (pHistory->hend == pHistory->hstart) {
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
128 129
    }
  }
130 131 132 133 134 135 136
}

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

137 138 139 140 141 142
  // add help or help; 
  if(strcmp(command, "help") == 0 || strcmp(command, "help;") == 0) {
    showHelp();
    return 0;
  }

143
  if (recordHistory) shellRecordCommandToHistory(command);
144

wmmhello's avatar
wmmhello 已提交
145
  char quote = 0, *cmd = command;
146
  for (char c = *command++; c != 0; c = *command++) {
wmmhello's avatar
wmmhello 已提交
147
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
S
Shengliang Guan 已提交
148
      command++;
149 150
      continue;
    }
151

152 153
    if (quote == c) {
      quote = 0;
wmmhello's avatar
wmmhello 已提交
154
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
155
      quote = c;
wmmhello's avatar
wmmhello 已提交
156 157 158
    } else if (c == ';' && quote == 0) {
      c = *command;
      *command = 0;
159
      if (shellRunSingleCommand(cmd) < 0) {
160 161
        return -1;
      }
wmmhello's avatar
wmmhello 已提交
162 163
      *command = c;
      cmd = command;
164 165
    }
  }
166
  return shellRunSingleCommand(cmd);
D
dapan1121 已提交
167 168
}

169
void shellRunSingleCommandImp(char *command) {
170 171 172 173 174
  int64_t st, et;
  char   *sptr = NULL;
  char   *cptr = NULL;
  char   *fname = NULL;
  bool    printMode = false;
H
hzcheng 已提交
175 176 177 178 179 180 181

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

182
    fname = sptr + 2;
wafwerar's avatar
wafwerar 已提交
183
    while (*fname == ' ') fname++;
H
hzcheng 已提交
184 185 186
    *sptr = '\0';
  }

187 188 189 190 191 192 193 194 195 196
  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 已提交
197 198
  st = taosGetTimestampUs();

199
  TAOS_RES *pSql = taos_query(shell.conn, command);
H
Haojun Liao 已提交
200
  if (taos_errno(pSql)) {
201
    shellPrintError(pSql, st);
H
hzcheng 已提交
202 203 204
    return;
  }

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

A
Alex Duan 已提交
209 210 211
    // call back auto tab module
    callbackAutoTab(command, pSql, true);

S
Shengliang Guan 已提交
212 213
    taos_free_result(pSql);

H
hzcheng 已提交
214 215 216
    return;
  }

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

S
Shengliang Guan 已提交
221
    int32_t numOfRows = shellDumpResult(pSql, fname, &error_no, printMode, command);
222
    if (numOfRows < 0) return;
H
hzcheng 已提交
223 224 225

    et = taosGetTimestampUs();
    if (error_no == 0) {
226
      printf("Query OK, %d row(s) in set (%.6fs)\r\n", numOfRows, (et - st) / 1E6);
H
hzcheng 已提交
227
    } else {
228
      printf("Query interrupted (%s), %d row(s) in set (%.6fs)\r\n", taos_errstr(pSql), numOfRows, (et - st) / 1E6);
H
hzcheng 已提交
229
    }
S
Shengliang Guan 已提交
230
    taos_free_result(pSql);
H
hzcheng 已提交
231
  } else {
232
    int32_t num_rows_affacted = taos_affected_rows(pSql);
233
    taos_free_result(pSql);
H
hzcheng 已提交
234
    et = taosGetTimestampUs();
A
Alex Duan 已提交
235
    printf("Query OK, %d row(s) affected(%.6fs)\r\n", num_rows_affacted, (et - st) / 1E6);
A
Alex Duan 已提交
236 237

    // call auto tab
H
Haojun Liao 已提交
238
    callbackAutoTab(command, NULL, false);
H
hzcheng 已提交
239 240
  }

wafwerar's avatar
wafwerar 已提交
241
  printf("\r\n");
H
hzcheng 已提交
242 243
}

244 245
char *shellFormatTimestamp(char *buf, int64_t val, int32_t precision) {
  if (shell.args.is_raw_time) {
246 247 248
    sprintf(buf, "%" PRId64, val);
    return buf;
  }
H
hzcheng 已提交
249

S
Shengliang Guan 已提交
250
  time_t  tt;
D
fix bug  
dapan1121 已提交
251
  int32_t ms = 0;
252 253 254 255
  if (precision == TSDB_TIME_PRECISION_NANO) {
    tt = (time_t)(val / 1000000000);
    ms = val % 1000000000;
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
256
    tt = (time_t)(val / 1000000);
D
fix bug  
dapan1121 已提交
257
    ms = val % 1000000;
258 259
  } else {
    tt = (time_t)(val / 1000);
D
fix bug  
dapan1121 已提交
260
    ms = val % 1000;
261 262
  }

S
Shengliang Guan 已提交
263
  if (tt <= 0 && ms < 0) {
D
fix bug  
dapan1121 已提交
264
    tt--;
265 266 267
    if (precision == TSDB_TIME_PRECISION_NANO) {
      ms += 1000000000;
    } else if (precision == TSDB_TIME_PRECISION_MICRO) {
D
fix bug  
dapan1121 已提交
268 269 270 271 272
      ms += 1000000;
    } else {
      ms += 1000;
    }
  }
273

274 275 276
  struct tm ptm = {0};
  taosLocalTime(&tt, &ptm);
  size_t     pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
277

278 279 280
  if (precision == TSDB_TIME_PRECISION_NANO) {
    sprintf(buf + pos, ".%09d", ms);
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
D
fix bug  
dapan1121 已提交
281
    sprintf(buf + pos, ".%06d", ms);
282
  } else {
D
fix bug  
dapan1121 已提交
283
    sprintf(buf + pos, ".%03d", ms);
284 285 286 287 288
  }

  return buf;
}

wafwerar's avatar
wafwerar 已提交
289
void shellDumpFieldToFile(TdFilePtr pFile, const char *val, TAOS_FIELD *field, int32_t length, int32_t precision) {
290
  if (val == NULL) {
X
Xiaoyu Wang 已提交
291
    taosFprintfFile(pFile, "NULL");
292 293 294
    return;
  }

X
Xiaoyu Wang 已提交
295 296 297 298
  char quotationStr[2];
  quotationStr[0] = '\"';
  quotationStr[1] = 0;

S
Shengliang Guan 已提交
299
  int  n;
300 301 302
  char buf[TSDB_MAX_BYTES_PER_ROW];
  switch (field->type) {
    case TSDB_DATA_TYPE_BOOL:
wafwerar's avatar
wafwerar 已提交
303
      taosFprintfFile(pFile, "%d", ((((int32_t)(*((char *)val))) == 1) ? 1 : 0));
304 305
      break;
    case TSDB_DATA_TYPE_TINYINT:
wafwerar's avatar
wafwerar 已提交
306
      taosFprintfFile(pFile, "%d", *((int8_t *)val));
307
      break;
S
Shengliang Guan 已提交
308
    case TSDB_DATA_TYPE_UTINYINT:
wafwerar's avatar
wafwerar 已提交
309
      taosFprintfFile(pFile, "%u", *((uint8_t *)val));
S
Shengliang Guan 已提交
310
      break;
311
    case TSDB_DATA_TYPE_SMALLINT:
wafwerar's avatar
wafwerar 已提交
312
      taosFprintfFile(pFile, "%d", *((int16_t *)val));
313
      break;
S
Shengliang Guan 已提交
314
    case TSDB_DATA_TYPE_USMALLINT:
wafwerar's avatar
wafwerar 已提交
315
      taosFprintfFile(pFile, "%u", *((uint16_t *)val));
S
Shengliang Guan 已提交
316
      break;
317
    case TSDB_DATA_TYPE_INT:
wafwerar's avatar
wafwerar 已提交
318
      taosFprintfFile(pFile, "%d", *((int32_t *)val));
319
      break;
S
Shengliang Guan 已提交
320
    case TSDB_DATA_TYPE_UINT:
wafwerar's avatar
wafwerar 已提交
321
      taosFprintfFile(pFile, "%u", *((uint32_t *)val));
S
Shengliang Guan 已提交
322
      break;
323
    case TSDB_DATA_TYPE_BIGINT:
wafwerar's avatar
wafwerar 已提交
324
      taosFprintfFile(pFile, "%" PRId64, *((int64_t *)val));
325
      break;
S
Shengliang Guan 已提交
326
    case TSDB_DATA_TYPE_UBIGINT:
wafwerar's avatar
wafwerar 已提交
327
      taosFprintfFile(pFile, "%" PRIu64, *((uint64_t *)val));
S
Shengliang Guan 已提交
328
      break;
329
    case TSDB_DATA_TYPE_FLOAT:
wafwerar's avatar
wafwerar 已提交
330
      taosFprintfFile(pFile, "%.5f", GET_FLOAT_VAL(val));
331 332
      break;
    case TSDB_DATA_TYPE_DOUBLE:
wafwerar's avatar
wafwerar 已提交
333
      n = snprintf(buf, TSDB_MAX_BYTES_PER_ROW, "%*.9f", length, GET_DOUBLE_VAL(val));
334
      if (n > TMAX(25, length)) {
wafwerar's avatar
wafwerar 已提交
335
        taosFprintfFile(pFile, "%*.15e", length, GET_DOUBLE_VAL(val));
S
Shengliang Guan 已提交
336 337 338
      } else {
        taosFprintfFile(pFile, "%s", buf);
      }
339 340 341
      break;
    case TSDB_DATA_TYPE_BINARY:
    case TSDB_DATA_TYPE_NCHAR:
wmmhello's avatar
wmmhello 已提交
342
    case TSDB_DATA_TYPE_JSON:
wafwerar's avatar
wafwerar 已提交
343 344 345
      {
        int32_t bufIndex = 0;
        for (int32_t i = 0; i < length; i++) {
wafwerar's avatar
wafwerar 已提交
346 347
          buf[bufIndex] = val[i];
          bufIndex++;
wafwerar's avatar
wafwerar 已提交
348 349 350 351
          if (val[i] == '\"') {
            buf[bufIndex] = val[i];
            bufIndex++;
          }
wafwerar's avatar
wafwerar 已提交
352
        }
wafwerar's avatar
wafwerar 已提交
353
        buf[bufIndex] = 0;
wafwerar's avatar
wafwerar 已提交
354
        
wafwerar's avatar
wafwerar 已提交
355
        taosFprintfFile(pFile, "%s%s%s", quotationStr, buf, quotationStr);
wafwerar's avatar
wafwerar 已提交
356
      }
357 358
      break;
    case TSDB_DATA_TYPE_TIMESTAMP:
359
      shellFormatTimestamp(buf, *(int64_t *)val, precision);
X
Xiaoyu Wang 已提交
360
      taosFprintfFile(pFile, "%s%s%s", quotationStr, buf, quotationStr);
361 362 363 364 365 366
      break;
    default:
      break;
  }
}

367
int32_t shellDumpResultToFile(const char *fname, TAOS_RES *tres) {
368 369 370 371 372
  char fullname[PATH_MAX] = {0};
  if (taosExpandDir(fname, fullname, PATH_MAX) != 0) {
    tstrncpy(fullname, fname, PATH_MAX);
  }

373
  TAOS_ROW row = taos_fetch_row(tres);
374 375 376 377
  if (row == NULL) {
    return 0;
  }

378
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_TRUNC | TD_FILE_STREAM);
379
  if (pFile == NULL) {
wafwerar's avatar
wafwerar 已提交
380
    fprintf(stderr, "failed to open file: %s\r\n", fullname);
381 382 383
    return -1;
  }

384
  TAOS_FIELD *fields = taos_fetch_fields(tres);
385 386
  int32_t     num_fields = taos_num_fields(tres);
  int32_t     precision = taos_result_precision(tres);
387

388
  for (int32_t col = 0; col < num_fields; col++) {
389
    if (col > 0) {
390
      taosFprintfFile(pFile, ",");
391
    }
392
    taosFprintfFile(pFile, "%s", fields[col].name);
393
  }
wafwerar's avatar
wafwerar 已提交
394
  taosFprintfFile(pFile, "\r\n");
395

396
  int32_t numOfRows = 0;
397
  do {
S
Shengliang Guan 已提交
398
    int32_t *length = taos_fetch_lengths(tres);
399
    for (int32_t i = 0; i < num_fields; i++) {
400
      if (i > 0) {
X
Xiaoyu Wang 已提交
401
        taosFprintfFile(pFile, ",");
402
      }
wafwerar's avatar
wafwerar 已提交
403
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision);
H
hzcheng 已提交
404
    }
wafwerar's avatar
wafwerar 已提交
405
    taosFprintfFile(pFile, "\r\n");
406 407

    numOfRows++;
408
    row = taos_fetch_row(tres);
S
Shengliang Guan 已提交
409
  } while (row != NULL);
410

411
  taosCloseFile(&pFile);
412

413 414 415
  return numOfRows;
}

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

420
  while (pos < length) {
wafwerar's avatar
wafwerar 已提交
421
    TdWchar wc;
422
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
wmmhello's avatar
wmmhello 已提交
423
    if (bytes <= 0) {
424 425
      break;
    }
wmmhello's avatar
wmmhello 已提交
426 427

    if (pos + bytes > length) {
428 429
      break;
    }
wmmhello's avatar
wmmhello 已提交
430
    int w = 0;
X
Xiaoyu Wang 已提交
431
    if (*(str + pos) == '\t' || *(str + pos) == '\n' || *(str + pos) == '\r') {
wmmhello's avatar
wmmhello 已提交
432
      w = bytes;
X
Xiaoyu Wang 已提交
433
    } else {
wmmhello's avatar
wmmhello 已提交
434 435 436 437
      w = taosWcharWidth(wc);
    }
    pos += bytes;

438 439 440 441 442 443 444 445 446 447 448 449 450 451
    if (w <= 0) {
      continue;
    }

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

    totalCols += w;
    if (totalCols > width) {
      break;
    }
    if (totalCols <= (width - 3)) {
452 453
      printf("%lc", wc);
      cols += w;
454 455 456
    } else {
      tail[tailLen] = wc;
      tailLen++;
457 458 459
    }
  }

460 461
  if (totalCols > width) {
    // width could be 1 or 2, so printf("...") cannot be used
462
    for (int32_t i = 0; i < 3; i++) {
463 464 465 466 467 468 469
      if (cols >= width) {
        break;
      }
      putchar('.');
      ++cols;
    }
  } else {
470
    for (int32_t i = 0; i < tailLen; i++) {
471 472 473 474 475
      printf("%lc", tail[i]);
    }
    cols = totalCols;
  }

476 477 478 479 480
  for (; cols < width; cols++) {
    putchar(' ');
  }
}

481
void shellPrintField(const char *val, TAOS_FIELD *field, int32_t width, int32_t length, int32_t precision) {
482
  if (val == NULL) {
483
    int32_t w = width;
484 485
    if (field->type < TSDB_DATA_TYPE_TINYINT || field->type > TSDB_DATA_TYPE_DOUBLE) {
      w = 0;
H
hzcheng 已提交
486
    }
487 488 489 490 491 492
    w = printf("%*s", w, TSDB_DATA_NULL_STR);
    for (; w < width; w++) {
      putchar(' ');
    }
    return;
  }
H
hzcheng 已提交
493

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

549 550 551
// show whole result for this query return true, like limit or describe
bool shellIsShowWhole(const char *sql) {
  // limit
wafwerar's avatar
wafwerar 已提交
552
  if (taosStrCaseStr(sql, " limit ") != NULL) {
S
Shengliang Guan 已提交
553 554
    return true;
  }
555 556 557 558
  // describe
  if (taosStrCaseStr(sql, "describe ") != NULL) {
    return true;
  }
559
  // show
560 561 562
  if (taosStrCaseStr(sql, "show ") != NULL) {
    return true;
  }
S
Shengliang Guan 已提交
563 564 565 566

  return false;
}

D
dapan1121 已提交
567
bool shellIsShowQuery(const char *sql) {
X
Xiaoyu Wang 已提交
568
  // todo refactor
D
dapan1121 已提交
569 570 571 572 573 574 575
  if (taosStrCaseStr(sql, "show ") != NULL) {
    return true;
  }

  return false;
}

S
Shengliang Guan 已提交
576
int32_t shellVerticalPrintResult(TAOS_RES *tres, const char *sql) {
H
Haojun Liao 已提交
577
  TAOS_ROW row = taos_fetch_row(tres);
578 579 580 581
  if (row == NULL) {
    return 0;
  }

582
  int32_t     num_fields = taos_num_fields(tres);
H
Haojun Liao 已提交
583
  TAOS_FIELD *fields = taos_fetch_fields(tres);
584
  int32_t     precision = taos_result_precision(tres);
585

586 587 588
  int32_t maxColNameLen = 0;
  for (int32_t col = 0; col < num_fields; col++) {
    int32_t len = (int32_t)strlen(fields[col].name);
589 590 591 592 593
    if (len > maxColNameLen) {
      maxColNameLen = len;
    }
  }

D
fix bug  
dapan1121 已提交
594 595
  uint64_t resShowMaxNum = UINT64_MAX;

596
  if (shell.args.commands == NULL && shell.args.file[0] == 0 && !shellIsShowWhole(sql)) {
597
    resShowMaxNum = SHELL_DEFAULT_RES_SHOW_NUM;
D
fix bug  
dapan1121 已提交
598 599
  }

600 601
  int32_t numOfRows = 0;
  int32_t showMore = 1;
602
  do {
D
fix bug  
dapan1121 已提交
603
    if (numOfRows < resShowMaxNum) {
wafwerar's avatar
wafwerar 已提交
604
      printf("*************************** %d.row ***************************\r\n", numOfRows + 1);
D
fix bug  
dapan1121 已提交
605

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

608
      for (int32_t i = 0; i < num_fields; i++) {
S
Shengliang Guan 已提交
609
        TAOS_FIELD *field = fields + i;
610

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

614
        shellPrintField((const char *)row[i], field, 0, length[i], precision);
wafwerar's avatar
wafwerar 已提交
615
        putchar('\r');
D
fix bug  
dapan1121 已提交
616 617
        putchar('\n');
      }
D
fix bug  
dapan1121 已提交
618
    } else if (showMore) {
wafwerar's avatar
wafwerar 已提交
619 620 621 622 623 624 625
      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 已提交
626
      showMore = 0;
627 628 629
    }

    numOfRows++;
H
Haojun Liao 已提交
630
    row = taos_fetch_row(tres);
S
Shengliang Guan 已提交
631
  } while (row != NULL);
632 633 634 635

  return numOfRows;
}

636 637
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
  int32_t width = (int32_t)strlen(field->name);
638 639

  switch (field->type) {
D
dapan1121 已提交
640 641
    case TSDB_DATA_TYPE_NULL:
      return TMAX(4, width);  // null
642
    case TSDB_DATA_TYPE_BOOL:
dengyihao's avatar
dengyihao 已提交
643
      return TMAX(5, width);  // 'false'
644 645

    case TSDB_DATA_TYPE_TINYINT:
646
    case TSDB_DATA_TYPE_UTINYINT:
dengyihao's avatar
dengyihao 已提交
647
      return TMAX(4, width);  // '-127'
648 649

    case TSDB_DATA_TYPE_SMALLINT:
650
    case TSDB_DATA_TYPE_USMALLINT:
dengyihao's avatar
dengyihao 已提交
651
      return TMAX(6, width);  // '-32767'
652 653

    case TSDB_DATA_TYPE_INT:
654
    case TSDB_DATA_TYPE_UINT:
dengyihao's avatar
dengyihao 已提交
655
      return TMAX(11, width);  // '-2147483648'
656 657

    case TSDB_DATA_TYPE_BIGINT:
658
    case TSDB_DATA_TYPE_UBIGINT:
dengyihao's avatar
dengyihao 已提交
659
      return TMAX(21, width);  // '-9223372036854775807'
660 661

    case TSDB_DATA_TYPE_FLOAT:
dengyihao's avatar
dengyihao 已提交
662
      return TMAX(20, width);
663 664

    case TSDB_DATA_TYPE_DOUBLE:
dengyihao's avatar
dengyihao 已提交
665
      return TMAX(25, width);
666 667

    case TSDB_DATA_TYPE_BINARY:
668 669
      if (field->bytes > shell.args.displayWidth) {
        return TMAX(shell.args.displayWidth, width);
670
      } else {
dengyihao's avatar
dengyihao 已提交
671
        return TMAX(field->bytes, width);
672 673
      }

wmmhello's avatar
wmmhello 已提交
674 675
    case TSDB_DATA_TYPE_NCHAR:
    case TSDB_DATA_TYPE_JSON: {
676
      int16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
677 678
      if (bytes > shell.args.displayWidth) {
        return TMAX(shell.args.displayWidth, width);
679
      } else {
dengyihao's avatar
dengyihao 已提交
680
        return TMAX(bytes, width);
681 682 683
      }
    }

684
    case TSDB_DATA_TYPE_TIMESTAMP:
685
      if (shell.args.is_raw_time) {
dengyihao's avatar
dengyihao 已提交
686
        return TMAX(14, width);
S
Shengliang Guan 已提交
687 688
      }
      if (precision == TSDB_TIME_PRECISION_NANO) {
dengyihao's avatar
dengyihao 已提交
689
        return TMAX(29, width);
690
      } else if (precision == TSDB_TIME_PRECISION_MICRO) {
dengyihao's avatar
dengyihao 已提交
691
        return TMAX(26, width);  // '2020-01-01 00:00:00.000000'
692
      } else {
dengyihao's avatar
dengyihao 已提交
693
        return TMAX(23, width);  // '2020-01-01 00:00:00.000'
S
slguan 已提交
694
      }
H
hzcheng 已提交
695

696 697
    default:
      assert(false);
H
hzcheng 已提交
698 699
  }

700 701
  return 0;
}
H
hzcheng 已提交
702

703 704 705
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 已提交
706
    TAOS_FIELD *field = fields + col;
707 708
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
    int32_t     left = padding / 2;
709 710 711 712
    printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
    rowWidth += width[col] + 3;
  }

wafwerar's avatar
wafwerar 已提交
713
  putchar('\r');
714
  putchar('\n');
715
  for (int32_t i = 0; i < rowWidth; i++) {
716 717
    putchar('=');
  }
wafwerar's avatar
wafwerar 已提交
718
  putchar('\r');
719 720 721
  putchar('\n');
}

S
Shengliang Guan 已提交
722
int32_t shellHorizontalPrintResult(TAOS_RES *tres, const char *sql) {
H
Haojun Liao 已提交
723
  TAOS_ROW row = taos_fetch_row(tres);
724 725 726 727
  if (row == NULL) {
    return 0;
  }

728
  int32_t     num_fields = taos_num_fields(tres);
H
Haojun Liao 已提交
729
  TAOS_FIELD *fields = taos_fetch_fields(tres);
730
  int32_t     precision = taos_result_precision(tres);
731

732 733 734
  int32_t width[TSDB_MAX_COLUMNS];
  for (int32_t col = 0; col < num_fields; col++) {
    width[col] = shellCalcColWidth(fields + col, precision);
735 736
  }

737
  shellPrintHeader(fields, width, num_fields);
738

D
fix bug  
dapan1121 已提交
739 740
  uint64_t resShowMaxNum = UINT64_MAX;

741
  if (shell.args.commands == NULL && shell.args.file[0] == 0 && !shellIsShowWhole(sql)) {
742
    resShowMaxNum = SHELL_DEFAULT_RES_SHOW_NUM;
D
fix bug  
dapan1121 已提交
743 744
  }

745 746
  int32_t numOfRows = 0;
  int32_t showMore = 1;
747

748
  do {
S
Shengliang Guan 已提交
749
    int32_t *length = taos_fetch_lengths(tres);
D
fix bug  
dapan1121 已提交
750
    if (numOfRows < resShowMaxNum) {
751
      for (int32_t i = 0; i < num_fields; i++) {
D
fix bug  
dapan1121 已提交
752
        putchar(' ');
753
        shellPrintField((const char *)row[i], fields + i, width[i], length[i], precision);
D
fix bug  
dapan1121 已提交
754 755 756
        putchar(' ');
        putchar('|');
      }
wafwerar's avatar
wafwerar 已提交
757
      putchar('\r');
D
fix bug  
dapan1121 已提交
758
      putchar('\n');
D
fix bug  
dapan1121 已提交
759
    } else if (showMore) {
wafwerar's avatar
wafwerar 已提交
760 761
      printf("\r\n");
      printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
wafwerar's avatar
wafwerar 已提交
762 763 764 765 766 767
      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 已提交
768 769 770
      printf("\r\n");
      printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
      printf("\r\n");
S
Shengliang Guan 已提交
771
      showMore = 0;
772
    }
773

774
    numOfRows++;
H
Haojun Liao 已提交
775
    row = taos_fetch_row(tres);
S
Shengliang Guan 已提交
776
  } while (row != NULL);
777 778 779 780

  return numOfRows;
}

S
Shengliang Guan 已提交
781
int32_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
782
  int32_t numOfRows = 0;
H
hzcheng 已提交
783
  if (fname != NULL) {
784
    numOfRows = shellDumpResultToFile(fname, tres);
S
Shengliang Guan 已提交
785
  } else if (vertical) {
S
Shengliang Guan 已提交
786
    numOfRows = shellVerticalPrintResult(tres, sql);
787
  } else {
S
Shengliang Guan 已提交
788
    numOfRows = shellHorizontalPrintResult(tres, sql);
H
hzcheng 已提交
789 790
  }

H
Haojun Liao 已提交
791
  *error_no = taos_errno(tres);
H
hzcheng 已提交
792 793 794
  return numOfRows;
}

795
void shellReadHistory() {
796 797 798
  SShellHistory *pHistory = &shell.history;
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_READ | TD_FILE_STREAM);
  if (pFile == NULL) return;
H
hzcheng 已提交
799

wafwerar's avatar
wafwerar 已提交
800
  char    *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
801
  int32_t read_size = 0;
wafwerar's avatar
wafwerar 已提交
802
  while ((read_size = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) != -1) {
H
hzcheng 已提交
803
    line[read_size - 1] = '\0';
804
    taosMemoryFree(pHistory->hist[pHistory->hend]);
805
    pHistory->hist[pHistory->hend] = strdup(line);
H
hzcheng 已提交
806

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

809 810
    if (pHistory->hend == pHistory->hstart) {
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
H
hzcheng 已提交
811 812 813
    }
  }

wafwerar's avatar
wafwerar 已提交
814
  taosMemoryFreeClear(line);
815
  taosCloseFile(&pFile);
816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
  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 已提交
832
  pHistory->hstart = pHistory->hend;
H
hzcheng 已提交
833 834
}

835
void shellWriteHistory() {
836
  SShellHistory *pHistory = &shell.history;
837
  if (pHistory->hend == pHistory->hstart) return;
S
Shengliang Guan 已提交
838
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_APPEND);
839
  if (pFile == NULL) return;
H
hzcheng 已提交
840

841 842 843
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
    if (pHistory->hist[i] != NULL) {
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
844 845
      taosMemoryFree(pHistory->hist[i]);
      pHistory->hist[i] = NULL;
H
hzcheng 已提交
846
    }
847
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
H
hzcheng 已提交
848
  }
849
  taosFsyncFile(pFile);
850
  taosCloseFile(&pFile);
H
hzcheng 已提交
851 852
}

853 854 855 856 857 858 859 860 861 862
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;
    }
  }
}

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

869 870
bool shellIsCommentLine(char *line) {
  if (line == NULL) return true;
871
  return shellRegexMatch(line, "^\\s*#.*", REG_EXTENDED);
H
hzcheng 已提交
872 873
}

874 875 876 877
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;
878
  char    fullname[PATH_MAX] = {0};
879
  char    sourceFileCommand[PATH_MAX + 8] = {0};
H
hzcheng 已提交
880

881 882
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
    tstrncpy(fullname, file, PATH_MAX);
H
hzcheng 已提交
883 884
  }

885 886 887
  sprintf(sourceFileCommand, "source %s;",fullname);
  shellRecordCommandToHistory(sourceFileCommand);

888
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_READ | TD_FILE_STREAM);
889
  if (pFile == NULL) {
wafwerar's avatar
wafwerar 已提交
890
    fprintf(stderr, "failed to open file %s\r\n", fullname);
wafwerar's avatar
wafwerar 已提交
891
    taosMemoryFree(cmd);
H
hzcheng 已提交
892 893 894
    return;
  }

wafwerar's avatar
wafwerar 已提交
895 896
  char   *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
  while ((read_len = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) != -1) {
H
Haojun Liao 已提交
897
    if (read_len >= TSDB_MAX_ALLOWED_SQL_LEN) continue;
H
hzcheng 已提交
898 899
    line[--read_len] = '\0';

900
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
H
hzcheng 已提交
901 902 903 904 905 906 907 908 909 910
      continue;
    }

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

911 912 913 914
    if (line[read_len - 1] == '\r') {
      line[read_len - 1] = ' ';
    }

H
hzcheng 已提交
915
    memcpy(cmd + cmd_len, line, read_len);
wafwerar's avatar
wafwerar 已提交
916
    printf("%s%s\r\n", shell.info.promptHeader, cmd);
917
    shellRunCommand(cmd, false);
H
Haojun Liao 已提交
918
    memset(cmd, 0, TSDB_MAX_ALLOWED_SQL_LEN);
H
hzcheng 已提交
919 920 921
    cmd_len = 0;
  }

wafwerar's avatar
wafwerar 已提交
922
  taosMemoryFree(cmd);
wafwerar's avatar
wafwerar 已提交
923
  taosMemoryFreeClear(line);
924
  taosCloseFile(&pFile);
H
hzcheng 已提交
925
}
S
slguan 已提交
926

927
void shellGetGrantInfo() {
928 929
  char sinfo[1024] = {0};
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
wafwerar's avatar
wafwerar 已提交
930
  strtok(sinfo, "\r\n");
931

S
slguan 已提交
932 933
  char sql[] = "show grants";

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

936
  int32_t code = taos_errno(tres);
S
slguan 已提交
937
  if (code != TSDB_CODE_SUCCESS) {
938
    if (code != TSDB_CODE_OPS_NOT_SUPPORT && code != TSDB_CODE_MND_NO_RIGHTS) {
wafwerar's avatar
wafwerar 已提交
939
      fprintf(stderr, "Failed to check Server Edition, Reason:0x%04x:%s\r\n\r\n", code, taos_errstr(tres));
S
slguan 已提交
940
    }
S
slguan 已提交
941 942 943
    return;
  }

944
  int32_t num_fields = taos_field_count(tres);
S
slguan 已提交
945
  if (num_fields == 0) {
wafwerar's avatar
wafwerar 已提交
946
    fprintf(stderr, "\r\nInvalid grant information.\r\n");
S
slguan 已提交
947 948
    exit(0);
  } else {
949
    if (tres == NULL) {
wafwerar's avatar
wafwerar 已提交
950
      fprintf(stderr, "\r\nGrant information is null.\r\n");
S
slguan 已提交
951 952 953
      exit(0);
    }

954
    TAOS_FIELD *fields = taos_fetch_fields(tres);
955
    TAOS_ROW    row = taos_fetch_row(tres);
S
slguan 已提交
956
    if (row == NULL) {
wafwerar's avatar
wafwerar 已提交
957
      fprintf(stderr, "\r\nFailed to get grant information from server. Abort.\r\n");
S
slguan 已提交
958 959 960
      exit(0);
    }

S
slguan 已提交
961
    char serverVersion[32] = {0};
S
slguan 已提交
962 963 964
    char expiretime[32] = {0};
    char expired[32] = {0};

S
slguan 已提交
965
    memcpy(serverVersion, row[0], fields[0].bytes);
S
slguan 已提交
966 967 968
    memcpy(expiretime, row[1], fields[1].bytes);
    memcpy(expired, row[2], fields[2].bytes);

969
    if (strcmp(serverVersion, "community") == 0) {
wafwerar's avatar
wafwerar 已提交
970
      fprintf(stdout, "Server is Community Edition.\r\n");
971
    } else if (strcmp(expiretime, "unlimited") == 0) {
wafwerar's avatar
wafwerar 已提交
972
      fprintf(stdout, "Server is Enterprise %s Edition, %s and will never expire.\r\n", serverVersion, sinfo);
S
slguan 已提交
973
    } else {
wafwerar's avatar
wafwerar 已提交
974
      fprintf(stdout, "Server is Enterprise %s Edition, %s and will expire at %s.\r\n", serverVersion, sinfo, expiretime);
S
slguan 已提交
975 976
    }

977
    taos_free_result(tres);
S
slguan 已提交
978 979
  }

wafwerar's avatar
wafwerar 已提交
980
  fprintf(stdout, "\r\n");
981 982
}

983 984 985 986
#ifdef WINDOWS
BOOL shellQueryInterruptHandler(DWORD fdwCtrlType) {
  tsem_post(&shell.cancelSem);
  return TRUE;
987
}
988 989 990
#else
void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) { tsem_post(&shell.cancelSem); }
#endif
991

992 993 994 995 996
void shellCleanup(void *arg) { taosResetTerminalMode(); }

void *shellCancelHandler(void *arg) {
  setThreadName("shellCancelHandler");
  while (1) {
997 998 999 1000
    if (shell.exit == true) {
      break;
    }

1001 1002 1003 1004
    if (tsem_wait(&shell.cancelSem) != 0) {
      taosMsleep(10);
      continue;
    }
Y
Yang Zhao 已提交
1005 1006 1007 1008 1009 1010

#ifdef WEBSOCKET
	if (shell.args.restful || shell.args.cloud) {
		shell.stop_query = true;
	} else {
#endif
D
dapan1121 已提交
1011 1012 1013
    if (shell.conn) {
		  taos_kill_query(shell.conn);
		}
Y
Yang Zhao 已提交
1014 1015
#ifdef WEBSOCKET
	}
1016
#endif
1017 1018 1019
  #ifdef WINDOWS
    printf("\n%s", shell.info.promptHeader);
  #endif
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
  }

  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 已提交
1032
    printf("failed to malloc command\r\n");
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    return NULL;
  }

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

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

    taosResetTerminalMode();
1045
  } while (shellRunCommand(command, true) == 0);
1046 1047

  taosMemoryFreeClear(command);
1048 1049
  shellWriteHistory();
  shellExit();
1050

1051 1052 1053 1054 1055
  taosThreadCleanupPop(1);
  return NULL;
}

int32_t shellExecute() {
wafwerar's avatar
wafwerar 已提交
1056
  printf(shell.info.clientVersion, taos_get_client_info());
1057 1058 1059
  fflush(stdout);

  SShellArgs *pArgs = &shell.args;
Y
Yang Zhao 已提交
1060 1061 1062 1063
#ifdef WEBSOCKET
  if (shell.args.restful || shell.args.cloud) {
	if (shell_conn_ws_server(1)) {
		return -1;
1064
	}
1065
  } else {
Y
Yang Zhao 已提交
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
#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
1078
  }
Y
Yang Zhao 已提交
1079
#endif
1080

A
Alex Duan 已提交
1081
  shellSetConn(shell.conn);
1082 1083
  shellReadHistory();

1084
  if (pArgs->commands != NULL || pArgs->file[0] != 0) {
1085
    if (pArgs->commands != NULL) {
wafwerar's avatar
wafwerar 已提交
1086
      printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
1087
      char *cmd = strdup(pArgs->commands);
1088
      shellRunCommand(cmd, true);
1089 1090 1091
      taosMemoryFree(cmd);
    }

1092
    if (pArgs->file[0] != 0) {
1093 1094
      shellSourceFile(pArgs->file);
    }
Y
Yang Zhao 已提交
1095 1096 1097 1098
#ifdef WEBSOCKET
	if (shell.args.restful || shell.args.cloud) {
		ws_close(shell.ws_conn);
	} else {
1099
#endif
Y
Yang Zhao 已提交
1100 1101 1102 1103
		taos_close(shell.conn);
#ifdef WEBSOCKET
	}
#endif
1104 1105

    shellWriteHistory();
1106
    shellCleanupHistory();
1107 1108 1109 1110
    return 0;
  }

  if (tsem_init(&shell.cancelSem, 0, 0) != 0) {
wafwerar's avatar
wafwerar 已提交
1111
    printf("failed to create cancel semphore\r\n");
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
    return -1;
  }

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

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

1122
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
1123

Y
Yang Zhao 已提交
1124 1125 1126
#ifdef WEBSOCKET
  if (!shell.args.restful && !shell.args.cloud) {
#endif
1127
#ifndef WINDOWS
1128
  printfIntroduction();
1129
#endif  
Y
Yang Zhao 已提交
1130 1131 1132 1133
	shellGetGrantInfo();
#ifdef WEBSOCKET
  }
#endif
1134
  while (1) {
Y
Yang Zhao 已提交
1135
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, NULL);
1136
    taosThreadJoin(shell.pid, NULL);
1137
    taosThreadClear(&shell.pid);
1138 1139 1140 1141
    if (shell.exit) {
      tsem_post(&shell.cancelSem);
      break;
    }
1142
  }
1143
  taosThreadJoin(spid, NULL);
1144

1145
  shellCleanupHistory();
1146
  return 0;
S
slguan 已提交
1147
}