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

114
void shellRecordCommandToHistory(char *command) {
115 116 117 118 119 120 121
  if (strncasecmp(command, "create user ", 12) == 0 || strncasecmp(command, "alter user ", 11) == 0) {
    if (taosStrCaseStr(command, " pass ")) {
      // have password command forbid record to history because security
      return;
    }
  }

122 123 124 125 126 127
  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]);
128
    }
129
    pHistory->hist[pHistory->hend] = taosStrdup(command);
130

131 132 133
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
    if (pHistory->hend == pHistory->hstart) {
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
134 135
    }
  }
136 137 138 139 140 141 142
}

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

143
  // add help or help; 
144
  if(strncasecmp(command, "help;", 5) == 0) {
145 146 147 148
    showHelp();
    return 0;
  }

149
  if (recordHistory) shellRecordCommandToHistory(command);
150

wmmhello's avatar
wmmhello 已提交
151
  char quote = 0, *cmd = command;
152
  for (char c = *command++; c != 0; c = *command++) {
wmmhello's avatar
wmmhello 已提交
153
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
S
Shengliang Guan 已提交
154
      command++;
155 156
      continue;
    }
157

158 159
    if (quote == c) {
      quote = 0;
wmmhello's avatar
wmmhello 已提交
160
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
161
      quote = c;
wmmhello's avatar
wmmhello 已提交
162 163 164
    } else if (c == ';' && quote == 0) {
      c = *command;
      *command = 0;
165
      if (shellRunSingleCommand(cmd) < 0) {
166 167
        return -1;
      }
wmmhello's avatar
wmmhello 已提交
168 169
      *command = c;
      cmd = command;
170 171
    }
  }
172
  return shellRunSingleCommand(cmd);
D
dapan1121 已提交
173 174
}

175
void shellRunSingleCommandImp(char *command) {
176 177 178 179 180
  int64_t st, et;
  char   *sptr = NULL;
  char   *cptr = NULL;
  char   *fname = NULL;
  bool    printMode = false;
H
hzcheng 已提交
181 182 183 184 185 186 187

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

188
    fname = sptr + 2;
wafwerar's avatar
wafwerar 已提交
189
    while (*fname == ' ') fname++;
H
hzcheng 已提交
190 191 192
    *sptr = '\0';
  }

193 194 195 196 197 198 199 200 201 202
  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 已提交
203 204
  st = taosGetTimestampUs();

205
  TAOS_RES *pSql = taos_query(shell.conn, command);
H
Haojun Liao 已提交
206
  if (taos_errno(pSql)) {
207
    shellPrintError(pSql, st);
H
hzcheng 已提交
208 209 210
    return;
  }

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

A
Alex Duan 已提交
215 216 217
    // call back auto tab module
    callbackAutoTab(command, pSql, true);

S
Shengliang Guan 已提交
218 219
    taos_free_result(pSql);

H
hzcheng 已提交
220 221 222
    return;
  }

223 224 225
  // pre string
  char * pre = "Query OK";
  if (shellRegexMatch(command, "^\\s*delete\\s*from\\s*.*", REG_EXTENDED | REG_ICASE)) {
A
Alex Duan 已提交
226
    pre = "Delete OK";
227
  } else if(shellRegexMatch(command, "^\\s*insert\\s*into\\s*.*", REG_EXTENDED | REG_ICASE)) {
A
Alex Duan 已提交
228
    pre = "Insert OK";
229
  } else if(shellRegexMatch(command, "^\\s*create\\s*.*", REG_EXTENDED | REG_ICASE)) {
A
Alex Duan 已提交
230
    pre = "Create OK";
231
  } else if(shellRegexMatch(command, "^\\s*drop\\s*.*", REG_EXTENDED | REG_ICASE)) {
A
Alex Duan 已提交
232
    pre = "Drop OK";
233 234
  }

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

S
Shengliang Guan 已提交
239
    int32_t numOfRows = shellDumpResult(pSql, fname, &error_no, printMode, command);
240
    if (numOfRows < 0) return;
H
hzcheng 已提交
241 242 243

    et = taosGetTimestampUs();
    if (error_no == 0) {
244
      printf("Query OK, %d row(s) in set (%.6fs)\r\n", numOfRows, (et - st) / 1E6);
H
hzcheng 已提交
245
    } else {
246
      printf("Query interrupted (%s), %d row(s) in set (%.6fs)\r\n", taos_errstr(pSql), numOfRows, (et - st) / 1E6);
H
hzcheng 已提交
247
    }
S
Shengliang Guan 已提交
248
    taos_free_result(pSql);
H
hzcheng 已提交
249
  } else {
250
    int64_t num_rows_affacted = taos_affected_rows64(pSql);
251
    taos_free_result(pSql);
H
hzcheng 已提交
252
    et = taosGetTimestampUs();
A
Alex Duan 已提交
253
    printf("%s, %" PRId64 " row(s) affected (%.6fs)\r\n", pre, num_rows_affacted, (et - st) / 1E6);
A
Alex Duan 已提交
254 255

    // call auto tab
H
Haojun Liao 已提交
256
    callbackAutoTab(command, NULL, false);
H
hzcheng 已提交
257 258
  }

wafwerar's avatar
wafwerar 已提交
259
  printf("\r\n");
H
hzcheng 已提交
260 261
}

262 263
char *shellFormatTimestamp(char *buf, int64_t val, int32_t precision) {
  if (shell.args.is_raw_time) {
264 265 266
    sprintf(buf, "%" PRId64, val);
    return buf;
  }
H
hzcheng 已提交
267

S
Shengliang Guan 已提交
268
  time_t  tt;
D
fix bug  
dapan1121 已提交
269
  int32_t ms = 0;
270 271 272 273
  if (precision == TSDB_TIME_PRECISION_NANO) {
    tt = (time_t)(val / 1000000000);
    ms = val % 1000000000;
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
274
    tt = (time_t)(val / 1000000);
D
fix bug  
dapan1121 已提交
275
    ms = val % 1000000;
276 277
  } else {
    tt = (time_t)(val / 1000);
D
fix bug  
dapan1121 已提交
278
    ms = val % 1000;
279 280
  }

S
Shengliang Guan 已提交
281
  if (tt <= 0 && ms < 0) {
D
fix bug  
dapan1121 已提交
282
    tt--;
283 284 285
    if (precision == TSDB_TIME_PRECISION_NANO) {
      ms += 1000000000;
    } else if (precision == TSDB_TIME_PRECISION_MICRO) {
D
fix bug  
dapan1121 已提交
286 287 288 289 290
      ms += 1000000;
    } else {
      ms += 1000;
    }
  }
291

292
  struct tm ptm = {0};
293
  if (taosLocalTime(&tt, &ptm, buf) == NULL) {
294 295
    return buf;
  }
296
  size_t     pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
297

298 299 300
  if (precision == TSDB_TIME_PRECISION_NANO) {
    sprintf(buf + pos, ".%09d", ms);
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
D
fix bug  
dapan1121 已提交
301
    sprintf(buf + pos, ".%06d", ms);
302
  } else {
D
fix bug  
dapan1121 已提交
303
    sprintf(buf + pos, ".%03d", ms);
304 305 306 307 308
  }

  return buf;
}

wafwerar's avatar
wafwerar 已提交
309
void shellDumpFieldToFile(TdFilePtr pFile, const char *val, TAOS_FIELD *field, int32_t length, int32_t precision) {
310
  if (val == NULL) {
X
Xiaoyu Wang 已提交
311
    taosFprintfFile(pFile, "NULL");
312 313 314
    return;
  }

X
Xiaoyu Wang 已提交
315 316 317 318
  char quotationStr[2];
  quotationStr[0] = '\"';
  quotationStr[1] = 0;

319
  int  n;
320 321 322
  char buf[TSDB_MAX_BYTES_PER_ROW];
  switch (field->type) {
    case TSDB_DATA_TYPE_BOOL:
wafwerar's avatar
wafwerar 已提交
323
      taosFprintfFile(pFile, "%d", ((((int32_t)(*((char *)val))) == 1) ? 1 : 0));
324 325
      break;
    case TSDB_DATA_TYPE_TINYINT:
wafwerar's avatar
wafwerar 已提交
326
      taosFprintfFile(pFile, "%d", *((int8_t *)val));
327
      break;
S
Shengliang Guan 已提交
328
    case TSDB_DATA_TYPE_UTINYINT:
wafwerar's avatar
wafwerar 已提交
329
      taosFprintfFile(pFile, "%u", *((uint8_t *)val));
S
Shengliang Guan 已提交
330
      break;
331
    case TSDB_DATA_TYPE_SMALLINT:
wafwerar's avatar
wafwerar 已提交
332
      taosFprintfFile(pFile, "%d", *((int16_t *)val));
333
      break;
S
Shengliang Guan 已提交
334
    case TSDB_DATA_TYPE_USMALLINT:
wafwerar's avatar
wafwerar 已提交
335
      taosFprintfFile(pFile, "%u", *((uint16_t *)val));
S
Shengliang Guan 已提交
336
      break;
337
    case TSDB_DATA_TYPE_INT:
wafwerar's avatar
wafwerar 已提交
338
      taosFprintfFile(pFile, "%d", *((int32_t *)val));
339
      break;
S
Shengliang Guan 已提交
340
    case TSDB_DATA_TYPE_UINT:
wafwerar's avatar
wafwerar 已提交
341
      taosFprintfFile(pFile, "%u", *((uint32_t *)val));
S
Shengliang Guan 已提交
342
      break;
343
    case TSDB_DATA_TYPE_BIGINT:
wafwerar's avatar
wafwerar 已提交
344
      taosFprintfFile(pFile, "%" PRId64, *((int64_t *)val));
345
      break;
S
Shengliang Guan 已提交
346
    case TSDB_DATA_TYPE_UBIGINT:
wafwerar's avatar
wafwerar 已提交
347
      taosFprintfFile(pFile, "%" PRIu64, *((uint64_t *)val));
S
Shengliang Guan 已提交
348
      break;
349
    case TSDB_DATA_TYPE_FLOAT:
350 351 352 353 354
      if (tsEnableScience) {
        taosFprintfFile(pFile, "%e", GET_FLOAT_VAL(val));
      } else {
        taosFprintfFile(pFile, "%.5f", GET_FLOAT_VAL(val));
      }
355 356
      break;
    case TSDB_DATA_TYPE_DOUBLE:
357 358 359 360 361 362 363 364 365 366 367
      if (tsEnableScience) {
        snprintf(buf, TSDB_MAX_BYTES_PER_ROW, "%*.9e", 23, GET_DOUBLE_VAL(val));
        taosFprintfFile(pFile, "%s", buf);
      } else {
        n = snprintf(buf, TSDB_MAX_BYTES_PER_ROW, "%*.9f", length, GET_DOUBLE_VAL(val));
        if (n > TMAX(25, length)) {
          taosFprintfFile(pFile, "%*.15e", length, GET_DOUBLE_VAL(val));
        } else {
          taosFprintfFile(pFile, "%s", buf);
        }
      }
368 369 370
      break;
    case TSDB_DATA_TYPE_BINARY:
    case TSDB_DATA_TYPE_NCHAR:
wmmhello's avatar
wmmhello 已提交
371
    case TSDB_DATA_TYPE_JSON:
wafwerar's avatar
wafwerar 已提交
372 373 374
      {
        int32_t bufIndex = 0;
        for (int32_t i = 0; i < length; i++) {
wafwerar's avatar
wafwerar 已提交
375 376
          buf[bufIndex] = val[i];
          bufIndex++;
wafwerar's avatar
wafwerar 已提交
377 378 379 380
          if (val[i] == '\"') {
            buf[bufIndex] = val[i];
            bufIndex++;
          }
wafwerar's avatar
wafwerar 已提交
381
        }
wafwerar's avatar
wafwerar 已提交
382
        buf[bufIndex] = 0;
wafwerar's avatar
wafwerar 已提交
383
        
wafwerar's avatar
wafwerar 已提交
384
        taosFprintfFile(pFile, "%s%s%s", quotationStr, buf, quotationStr);
wafwerar's avatar
wafwerar 已提交
385
      }
386 387
      break;
    case TSDB_DATA_TYPE_TIMESTAMP:
388
      shellFormatTimestamp(buf, *(int64_t *)val, precision);
X
Xiaoyu Wang 已提交
389
      taosFprintfFile(pFile, "%s%s%s", quotationStr, buf, quotationStr);
390 391 392 393 394 395
      break;
    default:
      break;
  }
}

396
int32_t shellDumpResultToFile(const char *fname, TAOS_RES *tres) {
397 398 399 400 401
  char fullname[PATH_MAX] = {0};
  if (taosExpandDir(fname, fullname, PATH_MAX) != 0) {
    tstrncpy(fullname, fname, PATH_MAX);
  }

402
  TAOS_ROW row = taos_fetch_row(tres);
403 404 405 406
  if (row == NULL) {
    return 0;
  }

407
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_TRUNC | TD_FILE_STREAM);
408
  if (pFile == NULL) {
wafwerar's avatar
wafwerar 已提交
409
    fprintf(stderr, "failed to open file: %s\r\n", fullname);
410 411 412
    return -1;
  }

413
  TAOS_FIELD *fields = taos_fetch_fields(tres);
414 415
  int32_t     num_fields = taos_num_fields(tres);
  int32_t     precision = taos_result_precision(tres);
416

417
  for (int32_t col = 0; col < num_fields; col++) {
418
    if (col > 0) {
419
      taosFprintfFile(pFile, ",");
420
    }
421
    taosFprintfFile(pFile, "%s", fields[col].name);
422
  }
wafwerar's avatar
wafwerar 已提交
423
  taosFprintfFile(pFile, "\r\n");
424

425
  int32_t numOfRows = 0;
426
  do {
S
Shengliang Guan 已提交
427
    int32_t *length = taos_fetch_lengths(tres);
428
    for (int32_t i = 0; i < num_fields; i++) {
429
      if (i > 0) {
X
Xiaoyu Wang 已提交
430
        taosFprintfFile(pFile, ",");
431
      }
wafwerar's avatar
wafwerar 已提交
432
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision);
H
hzcheng 已提交
433
    }
wafwerar's avatar
wafwerar 已提交
434
    taosFprintfFile(pFile, "\r\n");
435 436

    numOfRows++;
437
    row = taos_fetch_row(tres);
S
Shengliang Guan 已提交
438
  } while (row != NULL);
439

440
  taosCloseFile(&pFile);
441

442 443 444
  return numOfRows;
}

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

449
  while (pos < length) {
wafwerar's avatar
wafwerar 已提交
450
    TdWchar wc;
451
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
wmmhello's avatar
wmmhello 已提交
452
    if (bytes <= 0) {
453 454
      break;
    }
wmmhello's avatar
wmmhello 已提交
455 456

    if (pos + bytes > length) {
457 458
      break;
    }
wmmhello's avatar
wmmhello 已提交
459
    int w = 0;
X
Xiaoyu Wang 已提交
460
    if (*(str + pos) == '\t' || *(str + pos) == '\n' || *(str + pos) == '\r') {
wmmhello's avatar
wmmhello 已提交
461
      w = bytes;
X
Xiaoyu Wang 已提交
462
    } else {
wmmhello's avatar
wmmhello 已提交
463 464 465 466
      w = taosWcharWidth(wc);
    }
    pos += bytes;

467 468 469 470 471 472 473 474 475 476 477 478 479 480
    if (w <= 0) {
      continue;
    }

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

    totalCols += w;
    if (totalCols > width) {
      break;
    }
    if (totalCols <= (width - 3)) {
481 482
      printf("%lc", wc);
      cols += w;
483 484 485
    } else {
      tail[tailLen] = wc;
      tailLen++;
486 487 488
    }
  }

489 490
  if (totalCols > width) {
    // width could be 1 or 2, so printf("...") cannot be used
491
    for (int32_t i = 0; i < 3; i++) {
492 493 494 495 496 497 498
      if (cols >= width) {
        break;
      }
      putchar('.');
      ++cols;
    }
  } else {
499
    for (int32_t i = 0; i < tailLen; i++) {
500 501 502 503 504
      printf("%lc", tail[i]);
    }
    cols = totalCols;
  }

505 506 507 508 509
  for (; cols < width; cols++) {
    putchar(' ');
  }
}

510
void shellPrintField(const char *val, TAOS_FIELD *field, int32_t width, int32_t length, int32_t precision) {
511
  if (val == NULL) {
512
    int32_t w = width;
513 514
    if (field->type < TSDB_DATA_TYPE_TINYINT || field->type > TSDB_DATA_TYPE_DOUBLE) {
      w = 0;
H
hzcheng 已提交
515
    }
516 517 518 519 520 521
    w = printf("%*s", w, TSDB_DATA_NULL_STR);
    for (; w < width; w++) {
      putchar(' ');
    }
    return;
  }
H
hzcheng 已提交
522

523
  int  n;
524 525 526
  char buf[TSDB_MAX_BYTES_PER_ROW];
  switch (field->type) {
    case TSDB_DATA_TYPE_BOOL:
S
TD-1530  
Shengliang Guan 已提交
527
      printf("%*s", width, ((((int32_t)(*((char *)val))) == 1) ? "true" : "false"));
528 529
      break;
    case TSDB_DATA_TYPE_TINYINT:
S
TD-1530  
Shengliang Guan 已提交
530
      printf("%*d", width, *((int8_t *)val));
531
      break;
532 533 534
    case TSDB_DATA_TYPE_UTINYINT:
      printf("%*u", width, *((uint8_t *)val));
      break;
535
    case TSDB_DATA_TYPE_SMALLINT:
S
TD-1530  
Shengliang Guan 已提交
536
      printf("%*d", width, *((int16_t *)val));
537
      break;
538 539 540
    case TSDB_DATA_TYPE_USMALLINT:
      printf("%*u", width, *((uint16_t *)val));
      break;
541
    case TSDB_DATA_TYPE_INT:
S
TD-1530  
Shengliang Guan 已提交
542
      printf("%*d", width, *((int32_t *)val));
543
      break;
544 545 546
    case TSDB_DATA_TYPE_UINT:
      printf("%*u", width, *((uint32_t *)val));
      break;
547 548 549
    case TSDB_DATA_TYPE_BIGINT:
      printf("%*" PRId64, width, *((int64_t *)val));
      break;
550 551 552
    case TSDB_DATA_TYPE_UBIGINT:
      printf("%*" PRIu64, width, *((uint64_t *)val));
      break;
553
    case TSDB_DATA_TYPE_FLOAT:
554 555 556
      if (tsEnableScience) {
        printf("%*e", width, GET_FLOAT_VAL(val));
      } else {
A
Alex Duan 已提交
557
        printf("%*.5f", width, GET_FLOAT_VAL(val));
558
      }
559 560
      break;
    case TSDB_DATA_TYPE_DOUBLE:
561 562 563 564
      if (tsEnableScience) {
        snprintf(buf, TSDB_MAX_BYTES_PER_ROW, "%.9e", GET_DOUBLE_VAL(val));
        printf("%*s", width, buf);
      } else {
A
Alex Duan 已提交
565 566 567
        n = snprintf(buf, TSDB_MAX_BYTES_PER_ROW, "%*.9f", width, GET_DOUBLE_VAL(val));
        if (n > TMAX(25, width)) {
            printf("%*.15e", width, GET_DOUBLE_VAL(val));
568 569 570 571
        } else {
            printf("%s", buf);
        }
      }
572 573 574
      break;
    case TSDB_DATA_TYPE_BINARY:
    case TSDB_DATA_TYPE_NCHAR:
wmmhello's avatar
wmmhello 已提交
575
    case TSDB_DATA_TYPE_JSON:
B
Bomin Zhang 已提交
576
      shellPrintNChar(val, length, width);
577 578
      break;
    case TSDB_DATA_TYPE_TIMESTAMP:
579
      shellFormatTimestamp(buf, *(int64_t *)val, precision);
580 581 582 583
      printf("%s", buf);
      break;
    default:
      break;
H
hzcheng 已提交
584
  }
585
}
H
hzcheng 已提交
586

587 588 589
// show whole result for this query return true, like limit or describe
bool shellIsShowWhole(const char *sql) {
  // limit
wafwerar's avatar
wafwerar 已提交
590
  if (taosStrCaseStr(sql, " limit ") != NULL) {
S
Shengliang Guan 已提交
591 592
    return true;
  }
593 594 595 596
  // describe
  if (taosStrCaseStr(sql, "describe ") != NULL) {
    return true;
  }
597
  // show
598 599 600
  if (taosStrCaseStr(sql, "show ") != NULL) {
    return true;
  }
S
Shengliang Guan 已提交
601 602 603 604

  return false;
}

D
dapan1121 已提交
605
bool shellIsShowQuery(const char *sql) {
X
Xiaoyu Wang 已提交
606
  // todo refactor
D
dapan1121 已提交
607 608 609 610 611 612 613
  if (taosStrCaseStr(sql, "show ") != NULL) {
    return true;
  }

  return false;
}

S
Shengliang Guan 已提交
614
int32_t shellVerticalPrintResult(TAOS_RES *tres, const char *sql) {
H
Haojun Liao 已提交
615
  TAOS_ROW row = taos_fetch_row(tres);
616 617 618 619
  if (row == NULL) {
    return 0;
  }

620
  int32_t     num_fields = taos_num_fields(tres);
H
Haojun Liao 已提交
621
  TAOS_FIELD *fields = taos_fetch_fields(tres);
622
  int32_t     precision = taos_result_precision(tres);
623

624 625 626
  int32_t maxColNameLen = 0;
  for (int32_t col = 0; col < num_fields; col++) {
    int32_t len = (int32_t)strlen(fields[col].name);
627 628 629 630 631
    if (len > maxColNameLen) {
      maxColNameLen = len;
    }
  }

D
fix bug  
dapan1121 已提交
632 633
  uint64_t resShowMaxNum = UINT64_MAX;

634
  if (shell.args.commands == NULL && shell.args.file[0] == 0 && !shellIsShowWhole(sql)) {
635
    resShowMaxNum = SHELL_DEFAULT_RES_SHOW_NUM;
D
fix bug  
dapan1121 已提交
636 637
  }

638 639
  int32_t numOfRows = 0;
  int32_t showMore = 1;
640
  do {
D
fix bug  
dapan1121 已提交
641
    if (numOfRows < resShowMaxNum) {
wafwerar's avatar
wafwerar 已提交
642
      printf("*************************** %d.row ***************************\r\n", numOfRows + 1);
D
fix bug  
dapan1121 已提交
643

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

646
      for (int32_t i = 0; i < num_fields; i++) {
S
Shengliang Guan 已提交
647
        TAOS_FIELD *field = fields + i;
648

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

652
        shellPrintField((const char *)row[i], field, 0, length[i], precision);
wafwerar's avatar
wafwerar 已提交
653
        putchar('\r');
D
fix bug  
dapan1121 已提交
654 655
        putchar('\n');
      }
D
fix bug  
dapan1121 已提交
656
    } else if (showMore) {
wafwerar's avatar
wafwerar 已提交
657 658 659 660 661 662 663
      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 已提交
664
      showMore = 0;
665 666 667
    }

    numOfRows++;
H
Haojun Liao 已提交
668
    row = taos_fetch_row(tres);
S
Shengliang Guan 已提交
669
  } while (row != NULL);
670 671 672 673

  return numOfRows;
}

674 675
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
  int32_t width = (int32_t)strlen(field->name);
676 677

  switch (field->type) {
D
dapan1121 已提交
678 679
    case TSDB_DATA_TYPE_NULL:
      return TMAX(4, width);  // null
680
    case TSDB_DATA_TYPE_BOOL:
dengyihao's avatar
dengyihao 已提交
681
      return TMAX(5, width);  // 'false'
682 683

    case TSDB_DATA_TYPE_TINYINT:
684
    case TSDB_DATA_TYPE_UTINYINT:
dengyihao's avatar
dengyihao 已提交
685
      return TMAX(4, width);  // '-127'
686 687

    case TSDB_DATA_TYPE_SMALLINT:
688
    case TSDB_DATA_TYPE_USMALLINT:
dengyihao's avatar
dengyihao 已提交
689
      return TMAX(6, width);  // '-32767'
690 691

    case TSDB_DATA_TYPE_INT:
692
    case TSDB_DATA_TYPE_UINT:
dengyihao's avatar
dengyihao 已提交
693
      return TMAX(11, width);  // '-2147483648'
694 695

    case TSDB_DATA_TYPE_BIGINT:
696
    case TSDB_DATA_TYPE_UBIGINT:
dengyihao's avatar
dengyihao 已提交
697
      return TMAX(21, width);  // '-9223372036854775807'
698 699

    case TSDB_DATA_TYPE_FLOAT:
dengyihao's avatar
dengyihao 已提交
700
      return TMAX(20, width);
701 702

    case TSDB_DATA_TYPE_DOUBLE:
dengyihao's avatar
dengyihao 已提交
703
      return TMAX(25, width);
704 705

    case TSDB_DATA_TYPE_BINARY:
706 707
      if (field->bytes > shell.args.displayWidth) {
        return TMAX(shell.args.displayWidth, width);
708
      } else {
dengyihao's avatar
dengyihao 已提交
709
        return TMAX(field->bytes, width);
710 711
      }

wmmhello's avatar
wmmhello 已提交
712 713
    case TSDB_DATA_TYPE_NCHAR:
    case TSDB_DATA_TYPE_JSON: {
714
      int16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
715 716
      if (bytes > shell.args.displayWidth) {
        return TMAX(shell.args.displayWidth, width);
717
      } else {
dengyihao's avatar
dengyihao 已提交
718
        return TMAX(bytes, width);
719 720 721
      }
    }

722
    case TSDB_DATA_TYPE_TIMESTAMP:
723
      if (shell.args.is_raw_time) {
dengyihao's avatar
dengyihao 已提交
724
        return TMAX(14, width);
S
Shengliang Guan 已提交
725 726
      }
      if (precision == TSDB_TIME_PRECISION_NANO) {
dengyihao's avatar
dengyihao 已提交
727
        return TMAX(29, width);
728
      } else if (precision == TSDB_TIME_PRECISION_MICRO) {
dengyihao's avatar
dengyihao 已提交
729
        return TMAX(26, width);  // '2020-01-01 00:00:00.000000'
730
      } else {
dengyihao's avatar
dengyihao 已提交
731
        return TMAX(23, width);  // '2020-01-01 00:00:00.000'
S
slguan 已提交
732
      }
H
hzcheng 已提交
733

734
    default:
X
xinsheng Ren 已提交
735
      ASSERT(false);
H
hzcheng 已提交
736 737
  }

738 739
  return 0;
}
H
hzcheng 已提交
740

741 742 743
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 已提交
744
    TAOS_FIELD *field = fields + col;
745 746
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
    int32_t     left = padding / 2;
747 748 749 750
    printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
    rowWidth += width[col] + 3;
  }

wafwerar's avatar
wafwerar 已提交
751
  putchar('\r');
752
  putchar('\n');
753
  for (int32_t i = 0; i < rowWidth; i++) {
754 755
    putchar('=');
  }
wafwerar's avatar
wafwerar 已提交
756
  putchar('\r');
757 758 759
  putchar('\n');
}

S
Shengliang Guan 已提交
760
int32_t shellHorizontalPrintResult(TAOS_RES *tres, const char *sql) {
H
Haojun Liao 已提交
761
  TAOS_ROW row = taos_fetch_row(tres);
762 763 764 765
  if (row == NULL) {
    return 0;
  }

766
  int32_t     num_fields = taos_num_fields(tres);
H
Haojun Liao 已提交
767
  TAOS_FIELD *fields = taos_fetch_fields(tres);
768
  int32_t     precision = taos_result_precision(tres);
769

770 771 772
  int32_t width[TSDB_MAX_COLUMNS];
  for (int32_t col = 0; col < num_fields; col++) {
    width[col] = shellCalcColWidth(fields + col, precision);
773 774
  }

775
  shellPrintHeader(fields, width, num_fields);
776

D
fix bug  
dapan1121 已提交
777 778
  uint64_t resShowMaxNum = UINT64_MAX;

779
  if (shell.args.commands == NULL && shell.args.file[0] == 0 && !shellIsShowWhole(sql)) {
780
    resShowMaxNum = SHELL_DEFAULT_RES_SHOW_NUM;
D
fix bug  
dapan1121 已提交
781 782
  }

783 784
  int32_t numOfRows = 0;
  int32_t showMore = 1;
785

786
  do {
S
Shengliang Guan 已提交
787
    int32_t *length = taos_fetch_lengths(tres);
D
fix bug  
dapan1121 已提交
788
    if (numOfRows < resShowMaxNum) {
789
      for (int32_t i = 0; i < num_fields; i++) {
D
fix bug  
dapan1121 已提交
790
        putchar(' ');
791
        shellPrintField((const char *)row[i], fields + i, width[i], length[i], precision);
D
fix bug  
dapan1121 已提交
792 793 794
        putchar(' ');
        putchar('|');
      }
wafwerar's avatar
wafwerar 已提交
795
      putchar('\r');
D
fix bug  
dapan1121 已提交
796
      putchar('\n');
D
fix bug  
dapan1121 已提交
797
    } else if (showMore) {
wafwerar's avatar
wafwerar 已提交
798 799
      printf("\r\n");
      printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
wafwerar's avatar
wafwerar 已提交
800 801 802 803 804 805
      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 已提交
806 807 808
      printf("\r\n");
      printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
      printf("\r\n");
S
Shengliang Guan 已提交
809
      showMore = 0;
810
    }
811

812
    numOfRows++;
H
Haojun Liao 已提交
813
    row = taos_fetch_row(tres);
S
Shengliang Guan 已提交
814
  } while (row != NULL);
815 816 817 818

  return numOfRows;
}

S
Shengliang Guan 已提交
819
int32_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
820
  int32_t numOfRows = 0;
H
hzcheng 已提交
821
  if (fname != NULL) {
822
    numOfRows = shellDumpResultToFile(fname, tres);
S
Shengliang Guan 已提交
823
  } else if (vertical) {
S
Shengliang Guan 已提交
824
    numOfRows = shellVerticalPrintResult(tres, sql);
825
  } else {
S
Shengliang Guan 已提交
826
    numOfRows = shellHorizontalPrintResult(tres, sql);
H
hzcheng 已提交
827 828
  }

H
Haojun Liao 已提交
829
  *error_no = taos_errno(tres);
H
hzcheng 已提交
830 831 832
  return numOfRows;
}

833
void shellReadHistory() {
834 835 836
  SShellHistory *pHistory = &shell.history;
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_READ | TD_FILE_STREAM);
  if (pFile == NULL) return;
H
hzcheng 已提交
837

wafwerar's avatar
wafwerar 已提交
838
  char    *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
839
  int32_t read_size = 0;
wafwerar's avatar
wafwerar 已提交
840
  while ((read_size = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) != -1) {
H
hzcheng 已提交
841
    line[read_size - 1] = '\0';
842
    taosMemoryFree(pHistory->hist[pHistory->hend]);
843
    pHistory->hist[pHistory->hend] = taosStrdup(line);
H
hzcheng 已提交
844

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

847 848
    if (pHistory->hend == pHistory->hstart) {
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
H
hzcheng 已提交
849 850 851
    }
  }

wafwerar's avatar
wafwerar 已提交
852
  taosMemoryFreeClear(line);
853
  taosCloseFile(&pFile);
854 855 856 857 858 859 860 861 862 863 864 865 866
  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]);
867 868

    /* coverity[+retval] */
869 870 871
    taosFsyncFile(pFile);
    taosCloseFile(&pFile);
  }
wafwerar's avatar
wafwerar 已提交
872
  pHistory->hstart = pHistory->hend;
H
hzcheng 已提交
873 874
}

875
void shellWriteHistory() {
876
  SShellHistory *pHistory = &shell.history;
877
  if (pHistory->hend == pHistory->hstart) return;
S
Shengliang Guan 已提交
878
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_APPEND);
879
  if (pFile == NULL) return;
H
hzcheng 已提交
880

881 882 883
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
    if (pHistory->hist[i] != NULL) {
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
884 885
      taosMemoryFree(pHistory->hist[i]);
      pHistory->hist[i] = NULL;
H
hzcheng 已提交
886
    }
887
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
H
hzcheng 已提交
888
  }
889
  taosCloseFile(&pFile);
H
hzcheng 已提交
890 891
}

892 893 894 895 896 897 898 899 900 901
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;
    }
  }
}

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

908 909
bool shellIsCommentLine(char *line) {
  if (line == NULL) return true;
910
  return shellRegexMatch(line, "^\\s*#.*", REG_EXTENDED);
H
hzcheng 已提交
911 912
}

913 914 915 916
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;
917
  char    fullname[PATH_MAX] = {0};
918
  char    sourceFileCommand[PATH_MAX + 8] = {0};
H
hzcheng 已提交
919

920 921
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
    tstrncpy(fullname, file, PATH_MAX);
H
hzcheng 已提交
922 923
  }

924 925 926
  sprintf(sourceFileCommand, "source %s;",fullname);
  shellRecordCommandToHistory(sourceFileCommand);

927
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_READ | TD_FILE_STREAM);
928
  if (pFile == NULL) {
wafwerar's avatar
wafwerar 已提交
929
    fprintf(stderr, "failed to open file %s\r\n", fullname);
wafwerar's avatar
wafwerar 已提交
930
    taosMemoryFree(cmd);
H
hzcheng 已提交
931 932 933
    return;
  }

wafwerar's avatar
wafwerar 已提交
934 935
  char   *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
  while ((read_len = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) != -1) {
H
Haojun Liao 已提交
936
    if (read_len >= TSDB_MAX_ALLOWED_SQL_LEN) continue;
H
hzcheng 已提交
937 938
    line[--read_len] = '\0';

939
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
H
hzcheng 已提交
940 941 942 943 944 945 946 947 948 949
      continue;
    }

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

950 951 952 953
    if (line[read_len - 1] == '\r') {
      line[read_len - 1] = ' ';
    }

H
hzcheng 已提交
954
    memcpy(cmd + cmd_len, line, read_len);
wafwerar's avatar
wafwerar 已提交
955
    printf("%s%s\r\n", shell.info.promptHeader, cmd);
956
    shellRunCommand(cmd, false);
H
Haojun Liao 已提交
957
    memset(cmd, 0, TSDB_MAX_ALLOWED_SQL_LEN);
H
hzcheng 已提交
958 959 960
    cmd_len = 0;
  }

wafwerar's avatar
wafwerar 已提交
961
  taosMemoryFree(cmd);
wafwerar's avatar
wafwerar 已提交
962
  taosMemoryFreeClear(line);
963
  taosCloseFile(&pFile);
H
hzcheng 已提交
964
}
S
slguan 已提交
965

966
void shellGetGrantInfo() {
967 968
  char sinfo[1024] = {0};
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
wafwerar's avatar
wafwerar 已提交
969
  strtok(sinfo, "\r\n");
970

S
slguan 已提交
971 972
  char sql[] = "show grants";

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

975
  int32_t code = taos_errno(tres);
S
slguan 已提交
976
  if (code != TSDB_CODE_SUCCESS) {
977
    if (code != TSDB_CODE_OPS_NOT_SUPPORT && code != TSDB_CODE_MND_NO_RIGHTS && code != TSDB_CODE_PAR_PERMISSION_DENIED) {
wafwerar's avatar
wafwerar 已提交
978
      fprintf(stderr, "Failed to check Server Edition, Reason:0x%04x:%s\r\n\r\n", code, taos_errstr(tres));
S
slguan 已提交
979
    }
S
slguan 已提交
980 981 982
    return;
  }

983
  int32_t num_fields = taos_field_count(tres);
S
slguan 已提交
984
  if (num_fields == 0) {
wafwerar's avatar
wafwerar 已提交
985
    fprintf(stderr, "\r\nInvalid grant information.\r\n");
S
slguan 已提交
986 987
    exit(0);
  } else {
988
    if (tres == NULL) {
wafwerar's avatar
wafwerar 已提交
989
      fprintf(stderr, "\r\nGrant information is null.\r\n");
S
slguan 已提交
990 991 992
      exit(0);
    }

993
    TAOS_FIELD *fields = taos_fetch_fields(tres);
994
    TAOS_ROW    row = taos_fetch_row(tres);
S
slguan 已提交
995
    if (row == NULL) {
wafwerar's avatar
wafwerar 已提交
996
      fprintf(stderr, "\r\nFailed to get grant information from server. Abort.\r\n");
S
slguan 已提交
997 998 999
      exit(0);
    }

S
slguan 已提交
1000
    char serverVersion[32] = {0};
S
slguan 已提交
1001 1002 1003
    char expiretime[32] = {0};
    char expired[32] = {0};

S
slguan 已提交
1004
    memcpy(serverVersion, row[0], fields[0].bytes);
S
slguan 已提交
1005 1006 1007
    memcpy(expiretime, row[1], fields[1].bytes);
    memcpy(expired, row[2], fields[2].bytes);

1008
    if (strcmp(serverVersion, "community") == 0) {
wafwerar's avatar
wafwerar 已提交
1009
      fprintf(stdout, "Server is Community Edition.\r\n");
1010
    } else if (strcmp(expiretime, "unlimited") == 0) {
wafwerar's avatar
wafwerar 已提交
1011
      fprintf(stdout, "Server is Enterprise %s Edition, %s and will never expire.\r\n", serverVersion, sinfo);
S
slguan 已提交
1012
    } else {
wafwerar's avatar
wafwerar 已提交
1013
      fprintf(stdout, "Server is Enterprise %s Edition, %s and will expire at %s.\r\n", serverVersion, sinfo, expiretime);
S
slguan 已提交
1014 1015
    }

1016
    taos_free_result(tres);
S
slguan 已提交
1017 1018
  }

wafwerar's avatar
wafwerar 已提交
1019
  fprintf(stdout, "\r\n");
1020 1021
}

1022 1023 1024 1025
#ifdef WINDOWS
BOOL shellQueryInterruptHandler(DWORD fdwCtrlType) {
  tsem_post(&shell.cancelSem);
  return TRUE;
1026
}
1027 1028 1029
#else
void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) { tsem_post(&shell.cancelSem); }
#endif
1030

1031 1032 1033 1034 1035
void shellCleanup(void *arg) { taosResetTerminalMode(); }

void *shellCancelHandler(void *arg) {
  setThreadName("shellCancelHandler");
  while (1) {
1036 1037 1038 1039
    if (shell.exit == true) {
      break;
    }

1040 1041 1042 1043
    if (tsem_wait(&shell.cancelSem) != 0) {
      taosMsleep(10);
      continue;
    }
Y
Yang Zhao 已提交
1044 1045

#ifdef WEBSOCKET
D
dapan1121 已提交
1046 1047 1048
    if (shell.args.restful || shell.args.cloud) {
      shell.stop_query = true;
    } else {
Y
Yang Zhao 已提交
1049
#endif
D
dapan1121 已提交
1050 1051 1052
      if (shell.conn) {
        taos_kill_query(shell.conn);
      }
Y
Yang Zhao 已提交
1053
#ifdef WEBSOCKET
D
dapan1121 已提交
1054
    }
1055
#endif
1056 1057 1058
  #ifdef WINDOWS
    printf("\n%s", shell.info.promptHeader);
  #endif
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
  }

  return NULL;
}

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

  do {
1070 1071 1072
    char *command = taosMemoryMalloc(SHELL_MAX_COMMAND_SIZE);
    if (command == NULL) {
      printf("failed to malloc command\r\n");
1073 1074 1075
      break;
    }

1076 1077 1078 1079 1080 1081 1082
    do {
      memset(command, 0, SHELL_MAX_COMMAND_SIZE);
      taosSetTerminalMode();

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

1084 1085 1086 1087 1088 1089 1090
      taosResetTerminalMode();
    } while (shellRunCommand(command, true) == 0);

    taosMemoryFreeClear(command);
    shellWriteHistory();
    shellExit();
  } while (0);
1091

1092 1093 1094 1095 1096
  taosThreadCleanupPop(1);
  return NULL;
}

int32_t shellExecute() {
sangshuduo's avatar
sangshuduo 已提交
1097 1098
  printf(shell.info.clientVersion, shell.info.cusName,
         taos_get_client_info(), shell.info.cusName);
1099 1100 1101
  fflush(stdout);

  SShellArgs *pArgs = &shell.args;
Y
Yang Zhao 已提交
1102 1103
#ifdef WEBSOCKET
  if (shell.args.restful || shell.args.cloud) {
D
dapan1121 已提交
1104 1105 1106
    if (shell_conn_ws_server(1)) {
      return -1;
    }
1107
  } else {
Y
Yang Zhao 已提交
1108
#endif
D
dapan1121 已提交
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
    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;
    }
Y
Yang Zhao 已提交
1119
#ifdef WEBSOCKET
1120
  }
Y
Yang Zhao 已提交
1121
#endif
1122

1123 1124
  bool runOnce = pArgs->commands != NULL || pArgs->file[0] != 0;
  shellSetConn(shell.conn, runOnce);
1125 1126
  shellReadHistory();

1127
  if (runOnce) {
1128
    if (pArgs->commands != NULL) {
wafwerar's avatar
wafwerar 已提交
1129
      printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
1130
      char *cmd = taosStrdup(pArgs->commands);
1131
      shellRunCommand(cmd, true);
1132 1133 1134
      taosMemoryFree(cmd);
    }

1135
    if (pArgs->file[0] != 0) {
1136 1137
      shellSourceFile(pArgs->file);
    }
Y
Yang Zhao 已提交
1138
#ifdef WEBSOCKET
D
dapan1121 已提交
1139 1140 1141
    if (shell.args.restful || shell.args.cloud) {
      ws_close(shell.ws_conn);
    } else {
1142
#endif
D
dapan1121 已提交
1143
      taos_close(shell.conn);
Y
Yang Zhao 已提交
1144
#ifdef WEBSOCKET
D
dapan1121 已提交
1145
    }
Y
Yang Zhao 已提交
1146
#endif
1147 1148

    shellWriteHistory();
1149
    shellCleanupHistory();
1150 1151 1152 1153
    return 0;
  }

  if (tsem_init(&shell.cancelSem, 0, 0) != 0) {
sangshuduo's avatar
sangshuduo 已提交
1154
    printf("failed to create cancel semaphore\r\n");
1155 1156 1157 1158 1159 1160 1161 1162
    return -1;
  }

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

  taosSetSignal(SIGTERM, shellQueryInterruptHandler);
  taosSetSignal(SIGHUP, shellQueryInterruptHandler);
1163
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
D
dapan1121 已提交
1164
  
Y
Yang Zhao 已提交
1165 1166 1167
#ifdef WEBSOCKET
  if (!shell.args.restful && !shell.args.cloud) {
#endif
1168
#ifndef WINDOWS
D
dapan1121 已提交
1169
    printfIntroduction();
1170
#endif  
D
dapan1121 已提交
1171
    shellGetGrantInfo();
Y
Yang Zhao 已提交
1172 1173 1174
#ifdef WEBSOCKET
  }
#endif
1175
  while (1) {
Y
Yang Zhao 已提交
1176
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, NULL);
1177
    taosThreadJoin(shell.pid, NULL);
1178
    taosThreadClear(&shell.pid);
1179 1180 1181 1182
    if (shell.exit) {
      tsem_post(&shell.cancelSem);
      break;
    }
1183
  }
1184
  taosThreadJoin(spid, NULL);
1185

1186
  shellCleanupHistory();
A
Alex Duan 已提交
1187 1188 1189
  taos_kill_query(shell.conn);
  taos_close(shell.conn);

1190
  return 0;
S
slguan 已提交
1191
}