shellEngine.c 28.0 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/>.
 */

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

22 23 24 25 26 27 28 29 30 31
static bool    shellIsEmptyCommand(const char *cmd);
static int32_t shellRunSingleCommand(char *command);
static int32_t shellRunCommand(char *command);
static void    shellRunSingleCommandImp(char *command);
static char   *shellFormatTimestamp(char *buf, int64_t val, int32_t precision);
static void    shellDumpFieldToFile(TdFilePtr pFile, const char *val, TAOS_FIELD *field, int32_t length,
                                    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);
static void    shellPrintField(const char *val, TAOS_FIELD *field, int32_t width, int32_t length, int32_t precision);
S
Shengliang Guan 已提交
32
static int32_t shellVerticalPrintResult(TAOS_RES *tres, const char *sql);
33 34
static int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision);
static void    shellPrintHeader(TAOS_FIELD *fields, int32_t *width, int32_t num_fields);
S
Shengliang Guan 已提交
35 36
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);
37 38 39 40 41 42 43 44 45 46 47 48
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();
static void    shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context);
static void    shellCleanup(void *arg);
static void   *shellCancelHandler(void *arg);
static void   *shellThreadLoop(void *arg);

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

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

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

67
  if (shellRegexMatch(command, "^[\t ]*clear[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
H
hzcheng 已提交
68
    system("clear");
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
  }
96

97
  shellRunSingleCommandImp(command);
98
  return 0;
H
hzcheng 已提交
99 100
}

101 102
int32_t shellRunCommand(char *command) {
  if (shellIsEmptyCommand(command)) {
103 104 105
    return 0;
  }

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

115 116 117
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
    if (pHistory->hend == pHistory->hstart) {
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
118 119 120
    }
  }

wmmhello's avatar
wmmhello 已提交
121
  char quote = 0, *cmd = command;
122
  for (char c = *command++; c != 0; c = *command++) {
wmmhello's avatar
wmmhello 已提交
123
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
S
Shengliang Guan 已提交
124
      command++;
125 126
      continue;
    }
127

128 129
    if (quote == c) {
      quote = 0;
wmmhello's avatar
wmmhello 已提交
130
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
131
      quote = c;
wmmhello's avatar
wmmhello 已提交
132 133 134
    } else if (c == ';' && quote == 0) {
      c = *command;
      *command = 0;
135
      if (shellRunSingleCommand(cmd) < 0) {
136 137
        return -1;
      }
wmmhello's avatar
wmmhello 已提交
138 139
      *command = c;
      cmd = command;
140 141
    }
  }
142
  return shellRunSingleCommand(cmd);
D
dapan1121 已提交
143 144
}

145
void shellRunSingleCommandImp(char *command) {
146 147 148 149 150
  int64_t st, et;
  char   *sptr = NULL;
  char   *cptr = NULL;
  char   *fname = NULL;
  bool    printMode = false;
H
hzcheng 已提交
151 152 153 154 155 156 157

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

158
    fname = sptr + 2;
H
hzcheng 已提交
159 160 161
    *sptr = '\0';
  }

162 163 164 165 166 167 168 169 170 171
  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 已提交
172 173
  st = taosGetTimestampUs();

174
  TAOS_RES *pSql = taos_query(shell.conn, command);
H
Haojun Liao 已提交
175
  if (taos_errno(pSql)) {
176
    shellPrintError(pSql, st);
H
hzcheng 已提交
177 178 179
    return;
  }

180
  if (shellRegexMatch(command, "^\\s*use\\s+[a-zA-Z0-9_]+\\s*;\\s*$", REG_EXTENDED | REG_ICASE)) {
H
hzcheng 已提交
181 182
    fprintf(stdout, "Database changed.\n\n");
    fflush(stdout);
183

S
Shengliang Guan 已提交
184 185
    taos_free_result(pSql);

H
hzcheng 已提交
186 187 188
    return;
  }

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

S
Shengliang Guan 已提交
193
    int32_t numOfRows = shellDumpResult(pSql, fname, &error_no, printMode, command);
194
    if (numOfRows < 0) return;
H
hzcheng 已提交
195 196 197

    et = taosGetTimestampUs();
    if (error_no == 0) {
wafwerar's avatar
wafwerar 已提交
198
      printf("Query OK, %d rows affected (%.6fs)\n", numOfRows, (et - st) / 1E6);
H
hzcheng 已提交
199
    } else {
wafwerar's avatar
wafwerar 已提交
200
      printf("Query interrupted (%s), %d rows affected (%.6fs)\n", taos_errstr(pSql), numOfRows, (et - st) / 1E6);
H
hzcheng 已提交
201
    }
S
Shengliang Guan 已提交
202
    taos_free_result(pSql);
H
hzcheng 已提交
203
  } else {
204
    int32_t num_rows_affacted = taos_affected_rows(pSql);
205
    taos_free_result(pSql);
H
hzcheng 已提交
206
    et = taosGetTimestampUs();
wafwerar's avatar
wafwerar 已提交
207
    printf("Query OK, %d of %d rows affected (%.6fs)\n", num_rows_affacted, num_rows_affacted, (et - st) / 1E6);
H
hzcheng 已提交
208 209 210 211 212
  }

  printf("\n");
}

213 214
char *shellFormatTimestamp(char *buf, int64_t val, int32_t precision) {
  if (shell.args.is_raw_time) {
215 216 217
    sprintf(buf, "%" PRId64, val);
    return buf;
  }
H
hzcheng 已提交
218

S
Shengliang Guan 已提交
219
  time_t  tt;
D
fix bug  
dapan1121 已提交
220
  int32_t ms = 0;
221 222 223 224
  if (precision == TSDB_TIME_PRECISION_NANO) {
    tt = (time_t)(val / 1000000000);
    ms = val % 1000000000;
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
225
    tt = (time_t)(val / 1000000);
D
fix bug  
dapan1121 已提交
226
    ms = val % 1000000;
227 228
  } else {
    tt = (time_t)(val / 1000);
D
fix bug  
dapan1121 已提交
229
    ms = val % 1000;
230 231
  }

232 233
  /*
    comment out as it make testcases like select_with_tags.sim fail.
S
Shengliang Guan 已提交
234 235 236 237 238
    but in windows, this may cause the call to localtime crash if tt < 0,
    need to find a better solution.
    if (tt < 0) {
      tt = 0;
    }
239
  */
240

241 242 243
#ifdef WINDOWS
  if (tt < 0) tt = 0;
#endif
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
  struct tm *ptm = taosLocalTime(&tt, NULL);
S
Shengliang Guan 已提交
256
  size_t     pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", ptm);
257

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

  return buf;
}

269
void shellDumpFieldToFile(TdFilePtr pFile, const char *val, TAOS_FIELD *field, int32_t length, int32_t precision) {
270
  if (val == NULL) {
271
    taosFprintfFile(pFile, "%s", TSDB_DATA_NULL_STR);
272 273 274
    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:
279
      taosFprintfFile(pFile, "%d", ((((int32_t)(*((char *)val))) == 1) ? 1 : 0));
280 281
      break;
    case TSDB_DATA_TYPE_TINYINT:
282
      taosFprintfFile(pFile, "%d", *((int8_t *)val));
283
      break;
S
Shengliang Guan 已提交
284 285 286
    case TSDB_DATA_TYPE_UTINYINT:
      taosFprintfFile(pFile, "%u", *((uint8_t *)val));
      break;
287
    case TSDB_DATA_TYPE_SMALLINT:
288
      taosFprintfFile(pFile, "%d", *((int16_t *)val));
289
      break;
S
Shengliang Guan 已提交
290 291 292
    case TSDB_DATA_TYPE_USMALLINT:
      taosFprintfFile(pFile, "%u", *((uint16_t *)val));
      break;
293
    case TSDB_DATA_TYPE_INT:
294
      taosFprintfFile(pFile, "%d", *((int32_t *)val));
295
      break;
S
Shengliang Guan 已提交
296 297 298
    case TSDB_DATA_TYPE_UINT:
      taosFprintfFile(pFile, "%u", *((uint32_t *)val));
      break;
299
    case TSDB_DATA_TYPE_BIGINT:
300
      taosFprintfFile(pFile, "%" PRId64, *((int64_t *)val));
301
      break;
S
Shengliang Guan 已提交
302 303 304
    case TSDB_DATA_TYPE_UBIGINT:
      taosFprintfFile(pFile, "%" PRIu64, *((uint64_t *)val));
      break;
305
    case TSDB_DATA_TYPE_FLOAT:
306
      taosFprintfFile(pFile, "%.5f", GET_FLOAT_VAL(val));
307 308
      break;
    case TSDB_DATA_TYPE_DOUBLE:
S
Shengliang Guan 已提交
309
      n = snprintf(buf, TSDB_MAX_BYTES_PER_ROW, "%*.9f", length, GET_DOUBLE_VAL(val));
310
      if (n > TMAX(25, length)) {
S
Shengliang Guan 已提交
311 312 313 314
        taosFprintfFile(pFile, "%*.15e", length, GET_DOUBLE_VAL(val));
      } 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:
319 320
      memcpy(buf, val, length);
      buf[length] = 0;
321
      taosFprintfFile(pFile, "\'%s\'", buf);
322 323
      break;
    case TSDB_DATA_TYPE_TIMESTAMP:
324
      shellFormatTimestamp(buf, *(int64_t *)val, precision);
325
      taosFprintfFile(pFile, "'%s'", buf);
326 327 328 329 330 331
      break;
    default:
      break;
  }
}

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

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

343
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_TRUNC | TD_FILE_STREAM);
344
  if (pFile == NULL) {
345
    fprintf(stderr, "failed to open file: %s\n", fullname);
346 347 348
    return -1;
  }

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

353
  for (int32_t col = 0; col < num_fields; col++) {
354
    if (col > 0) {
355
      taosFprintfFile(pFile, ",");
356
    }
357
    taosFprintfFile(pFile, "%s", fields[col].name);
358
  }
359
  taosFprintfFile(pFile, "\n");
360

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

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

376
  taosCloseFile(&pFile);
377

378 379 380
  return numOfRows;
}

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

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

    if (pos + bytes > length) {
393 394
      break;
    }
wmmhello's avatar
wmmhello 已提交
395
    int w = 0;
396
#ifdef WINDOWS
wmmhello's avatar
wmmhello 已提交
397
    w = bytes;
398
#else
wmmhello's avatar
wmmhello 已提交
399 400 401 402 403
    if(*(str + pos) == '\t' || *(str + pos) == '\n' || *(str + pos) == '\r'){
      w = bytes;
    }else{
      w = taosWcharWidth(wc);
    }
404
#endif
wmmhello's avatar
wmmhello 已提交
405 406
    pos += bytes;

407 408 409 410 411 412 413 414 415 416 417 418 419 420
    if (w <= 0) {
      continue;
    }

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

    totalCols += w;
    if (totalCols > width) {
      break;
    }
    if (totalCols <= (width - 3)) {
421 422
      printf("%lc", wc);
      cols += w;
423 424 425
    } else {
      tail[tailLen] = wc;
      tailLen++;
426 427 428
    }
  }

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

445 446 447 448 449
  for (; cols < width; cols++) {
    putchar(' ');
  }
}

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

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

S
Shengliang Guan 已提交
518 519
bool shellIsLimitQuery(const char *sql) {
  //todo refactor
wafwerar's avatar
wafwerar 已提交
520
  if (taosStrCaseStr(sql, " limit ") != NULL) {
S
Shengliang Guan 已提交
521 522 523 524 525 526 527
    return true;
  }

  return false;
}

int32_t shellVerticalPrintResult(TAOS_RES *tres, const char *sql) {
H
Haojun Liao 已提交
528
  TAOS_ROW row = taos_fetch_row(tres);
529 530 531 532
  if (row == NULL) {
    return 0;
  }

533
  int32_t     num_fields = taos_num_fields(tres);
H
Haojun Liao 已提交
534
  TAOS_FIELD *fields = taos_fetch_fields(tres);
535
  int32_t     precision = taos_result_precision(tres);
536

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

D
fix bug  
dapan1121 已提交
545 546
  uint64_t resShowMaxNum = UINT64_MAX;

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

551 552
  int32_t numOfRows = 0;
  int32_t showMore = 1;
553
  do {
D
fix bug  
dapan1121 已提交
554
    if (numOfRows < resShowMaxNum) {
D
fix bug  
dapan1121 已提交
555 556
      printf("*************************** %d.row ***************************\n", numOfRows + 1);

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

559
      for (int32_t i = 0; i < num_fields; i++) {
S
Shengliang Guan 已提交
560
        TAOS_FIELD *field = fields + i;
561

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

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

    numOfRows++;
H
Haojun Liao 已提交
580
    row = taos_fetch_row(tres);
S
Shengliang Guan 已提交
581
  } while (row != NULL);
582 583 584 585

  return numOfRows;
}

586 587
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
  int32_t width = (int32_t)strlen(field->name);
588 589 590

  switch (field->type) {
    case TSDB_DATA_TYPE_BOOL:
dengyihao's avatar
dengyihao 已提交
591
      return TMAX(5, width);  // 'false'
592 593

    case TSDB_DATA_TYPE_TINYINT:
594
    case TSDB_DATA_TYPE_UTINYINT:
dengyihao's avatar
dengyihao 已提交
595
      return TMAX(4, width);  // '-127'
596 597

    case TSDB_DATA_TYPE_SMALLINT:
598
    case TSDB_DATA_TYPE_USMALLINT:
dengyihao's avatar
dengyihao 已提交
599
      return TMAX(6, width);  // '-32767'
600 601

    case TSDB_DATA_TYPE_INT:
602
    case TSDB_DATA_TYPE_UINT:
dengyihao's avatar
dengyihao 已提交
603
      return TMAX(11, width);  // '-2147483648'
604 605

    case TSDB_DATA_TYPE_BIGINT:
606
    case TSDB_DATA_TYPE_UBIGINT:
dengyihao's avatar
dengyihao 已提交
607
      return TMAX(21, width);  // '-9223372036854775807'
608 609

    case TSDB_DATA_TYPE_FLOAT:
dengyihao's avatar
dengyihao 已提交
610
      return TMAX(20, width);
611 612

    case TSDB_DATA_TYPE_DOUBLE:
dengyihao's avatar
dengyihao 已提交
613
      return TMAX(25, width);
614 615

    case TSDB_DATA_TYPE_BINARY:
616 617
      if (field->bytes > shell.args.displayWidth) {
        return TMAX(shell.args.displayWidth, width);
618
      } else {
dengyihao's avatar
dengyihao 已提交
619
        return TMAX(field->bytes, width);
620 621
      }

wmmhello's avatar
wmmhello 已提交
622 623
    case TSDB_DATA_TYPE_NCHAR:
    case TSDB_DATA_TYPE_JSON: {
624
      int16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
625 626
      if (bytes > shell.args.displayWidth) {
        return TMAX(shell.args.displayWidth, width);
627
      } else {
dengyihao's avatar
dengyihao 已提交
628
        return TMAX(bytes, width);
629 630 631
      }
    }

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

644 645
    default:
      assert(false);
H
hzcheng 已提交
646 647
  }

648 649
  return 0;
}
H
hzcheng 已提交
650

651 652 653
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 已提交
654
    TAOS_FIELD *field = fields + col;
655 656
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
    int32_t     left = padding / 2;
657 658 659 660 661
    printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
    rowWidth += width[col] + 3;
  }

  putchar('\n');
662
  for (int32_t i = 0; i < rowWidth; i++) {
663 664 665 666 667
    putchar('=');
  }
  putchar('\n');
}

S
Shengliang Guan 已提交
668
int32_t shellHorizontalPrintResult(TAOS_RES *tres, const char *sql) {
H
Haojun Liao 已提交
669
  TAOS_ROW row = taos_fetch_row(tres);
670 671 672 673
  if (row == NULL) {
    return 0;
  }

674
  int32_t     num_fields = taos_num_fields(tres);
H
Haojun Liao 已提交
675
  TAOS_FIELD *fields = taos_fetch_fields(tres);
676
  int32_t     precision = taos_result_precision(tres);
677

678 679 680
  int32_t width[TSDB_MAX_COLUMNS];
  for (int32_t col = 0; col < num_fields; col++) {
    width[col] = shellCalcColWidth(fields + col, precision);
681 682
  }

683
  shellPrintHeader(fields, width, num_fields);
684

D
fix bug  
dapan1121 已提交
685 686
  uint64_t resShowMaxNum = UINT64_MAX;

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

691 692
  int32_t numOfRows = 0;
  int32_t showMore = 1;
693

694
  do {
S
Shengliang Guan 已提交
695
    int32_t *length = taos_fetch_lengths(tres);
D
fix bug  
dapan1121 已提交
696
    if (numOfRows < resShowMaxNum) {
697
      for (int32_t i = 0; i < num_fields; i++) {
D
fix bug  
dapan1121 已提交
698
        putchar(' ');
699
        shellPrintField((const char *)row[i], fields + i, width[i], length[i], precision);
D
fix bug  
dapan1121 已提交
700 701 702 703
        putchar(' ');
        putchar('|');
      }
      putchar('\n');
D
fix bug  
dapan1121 已提交
704
    } else if (showMore) {
S
Shengliang Guan 已提交
705 706 707 708 709 710 711
      printf("\n");
      printf(" Notice: The result shows only the first %d rows.\n", SHELL_DEFAULT_RES_SHOW_NUM);
      printf("         You can use the `LIMIT` clause to get fewer result to show.\n");
      printf("           Or use '>>' to redirect the whole set of the result to a specified file.\n");
      printf("\n");
      printf("         You can use Ctrl+C to stop the underway fetching.\n");
      printf("\n");
S
Shengliang Guan 已提交
712
      showMore = 0;
713
    }
714

715
    numOfRows++;
H
Haojun Liao 已提交
716
    row = taos_fetch_row(tres);
S
Shengliang Guan 已提交
717
  } while (row != NULL);
718 719 720 721

  return numOfRows;
}

S
Shengliang Guan 已提交
722
int32_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
723
  int32_t numOfRows = 0;
H
hzcheng 已提交
724
  if (fname != NULL) {
725
    numOfRows = shellDumpResultToFile(fname, tres);
S
Shengliang Guan 已提交
726
  } else if (vertical) {
S
Shengliang Guan 已提交
727
    numOfRows = shellVerticalPrintResult(tres, sql);
728
  } else {
S
Shengliang Guan 已提交
729
    numOfRows = shellHorizontalPrintResult(tres, sql);
H
hzcheng 已提交
730 731
  }

H
Haojun Liao 已提交
732
  *error_no = taos_errno(tres);
H
hzcheng 已提交
733 734 735
  return numOfRows;
}

736
void shellReadHistory() {
737 738 739
  SShellHistory *pHistory = &shell.history;
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_READ | TD_FILE_STREAM);
  if (pFile == NULL) return;
H
hzcheng 已提交
740

741 742
  char   *line = NULL;
  int32_t read_size = 0;
743
  while ((read_size = taosGetLineFile(pFile, &line)) != -1) {
H
hzcheng 已提交
744
    line[read_size - 1] = '\0';
745
    taosMemoryFree(pHistory->hist[pHistory->hend]);
746
    pHistory->hist[pHistory->hend] = strdup(line);
H
hzcheng 已提交
747

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

750 751
    if (pHistory->hend == pHistory->hstart) {
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
H
hzcheng 已提交
752 753 754
    }
  }

S
Shengliang Guan 已提交
755
  if (line != NULL) taosMemoryFree(line);
756
  taosCloseFile(&pFile);
H
hzcheng 已提交
757 758
}

759
void shellWriteHistory() {
760
  SShellHistory *pHistory = &shell.history;
S
Shengliang Guan 已提交
761
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_APPEND);
762
  if (pFile == NULL) return;
H
hzcheng 已提交
763

764 765 766
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
    if (pHistory->hist[i] != NULL) {
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
767 768
      taosMemoryFree(pHistory->hist[i]);
      pHistory->hist[i] = NULL;
H
hzcheng 已提交
769
    }
770
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
H
hzcheng 已提交
771
  }
772
  taosFsyncFile(pFile);
773
  taosCloseFile(&pFile);
H
hzcheng 已提交
774 775
}

776 777 778 779 780 781 782 783 784 785
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;
    }
  }
}

786
void shellPrintError(TAOS_RES *tres, int64_t st) {
S
TD-1793  
Shengliang Guan 已提交
787 788
  int64_t et = taosGetTimestampUs();
  fprintf(stderr, "\nDB error: %s (%.6fs)\n", taos_errstr(tres), (et - st) / 1E6);
H
Haojun Liao 已提交
789
  taos_free_result(tres);
H
hzcheng 已提交
790 791
}

792 793
bool shellIsCommentLine(char *line) {
  if (line == NULL) return true;
794
  return shellRegexMatch(line, "^\\s*#.*", REG_EXTENDED);
H
hzcheng 已提交
795 796
}

797 798 799 800 801
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;
802
  char    fullname[PATH_MAX] = {0};
H
hzcheng 已提交
803

804 805
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
    tstrncpy(fullname, file, PATH_MAX);
H
hzcheng 已提交
806 807
  }

808
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_READ | TD_FILE_STREAM);
809
  if (pFile == NULL) {
810
    fprintf(stderr, "failed to open file %s\n", fullname);
wafwerar's avatar
wafwerar 已提交
811
    taosMemoryFree(cmd);
H
hzcheng 已提交
812 813 814
    return;
  }

815
  while ((read_len = taosGetLineFile(pFile, &line)) != -1) {
H
Haojun Liao 已提交
816
    if (read_len >= TSDB_MAX_ALLOWED_SQL_LEN) continue;
H
hzcheng 已提交
817 818
    line[--read_len] = '\0';

819
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
H
hzcheng 已提交
820 821 822 823 824 825 826 827 828 829 830
      continue;
    }

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

    memcpy(cmd + cmd_len, line, read_len);
831 832
    printf("%s%s\n", shell.info.promptHeader, cmd);
    shellRunCommand(cmd);
H
Haojun Liao 已提交
833
    memset(cmd, 0, TSDB_MAX_ALLOWED_SQL_LEN);
H
hzcheng 已提交
834 835 836
    cmd_len = 0;
  }

wafwerar's avatar
wafwerar 已提交
837
  taosMemoryFree(cmd);
S
Shengliang Guan 已提交
838
  if (line != NULL) taosMemoryFree(line);
839
  taosCloseFile(&pFile);
H
hzcheng 已提交
840
}
S
slguan 已提交
841

842
void shellGetGrantInfo() {
843 844 845 846
  char sinfo[1024] = {0};
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
  strtok(sinfo, "\n");

S
slguan 已提交
847 848
  char sql[] = "show grants";

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

851
  int32_t code = taos_errno(tres);
S
slguan 已提交
852
  if (code != TSDB_CODE_SUCCESS) {
853
    if (code == TSDB_CODE_OPS_NOT_SUPPORT) {
854
      fprintf(stdout, "Server is Community Edition, %s\n\n", sinfo);
S
slguan 已提交
855
    } else {
856
      fprintf(stderr, "Failed to check Server Edition, Reason:0x%04x:%s\n\n", taos_errno(shell.conn),
857
              taos_errstr(shell.conn));
S
slguan 已提交
858
    }
S
slguan 已提交
859 860 861
    return;
  }

862
  int32_t num_fields = taos_field_count(tres);
S
slguan 已提交
863 864 865 866
  if (num_fields == 0) {
    fprintf(stderr, "\nInvalid grant information.\n");
    exit(0);
  } else {
867
    if (tres == NULL) {
S
slguan 已提交
868 869 870 871
      fprintf(stderr, "\nGrant information is null.\n");
      exit(0);
    }

872
    TAOS_FIELD *fields = taos_fetch_fields(tres);
873
    TAOS_ROW    row = taos_fetch_row(tres);
S
slguan 已提交
874
    if (row == NULL) {
H
hjxilinx 已提交
875
      fprintf(stderr, "\nFailed to get grant information from server. Abort.\n");
S
slguan 已提交
876 877 878
      exit(0);
    }

S
slguan 已提交
879
    char serverVersion[32] = {0};
S
slguan 已提交
880 881 882
    char expiretime[32] = {0};
    char expired[32] = {0};

S
slguan 已提交
883
    memcpy(serverVersion, row[0], fields[0].bytes);
S
slguan 已提交
884 885 886 887
    memcpy(expiretime, row[1], fields[1].bytes);
    memcpy(expired, row[2], fields[2].bytes);

    if (strcmp(expiretime, "unlimited") == 0) {
888
      fprintf(stdout, "Server is Enterprise %s Edition, %s and will never expire.\n", serverVersion, sinfo);
S
slguan 已提交
889
    } else {
890
      fprintf(stdout, "Server is Enterprise %s Edition, %s and will expire at %s.\n", serverVersion, sinfo, expiretime);
S
slguan 已提交
891 892
    }

893
    taos_free_result(tres);
S
slguan 已提交
894 895 896
  }

  fprintf(stdout, "\n");
897 898 899 900
}

void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) { tsem_post(&shell.cancelSem); }

901 902 903 904
void shellSigintHandler(int32_t signum, void *sigInfo, void *context) {
  // do nothing
}

905 906 907 908 909 910 911 912 913 914 915
void shellCleanup(void *arg) { taosResetTerminalMode(); }

void *shellCancelHandler(void *arg) {
  setThreadName("shellCancelHandler");
  while (1) {
    if (tsem_wait(&shell.cancelSem) != 0) {
      taosMsleep(10);
      continue;
    }

    taosResetTerminalMode();
916
    printf("\nReceive SIGTERM or other signal, quit shell.\n");
917 918
    shellWriteHistory();
    shellExit();
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946
  }

  return NULL;
}

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

  char *command = taosMemoryMalloc(SHELL_MAX_COMMAND_SIZE);
  if (command == NULL) {
    printf("failed to malloc command\n");
    return NULL;
  }

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

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

    taosResetTerminalMode();
  } while (shellRunCommand(command) == 0);

  taosMemoryFreeClear(command);
947 948
  shellWriteHistory();
  shellExit();
949

950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969
  taosThreadCleanupPop(1);
  return NULL;
}

int32_t shellExecute() {
  printf(shell.info.clientVersion, shell.info.osname, taos_get_client_info());
  fflush(stdout);

  SShellArgs *pArgs = &shell.args;
  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;
  }

970 971
  shellReadHistory();

972
  if (pArgs->commands != NULL || pArgs->file[0] != 0) {
973 974 975 976 977 978 979
    if (pArgs->commands != NULL) {
      printf("%s%s\n", shell.info.promptHeader, pArgs->commands);
      char *cmd = strdup(pArgs->commands);
      shellRunCommand(cmd);
      taosMemoryFree(cmd);
    }

980
    if (pArgs->file[0] != 0) {
981 982 983 984 985
      shellSourceFile(pArgs->file);
    }

    taos_close(shell.conn);
    shellWriteHistory();
986
    shellCleanupHistory();
987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
    return 0;
  }

  if (tsem_init(&shell.cancelSem, 0, 0) != 0) {
    printf("failed to create cancel semphore\n");
    return -1;
  }

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

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

1002 1003
  taosSetSignal(SIGINT, shellSigintHandler);

1004 1005 1006 1007 1008
  shellGetGrantInfo(shell.conn);

  while (1) {
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, shell.conn);
    taosThreadJoin(shell.pid, NULL);
1009
    taosThreadClear(&shell.pid);
1010 1011
  }

1012
  shellCleanupHistory();
1013
  return 0;
S
slguan 已提交
1014
}