• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

taosdata / TDengine / #3638

11 Mar 2025 12:59PM UTC coverage: 3.066% (-18.3%) from 21.409%
#3638

push

travis-ci

web-flow
Merge pull request #30118 from taosdata/wl30

udpate ci workflow

5914 of 287117 branches covered (2.06%)

Branch coverage included in aggregate %.

11588 of 283747 relevant lines covered (4.08%)

142.17 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

1.05
/tools/shell/src/shellEngine.c
1
/*
2
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
3
 *
4
 * This program is free software: you can use, redistribute, and/or modify
5
 * it under the terms of the GNU Affero General Public License, version 3
6
 * or later ("AGPL"), as published by the Free Software Foundation.
7
 *
8
 * This program is distributed in the hope that it will be useful, but WITHOUT
9
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
 * FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * You should have received a copy of the GNU Affero General Public License
13
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14
 */
15

16
#define ALLOW_FORBID_FUNC
17
#define _BSD_SOURCE
18
#define _GNU_SOURCE
19
#define _XOPEN_SOURCE
20
#define _DEFAULT_SOURCE
21
#include "geosWrapper.h"
22
#include "shellAuto.h"
23
#include "shellInt.h"
24

25
SShellObj shell = {0};
26

27
typedef struct {
28
  const char *sql;
29
  bool        vertical;
30
  tsem_t      sem;
31
  int64_t     numOfRows;  // the num of this batch
32
  int64_t     numOfAllRows;
33

34
  int32_t     numFields;
35
  TAOS_FIELD *fields;
36
  int32_t     precision;
37

38
  int32_t maxColNameLen;            // for vertical print
39
  int32_t width[TSDB_MAX_COLUMNS];  // for horizontal print
40

41
  uint64_t resShowMaxNum;
42
} tsDumpInfo;
43

44
static bool    shellIsEmptyCommand(const char *cmd);
45
static int32_t shellRunSingleCommand(char *command);
46
static void    shellRecordCommandToHistory(char *command);
47
static int32_t shellRunCommand(char *command, bool recordHistory);
48
static void    shellRunSingleCommandImp(char *command);
49
static char   *shellFormatTimestamp(char *buf, int32_t bufSize, int64_t val, int32_t precision);
50
static int64_t shellDumpResultToFile(const char *fname, TAOS_RES *tres);
51
static void    shellPrintNChar(const char *str, int32_t length, int32_t width);
52
static void    shellPrintGeometry(const unsigned char *str, int32_t length, int32_t width);
53
static void    shellVerticalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info);
54
static void    shellHorizontalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info);
55
static int64_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql);
56
static void    shellReadHistory();
57
static void    shellWriteHistory();
58
static void    shellPrintError(TAOS_RES *tres, int64_t st);
59
static bool    shellIsCommentLine(char *line);
60
static void    shellSourceFile(const char *file);
61
static int32_t shellGetGrantInfo(char* buf);
62

63
static void  shellCleanup(void *arg);
64
static void *shellCancelHandler(void *arg);
65
static void *shellThreadLoop(void *arg);
66

67
static bool shellCmdkilled = false;
68

69
bool shellIsEmptyCommand(const char *cmd) {
×
70
  for (char c = *cmd++; c != 0; c = *cmd++) {
×
71
    if (c != ' ' && c != '\t' && c != ';') {
×
72
      return false;
×
73
    }
74
  }
75
  return true;
×
76
}
77

78
int32_t shellRunSingleCommand(char *command) {
×
79
  shellCmdkilled = false;
×
80

81
  if (shellIsEmptyCommand(command)) {
×
82
    return 0;
×
83
  }
84

85
  if (shellRegexMatch(command, "^[ \t]*(quit|q|exit)[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
×
86
    return -1;
×
87
  }
88

89
  if (shellRegexMatch(command, "^[\t ]*clear[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
×
90
#pragma GCC diagnostic push
91
#pragma GCC diagnostic ignored "-Wunused-result"
92
    system("clear");
×
93
#pragma GCC diagnostic pop
94
    return 0;
×
95
  }
96

97
  if (shellRegexMatch(command, "^[\t ]*set[ \t]+max_binary_display_width[ \t]+(default|[1-9][0-9]*)[ \t;]*$",
×
98
                      REG_EXTENDED | REG_ICASE)) {
99
    strtok(command, " \t");
×
100
    strtok(NULL, " \t");
×
101
    char *p = strtok(NULL, " \t");
×
102
    if (strncasecmp(p, "default", 7) == 0) {
×
103
      shell.args.displayWidth = SHELL_DEFAULT_MAX_BINARY_DISPLAY_WIDTH;
×
104
    } else {
105
      int32_t displayWidth = atoi(p);
×
106
      displayWidth = TRANGE(displayWidth, 1, 10 * 1024);
×
107
      shell.args.displayWidth = displayWidth;
×
108
    }
109
    return 0;
×
110
  }
111

112
  if (shellRegexMatch(command, "^[ \t]*source[\t ]+[^ ]+[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
×
113
    /* If source file. */
114
    char *c_ptr = strtok(command, " ;");
×
115
    if (c_ptr == NULL) {
×
116
      shellRunSingleCommandImp(command);
×
117
      return 0;
×
118
    }
119
    c_ptr = strtok(NULL, " ;");
×
120
    if (c_ptr == NULL) {
×
121
      shellRunSingleCommandImp(command);
×
122
      return 0;
×
123
    }
124
    shellSourceFile(c_ptr);
×
125
    return 0;
×
126
  }
127
#ifdef WEBSOCKET
128
  if (shell.args.restful || shell.args.cloud) {
×
129
    shellRunSingleCommandWebsocketImp(command);
×
130
  } else {
131
#endif
132
    shellRunSingleCommandImp(command);
×
133
#ifdef WEBSOCKET
134
  }
135
#endif
136
  return 0;
×
137
}
138

139
void shellRecordCommandToHistory(char *command) {
×
140
  if (strncasecmp(command, "create user ", 12) == 0 || strncasecmp(command, "alter user ", 11) == 0) {
×
141
    if (taosStrCaseStr(command, " pass ")) {
×
142
      // have password command forbid record to history because security
143
      return;
×
144
    }
145
  }
146

147
  SShellHistory *pHistory = &shell.history;
×
148
  if (pHistory->hstart == pHistory->hend ||
×
149
      pHistory->hist[(pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE] == NULL ||
×
150
      strcmp(command, pHistory->hist[(pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE]) != 0) {
×
151
    if (pHistory->hist[pHistory->hend] != NULL) {
×
152
      taosMemoryFreeClear(pHistory->hist[pHistory->hend]);
×
153
    }
154
    pHistory->hist[pHistory->hend] = taosStrdup(command);
×
155

156
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
×
157
    if (pHistory->hend == pHistory->hstart) {
×
158
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
×
159
    }
160
  }
161
}
162

163
int32_t shellRunCommand(char *command, bool recordHistory) {
×
164
  if (shellIsEmptyCommand(command)) {
×
165
    return 0;
×
166
  }
167

168
  // add help or help;
169
  if (strncasecmp(command, "help", 4) == 0) {
×
170
    if (command[4] == ';' || command[4] == ' ' || command[4] == 0) {
×
171
      showHelp();
×
172
      return 0;
×
173
    }
174
  }
175

176
  if (recordHistory) shellRecordCommandToHistory(command);
×
177

178
  char quote = 0, *cmd = command;
×
179
  for (char c = *command++; c != 0; c = *command++) {
×
180
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
×
181
      command++;
×
182
      continue;
×
183
    }
184

185
    if (quote == c) {
×
186
      quote = 0;
×
187
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
×
188
      quote = c;
×
189
    } else if (c == ';' && quote == 0) {
×
190
      c = *command;
×
191
      *command = 0;
×
192
      if (shellRunSingleCommand(cmd) < 0) {
×
193
        return -1;
×
194
      }
195
      *command = c;
×
196
      cmd = command;
×
197
    }
198
  }
199
  return shellRunSingleCommand(cmd);
×
200
}
201

202
char *strendG(const char *pstr) {
×
203
  if (pstr == NULL) {
×
204
    return NULL;
×
205
  }
206

207
  size_t len = strlen(pstr);
×
208
  if (len < 4) {
×
209
    return NULL;
×
210
  }
211

212
  char *p = (char *)pstr + len - 2;
×
213
  if (strcmp(p, "\\G") == 0) {
×
214
    return p;
×
215
  }
216

217
  p = (char *)pstr + len - 3;
×
218
  if (strcmp(p, "\\G;") == 0) {
×
219
    return p;
×
220
  }
221

222
  return NULL;
×
223
}
224

225
void shellRunSingleCommandImp(char *command) {
×
226
  int64_t st, et;
227
  char   *sptr = NULL;
×
228
  char   *cptr = NULL;
×
229
  char   *fname = NULL;
×
230
  bool    printMode = false;
×
231

232
  if ((sptr = strstr(command, ">>")) != NULL) {
×
233
    fname = sptr + 2;
×
234
    while (*fname == ' ') fname++;
×
235
    *sptr = '\0';
×
236

237
    cptr = strstr(fname, ";");
×
238
    if (cptr != NULL) {
×
239
      *cptr = '\0';
×
240
    }
241
  }
242

243
  if ((sptr = strendG(command)) != NULL) {
×
244
    *sptr = '\0';
×
245
    printMode = true;  // When output to a file, the switch does not work.
×
246
  }
247

248
  st = taosGetTimestampUs();
×
249

250
  TAOS_RES *pSql = taos_query(shell.conn, command);
×
251
  if (taos_errno(pSql)) {
×
252
    shellPrintError(pSql, st);
×
253
    return;
×
254
  }
255

256
  if (shellRegexMatch(command, "^\\s*use\\s+[a-zA-Z0-9_]+\\s*;\\s*$", REG_EXTENDED | REG_ICASE)) {
×
257
    printf("Database changed.\r\n\r\n");
×
258

259
    // call back auto tab module
260
    callbackAutoTab(command, pSql, true);
×
261

262
    taos_free_result(pSql);
×
263

264
    return;
×
265
  }
266

267
  // pre string
268
  char *pre = "Query OK";
×
269
  if (shellRegexMatch(command, "^\\s*delete\\s*from\\s*.*", REG_EXTENDED | REG_ICASE)) {
×
270
    pre = "Delete OK";
×
271
  } else if (shellRegexMatch(command, "^\\s*insert\\s*into\\s*.*", REG_EXTENDED | REG_ICASE)) {
×
272
    pre = "Insert OK";
×
273
  } else if (shellRegexMatch(command, "^\\s*create\\s*.*", REG_EXTENDED | REG_ICASE)) {
×
274
    pre = "Create OK";
×
275
  } else if (shellRegexMatch(command, "^\\s*drop\\s*.*", REG_EXTENDED | REG_ICASE)) {
×
276
    pre = "Drop OK";
×
277
  }
278

279
  TAOS_FIELD *pFields = taos_fetch_fields(pSql);
×
280
  if (pFields != NULL) {  // select and show kinds of commands
×
281
    int32_t error_no = 0;
×
282

283
    int64_t numOfRows = shellDumpResult(pSql, fname, &error_no, printMode, command);
×
284
    if (numOfRows < 0) return;
×
285

286
    et = taosGetTimestampUs();
×
287
    if (error_no == 0) {
×
288
      printf("Query OK, %" PRId64 " row(s) in set (%.6fs)\r\n", numOfRows, (et - st) / 1E6);
×
289
    } else {
290
      terrno = error_no;
×
291
      printf("Query interrupted (%s), %" PRId64 " row(s) in set (%.6fs)\r\n", taos_errstr(NULL), numOfRows,
×
292
             (et - st) / 1E6);
×
293
    }
294
    taos_free_result(pSql);
×
295
  } else {
296
    int64_t num_rows_affacted = taos_affected_rows64(pSql);
×
297
    taos_free_result(pSql);
×
298
    et = taosGetTimestampUs();
×
299
    printf("%s, %" PRId64 " row(s) affected (%.6fs)\r\n", pre, num_rows_affacted, (et - st) / 1E6);
×
300

301
    // call auto tab
302
    callbackAutoTab(command, NULL, false);
×
303
  }
304

305
  printf("\r\n");
×
306
}
307

308
char *shellFormatTimestamp(char *buf, int32_t bufSize, int64_t val, int32_t precision) {
×
309
  if (shell.args.is_raw_time) {
×
310
    sprintf(buf, "%" PRId64, val);
×
311
    return buf;
×
312
  }
313

314
  time_t  tt;
315
  int32_t ms = 0;
×
316
  if (precision == TSDB_TIME_PRECISION_NANO) {
×
317
    tt = (time_t)(val / 1000000000);
×
318
    ms = val % 1000000000;
×
319
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
×
320
    tt = (time_t)(val / 1000000);
×
321
    ms = val % 1000000;
×
322
  } else {
323
    tt = (time_t)(val / 1000);
×
324
    ms = val % 1000;
×
325
  }
326

327
  if (tt <= 0 && ms < 0) {
×
328
    tt--;
×
329
    if (precision == TSDB_TIME_PRECISION_NANO) {
×
330
      ms += 1000000000;
×
331
    } else if (precision == TSDB_TIME_PRECISION_MICRO) {
×
332
      ms += 1000000;
×
333
    } else {
334
      ms += 1000;
×
335
    }
336
  }
337

338
  struct tm ptm = {0};
×
339
  if (taosLocalTime(&tt, &ptm, buf, bufSize, NULL) == NULL) {
×
340
    return buf;
×
341
  }
342
  size_t pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
×
343

344
  if (precision == TSDB_TIME_PRECISION_NANO) {
×
345
    sprintf(buf + pos, ".%09d", ms);
×
346
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
×
347
    sprintf(buf + pos, ".%06d", ms);
×
348
  } else {
349
    sprintf(buf + pos, ".%03d", ms);
×
350
  }
351

352
  return buf;
×
353
}
354

355
char *shellDumpHexValue(char *buf, const char *val, int32_t length) {
×
356
  for (int32_t i = 0; i < length; i++) {
×
357
    sprintf(buf + (i * 2), "%02X", val[i]);
×
358
  }
359
  buf[length * 2] = 0;
×
360

361
  return buf;
×
362
}
363

364
void shellDumpFieldToFile(TdFilePtr pFile, const char *val, TAOS_FIELD *field, int32_t length, int32_t precision) {
×
365
  if (val == NULL) {
×
366
    taosFprintfFile(pFile, "NULL");
×
367
    return;
×
368
  }
369

370
  char    quotationStr[2] = {'"', 0};
×
371
  int32_t width;
372

373
  int n = 0;
×
374
#define LENGTH 64
375
  char buf[LENGTH] = {0};
×
376
  switch (field->type) {
×
377
    case TSDB_DATA_TYPE_BOOL:
×
378
      taosFprintfFile(pFile, "%d", ((((int32_t)(*((char *)val))) == 1) ? 1 : 0));
×
379
      break;
×
380
    case TSDB_DATA_TYPE_TINYINT:
×
381
      taosFprintfFile(pFile, "%d", *((int8_t *)val));
×
382
      break;
×
383
    case TSDB_DATA_TYPE_UTINYINT:
×
384
      taosFprintfFile(pFile, "%u", *((uint8_t *)val));
×
385
      break;
×
386
    case TSDB_DATA_TYPE_SMALLINT:
×
387
      taosFprintfFile(pFile, "%d", *((int16_t *)val));
×
388
      break;
×
389
    case TSDB_DATA_TYPE_USMALLINT:
×
390
      taosFprintfFile(pFile, "%u", *((uint16_t *)val));
×
391
      break;
×
392
    case TSDB_DATA_TYPE_INT:
×
393
      taosFprintfFile(pFile, "%d", *((int32_t *)val));
×
394
      break;
×
395
    case TSDB_DATA_TYPE_UINT:
×
396
      taosFprintfFile(pFile, "%u", *((uint32_t *)val));
×
397
      break;
×
398
    case TSDB_DATA_TYPE_BIGINT:
×
399
      taosFprintfFile(pFile, "%" PRId64, *((int64_t *)val));
×
400
      break;
×
401
    case TSDB_DATA_TYPE_UBIGINT:
×
402
      taosFprintfFile(pFile, "%" PRIu64, *((uint64_t *)val));
×
403
      break;
×
404
    case TSDB_DATA_TYPE_FLOAT:
×
405
      width = SHELL_FLOAT_WIDTH;
×
406
      if (tsEnableScience) {
×
407
        taosFprintfFile(pFile, "%*.7e", width, GET_FLOAT_VAL(val));
×
408
      } else {
409
        n = tsnprintf(buf, LENGTH, "%*.7f", width, GET_FLOAT_VAL(val));
×
410
        if (n > SHELL_FLOAT_WIDTH) {
×
411
          taosFprintfFile(pFile, "%*.7e", width, GET_FLOAT_VAL(val));
×
412
        } else {
413
          taosFprintfFile(pFile, "%s", buf);
×
414
        }
415
      }
416
      break;
×
417
    case TSDB_DATA_TYPE_DOUBLE:
×
418
      width = SHELL_DOUBLE_WIDTH;
×
419
      if (tsEnableScience) {
×
420
        snprintf(buf, LENGTH, "%*.15e", width, GET_DOUBLE_VAL(val));
×
421
        taosFprintfFile(pFile, "%s", buf);
×
422
      } else {
423
        n = tsnprintf(buf, LENGTH, "%*.15f", width, GET_DOUBLE_VAL(val));
×
424
        if (n > SHELL_DOUBLE_WIDTH) {
×
425
          taosFprintfFile(pFile, "%*.15e", width, GET_DOUBLE_VAL(val));
×
426
        } else {
427
          taosFprintfFile(pFile, "%s", buf);
×
428
        }
429
      }
430
      break;
×
431
    case TSDB_DATA_TYPE_BINARY:
×
432
    case TSDB_DATA_TYPE_NCHAR:
433
    case TSDB_DATA_TYPE_JSON: {
434
      int32_t bufIndex = 0;
×
435
      char   *tmp = (char *)taosMemoryCalloc(length * 2 + 1, 1);
×
436
      if (tmp == NULL) break;
×
437
      for (int32_t i = 0; i < length; i++) {
×
438
        tmp[bufIndex] = val[i];
×
439
        bufIndex++;
×
440
        if (val[i] == '\"') {
×
441
          tmp[bufIndex] = val[i];
×
442
          bufIndex++;
×
443
        }
444
      }
445
      tmp[bufIndex] = 0;
×
446

447
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
×
448
      taosMemoryFree(tmp);
×
449
    } break;
×
450
    case TSDB_DATA_TYPE_VARBINARY: {
×
451
      void    *tmp = NULL;
×
452
      uint32_t size = 0;
×
453
      if (taosAscii2Hex(val, length, &tmp, &size) < 0) {
×
454
        break;
×
455
      }
456
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
×
457
      taosMemoryFree(tmp);
×
458
      break;
×
459
    }
460
    case TSDB_DATA_TYPE_GEOMETRY: {
×
461
      char *tmp = (char *)taosMemoryCalloc(length * 2 + 1, 1);
×
462
      if (tmp == NULL) break;
×
463
      shellDumpHexValue(tmp, val, length);
×
464
      taosFprintfFile(pFile, "%s", buf);
×
465
      taosMemoryFree(tmp);
×
466
      break;
×
467
    }
468
    case TSDB_DATA_TYPE_TIMESTAMP:
×
469
      shellFormatTimestamp(buf, sizeof(buf), *(int64_t *)val, precision);
×
470
      taosFprintfFile(pFile, "%s%s%s", quotationStr, buf, quotationStr);
×
471
      break;
×
472
    default:
×
473
      break;
×
474
  }
475
}
476

477
int64_t shellDumpResultToFile(const char *fname, TAOS_RES *tres) {
×
478
  char fullname[PATH_MAX] = {0};
×
479
  if (taosExpandDir(fname, fullname, PATH_MAX) != 0) {
×
480
    tstrncpy(fullname, fname, PATH_MAX);
×
481
  }
482

483
  TAOS_ROW row = taos_fetch_row(tres);
×
484
  if (row == NULL) {
×
485
    return 0;
×
486
  }
487

488
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_TRUNC | TD_FILE_STREAM);
×
489
  if (pFile == NULL) {
×
490
    fprintf(stderr, "failed to open file: %s\r\n", fullname);
×
491
    return -1;
×
492
  }
493

494
  TAOS_FIELD *fields = taos_fetch_fields(tres);
×
495
  int32_t     num_fields = taos_num_fields(tres);
×
496
  int32_t     precision = taos_result_precision(tres);
×
497

498
  for (int32_t col = 0; col < num_fields; col++) {
×
499
    if (col > 0) {
×
500
      taosFprintfFile(pFile, ",");
×
501
    }
502
    taosFprintfFile(pFile, "%s", fields[col].name);
×
503
  }
504
  taosFprintfFile(pFile, "\r\n");
×
505

506
  int64_t numOfRows = 0;
×
507
  do {
508
    int32_t *length = taos_fetch_lengths(tres);
×
509
    for (int32_t i = 0; i < num_fields; i++) {
×
510
      if (i > 0) {
×
511
        taosFprintfFile(pFile, ",");
×
512
      }
513
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision);
×
514
    }
515
    taosFprintfFile(pFile, "\r\n");
×
516

517
    numOfRows++;
×
518
    row = taos_fetch_row(tres);
×
519
  } while (row != NULL);
×
520

521
  taosCloseFile(&pFile);
×
522

523
  return numOfRows;
×
524
}
525

526
void shellPrintNChar(const char *str, int32_t length, int32_t width) {
×
527
  TdWchar tail[3];
528
  int32_t pos = 0, cols = 0, totalCols = 0, tailLen = 0;
×
529

530
  while (pos < length) {
×
531
    TdWchar wc;
532
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
×
533
    if (bytes <= 0) {
×
534
      break;
×
535
    }
536

537
    if (pos + bytes > length) {
×
538
      break;
×
539
    }
540
    int w = 0;
×
541
    if (*(str + pos) == '\t' || *(str + pos) == '\n' || *(str + pos) == '\r') {
×
542
      w = bytes;
×
543
    } else {
544
      w = taosWcharWidth(wc);
×
545
    }
546
    pos += bytes;
×
547

548
    if (w <= 0) {
×
549
      continue;
×
550
    }
551

552
    if (width <= 0) {
×
553
      printf("%lc", wc);
×
554
      continue;
×
555
    }
556

557
    totalCols += w;
×
558
    if (totalCols > width) {
×
559
      break;
×
560
    }
561
    if (totalCols <= (width - 3)) {
×
562
      printf("%lc", wc);
×
563
      cols += w;
×
564
    } else {
565
      tail[tailLen] = wc;
×
566
      tailLen++;
×
567
    }
568
  }
569

570
  if (totalCols > width) {
×
571
    // width could be 1 or 2, so printf("...") cannot be used
572
    for (int32_t i = 0; i < 3; i++) {
×
573
      if (cols >= width) {
×
574
        break;
×
575
      }
576
      putchar('.');
×
577
      ++cols;
×
578
    }
579
  } else {
580
    for (int32_t i = 0; i < tailLen; i++) {
×
581
      printf("%lc", tail[i]);
×
582
    }
583
    cols = totalCols;
×
584
  }
585

586
  for (; cols < width; cols++) {
×
587
    putchar(' ');
×
588
  }
589
}
×
590

591
void shellPrintString(const char *str, int32_t width) {
×
592
  int32_t len = strlen(str);
×
593

594
  if (width == 0) {
×
595
    printf("%s", str);
×
596
  } else if (len > width) {
×
597
    if (width <= 3) {
×
598
      printf("%.*s.", width - 1, str);
×
599
    } else {
600
      printf("%.*s...", width - 3, str);
×
601
    }
602
  } else {
603
    printf("%s%*.s", str, width - len, "");
×
604
  }
605
}
×
606

607
void shellPrintGeometry(const unsigned char *val, int32_t length, int32_t width) {
×
608
  if (length == 0) {  // empty value
×
609
    shellPrintString("", width);
×
610
    return;
×
611
  }
612

613
  int32_t code = TSDB_CODE_FAILED;
×
614

615
  code = initCtxAsText();
×
616
  if (code != TSDB_CODE_SUCCESS) {
×
617
    shellPrintString(getGeosErrMsg(code), width);
×
618
    return;
×
619
  }
620

621
  char *outputWKT = NULL;
×
622
  code = doAsText(val, length, &outputWKT);
×
623
  if (code != TSDB_CODE_SUCCESS) {
×
624
    shellPrintString(getGeosErrMsg(code), width);  // should NOT happen
×
625
    return;
×
626
  }
627

628
  shellPrintString(outputWKT, width);
×
629

630
  geosFreeBuffer(outputWKT);
×
631
}
632

633
void shellPrintField(const char *val, TAOS_FIELD *field, int32_t width, int32_t length, int32_t precision) {
×
634
  if (val == NULL) {
×
635
    shellPrintString(TSDB_DATA_NULL_STR, width);
×
636
    return;
×
637
  }
638

639
  int n = 0;
×
640
#define LENGTH 64
641
  char buf[LENGTH] = {0};
×
642
  switch (field->type) {
×
643
    case TSDB_DATA_TYPE_BOOL:
×
644
      shellPrintString(((((int32_t)(*((char *)val))) == TSDB_FALSE) ? "false" : "true"), width);
×
645
      break;
×
646
    case TSDB_DATA_TYPE_TINYINT:
×
647
      printf("%*d", width, *((int8_t *)val));
×
648
      break;
×
649
    case TSDB_DATA_TYPE_UTINYINT:
×
650
      printf("%*u", width, *((uint8_t *)val));
×
651
      break;
×
652
    case TSDB_DATA_TYPE_SMALLINT:
×
653
      printf("%*d", width, *((int16_t *)val));
×
654
      break;
×
655
    case TSDB_DATA_TYPE_USMALLINT:
×
656
      printf("%*u", width, *((uint16_t *)val));
×
657
      break;
×
658
    case TSDB_DATA_TYPE_INT:
×
659
      printf("%*d", width, *((int32_t *)val));
×
660
      break;
×
661
    case TSDB_DATA_TYPE_UINT:
×
662
      printf("%*u", width, *((uint32_t *)val));
×
663
      break;
×
664
    case TSDB_DATA_TYPE_BIGINT:
×
665
      printf("%*" PRId64, width, *((int64_t *)val));
×
666
      break;
×
667
    case TSDB_DATA_TYPE_UBIGINT:
×
668
      printf("%*" PRIu64, width, *((uint64_t *)val));
×
669
      break;
×
670
    case TSDB_DATA_TYPE_FLOAT:
×
671
      width = width >= LENGTH ? LENGTH - 1 : width;
×
672
      if (tsEnableScience) {
×
673
        printf("%*.7e", width, GET_FLOAT_VAL(val));
×
674
      } else {
675
        snprintf(buf, LENGTH, "%*.*g", width, FLT_DIG, GET_FLOAT_VAL(val));
×
676
        printf("%s", buf);
×
677
      }
678
      break;
×
679
    case TSDB_DATA_TYPE_DOUBLE:
×
680
      width = width >= LENGTH ? LENGTH - 1 : width;
×
681
      if (tsEnableScience) {
×
682
        snprintf(buf, LENGTH, "%*.15e", width, GET_DOUBLE_VAL(val));
×
683
        printf("%s", buf);
×
684
      } else {
685
        snprintf(buf, LENGTH, "%*.*g", width, DBL_DIG, GET_DOUBLE_VAL(val));
×
686
        printf("%*s", width, buf);
×
687
      }
688
      break;
×
689
    case TSDB_DATA_TYPE_VARBINARY: {
×
690
      void    *data = NULL;
×
691
      uint32_t size = 0;
×
692
      if (taosAscii2Hex(val, length, &data, &size) < 0) {
×
693
        break;
×
694
      }
695
      shellPrintNChar(data, size, width);
×
696
      taosMemoryFree(data);
×
697
      break;
×
698
    }
699
    case TSDB_DATA_TYPE_BINARY:
×
700
    case TSDB_DATA_TYPE_NCHAR:
701
    case TSDB_DATA_TYPE_JSON:
702
      shellPrintNChar(val, length, width);
×
703
      break;
×
704
    case TSDB_DATA_TYPE_GEOMETRY:
×
705
      shellPrintGeometry(val, length, width);
×
706
      break;
×
707
    case TSDB_DATA_TYPE_TIMESTAMP:
×
708
      shellFormatTimestamp(buf, sizeof(buf), *(int64_t *)val, precision);
×
709
      printf("%s", buf);
×
710
      break;
×
711
    default:
×
712
      break;
×
713
  }
714
}
715

716
// show whole result for this query return true, like limit or describe
717
bool shellIsShowWhole(const char *sql) {
×
718
  // limit
719
  if (taosStrCaseStr(sql, " limit ") != NULL) {
×
720
    return true;
×
721
  }
722
  // describe
723
  if (taosStrCaseStr(sql, "describe ") != NULL) {
×
724
    return true;
×
725
  }
726
  // desc
727
  if (taosStrCaseStr(sql, "desc ") != NULL) {
×
728
    return true;
×
729
  }
730
  // show
731
  if (taosStrCaseStr(sql, "show ") != NULL) {
×
732
    return true;
×
733
  }
734
  // explain
735
  if (taosStrCaseStr(sql, "explain ") != NULL) {
×
736
    return true;
×
737
  }
738

739
  return false;
×
740
}
741

742
bool shellIsShowQuery(const char *sql) {
×
743
  // todo refactor
744
  if (taosStrCaseStr(sql, "show ") != NULL) {
×
745
    return true;
×
746
  }
747

748
  return false;
×
749
}
750

751
void init_dump_info(tsDumpInfo *dump_info, TAOS_RES *tres, const char *sql, bool vertical) {
×
752
  dump_info->sql = sql;
×
753
  dump_info->vertical = vertical;
×
754
  tsem_init(&dump_info->sem, 0, 0);
×
755
  dump_info->numOfAllRows = 0;
×
756

757
  dump_info->numFields = taos_num_fields(tres);
×
758
  dump_info->fields = taos_fetch_fields(tres);
×
759
  dump_info->precision = taos_result_precision(tres);
×
760

761
  dump_info->resShowMaxNum = UINT64_MAX;
×
762

763
  if (shell.args.commands == NULL && shell.args.file[0] == 0 && !shellIsShowWhole(dump_info->sql)) {
×
764
    dump_info->resShowMaxNum = SHELL_DEFAULT_RES_SHOW_NUM;
×
765
  }
766

767
  if (vertical) {
×
768
    dump_info->maxColNameLen = 0;
×
769
    for (int32_t col = 0; col < dump_info->numFields; col++) {
×
770
      int32_t len = (int32_t)strlen(dump_info->fields[col].name);
×
771
      if (len > dump_info->maxColNameLen) {
×
772
        dump_info->maxColNameLen = len;
×
773
      }
774
    }
775
  } else {
776
    for (int32_t col = 0; col < dump_info->numFields; col++) {
×
777
      dump_info->width[col] = shellCalcColWidth(dump_info->fields + col, dump_info->precision);
×
778
    }
779
  }
780
}
×
781

782
void shellVerticalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
×
783
  TAOS_ROW row = taos_fetch_row(tres);
×
784
  if (row == NULL) {
×
785
    printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
786
    return;
×
787
  }
788

789
  int64_t numOfPintRows = dump_info->numOfAllRows;
×
790
  int     numOfPrintRowsThisOne = 0;
×
791

792
  while (row != NULL) {
×
793
    printf("*************************** %" PRId64 ".row ***************************\r\n", numOfPintRows + 1);
×
794

795
    int32_t *length = taos_fetch_lengths(tres);
×
796

797
    for (int32_t i = 0; i < dump_info->numFields; i++) {
×
798
      TAOS_FIELD *field = dump_info->fields + i;
×
799

800
      int32_t padding = (int32_t)(dump_info->maxColNameLen - strlen(field->name));
×
801
      printf("%*.s%s: ", padding, " ", field->name);
×
802

803
      shellPrintField((const char *)row[i], field, 0, length[i], dump_info->precision);
×
804
      putchar('\r');
×
805
      putchar('\n');
×
806
    }
807

808
    numOfPintRows++;
×
809
    numOfPrintRowsThisOne++;
×
810

811
    if (numOfPintRows == dump_info->resShowMaxNum) {
×
812
      printf("\r\n");
×
813
      printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
×
814
      printf("         You can use the `LIMIT` clause to get fewer result to show.\r\n");
×
815
      printf("           Or use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
816
      printf("\r\n");
×
817
      printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
×
818
      printf("\r\n");
×
819
      return;
×
820
    }
821

822
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
×
823
      return;
×
824
    }
825

826
    row = taos_fetch_row(tres);
×
827
  }
828
  return;
×
829
}
830

831
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
×
832
  int32_t width = (int32_t)strlen(field->name);
×
833

834
  switch (field->type) {
×
835
    case TSDB_DATA_TYPE_NULL:
×
836
      return TMAX(4, width);  // null
×
837
    case TSDB_DATA_TYPE_BOOL:
×
838
      return TMAX(5, width);  // 'false'
×
839

840
    case TSDB_DATA_TYPE_TINYINT:
×
841
    case TSDB_DATA_TYPE_UTINYINT:
842
      return TMAX(4, width);  // '-127'
×
843

844
    case TSDB_DATA_TYPE_SMALLINT:
×
845
    case TSDB_DATA_TYPE_USMALLINT:
846
      return TMAX(6, width);  // '-32767'
×
847

848
    case TSDB_DATA_TYPE_INT:
×
849
    case TSDB_DATA_TYPE_UINT:
850
      return TMAX(11, width);  // '-2147483648'
×
851

852
    case TSDB_DATA_TYPE_BIGINT:
×
853
    case TSDB_DATA_TYPE_UBIGINT:
854
      return TMAX(21, width);  // '-9223372036854775807'
×
855

856
    case TSDB_DATA_TYPE_FLOAT:
×
857
      return TMAX(SHELL_FLOAT_WIDTH, width);
×
858

859
    case TSDB_DATA_TYPE_DOUBLE:
×
860
      return TMAX(SHELL_DOUBLE_WIDTH, width);
×
861

862
    case TSDB_DATA_TYPE_BINARY:
×
863
    case TSDB_DATA_TYPE_GEOMETRY:
864
      if (field->bytes > shell.args.displayWidth) {
×
865
        return TMAX(shell.args.displayWidth, width);
×
866
      } else {
867
        return TMAX(field->bytes + 2, width);
×
868
      }
869
    case TSDB_DATA_TYPE_VARBINARY: {
×
870
      int32_t bytes = field->bytes * 2 + 2;
×
871
      if (bytes > shell.args.displayWidth) {
×
872
        return TMAX(shell.args.displayWidth, width);
×
873
      } else {
874
        return TMAX(bytes + 2, width);
×
875
      }
876
    }
877
    case TSDB_DATA_TYPE_NCHAR:
×
878
    case TSDB_DATA_TYPE_JSON: {
879
      uint16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
×
880
      if (bytes > shell.args.displayWidth) {
×
881
        return TMAX(shell.args.displayWidth, width);
×
882
      } else {
883
        return TMAX(bytes + 2, width);
×
884
      }
885
    }
886

887
    case TSDB_DATA_TYPE_TIMESTAMP:
×
888
      if (shell.args.is_raw_time) {
×
889
        return TMAX(14, width);
×
890
      }
891
      if (precision == TSDB_TIME_PRECISION_NANO) {
×
892
        return TMAX(29, width);
×
893
      } else if (precision == TSDB_TIME_PRECISION_MICRO) {
×
894
        return TMAX(26, width);  // '2020-01-01 00:00:00.000000'
×
895
      } else {
896
        return TMAX(23, width);  // '2020-01-01 00:00:00.000'
×
897
      }
898

899
    default:
×
900
      ASSERT(false);
×
901
  }
902

903
  return 0;
×
904
}
905

906
void shellPrintHeader(TAOS_FIELD *fields, int32_t *width, int32_t num_fields) {
×
907
  int32_t rowWidth = 0;
×
908
  for (int32_t col = 0; col < num_fields; col++) {
×
909
    TAOS_FIELD *field = fields + col;
×
910
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
×
911
    int32_t     left = padding / 2;
×
912
    printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
×
913
    rowWidth += width[col] + 3;
×
914
  }
915

916
  putchar('\r');
×
917
  putchar('\n');
×
918
  for (int32_t i = 0; i < rowWidth; i++) {
×
919
    putchar('=');
×
920
  }
921
  putchar('\r');
×
922
  putchar('\n');
×
923
}
×
924

925
void shellHorizontalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
×
926
  TAOS_ROW row = taos_fetch_row(tres);
×
927
  if (row == NULL) {
×
928
    printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
929
    return;
×
930
  }
931

932
  int64_t numOfPintRows = dump_info->numOfAllRows;
×
933
  int     numOfPrintRowsThisOne = 0;
×
934
  if (numOfPintRows == 0) {
×
935
    shellPrintHeader(dump_info->fields, dump_info->width, dump_info->numFields);
×
936
  }
937

938
  while (row != NULL) {
×
939
    int32_t *length = taos_fetch_lengths(tres);
×
940
    for (int32_t i = 0; i < dump_info->numFields; i++) {
×
941
      putchar(' ');
×
942
      shellPrintField((const char *)row[i], dump_info->fields + i, dump_info->width[i], length[i],
×
943
                      dump_info->precision);
944
      putchar(' ');
×
945
      putchar('|');
×
946
    }
947
    putchar('\r');
×
948
    putchar('\n');
×
949

950
    numOfPintRows++;
×
951
    numOfPrintRowsThisOne++;
×
952

953
    if (numOfPintRows == dump_info->resShowMaxNum) {
×
954
      printf("\r\n");
×
955
      printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
×
956
      if (shellIsShowQuery(dump_info->sql)) {
×
957
        printf("         You can use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
958
      } else {
959
        printf("         You can use the `LIMIT` clause to get fewer result to show.\r\n");
×
960
        printf("           Or use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
961
      }
962
      printf("\r\n");
×
963
      printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
×
964
      printf("\r\n");
×
965
      return;
×
966
    }
967

968
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
×
969
      return;
×
970
    }
971

972
    row = taos_fetch_row(tres);
×
973
  }
974
  return;
×
975
}
976

977
void shellDumpResultCallback(void *param, TAOS_RES *tres, int num_of_rows) {
×
978
  tsDumpInfo *dump_info = (tsDumpInfo *)param;
×
979
  if (num_of_rows > 0) {
×
980
    dump_info->numOfRows = num_of_rows;
×
981
    if (dump_info->numOfAllRows < dump_info->resShowMaxNum) {
×
982
      if (dump_info->vertical) {
×
983
        shellVerticalPrintResult(tres, dump_info);
×
984
      } else {
985
        shellHorizontalPrintResult(tres, dump_info);
×
986
      }
987
    }
988
    dump_info->numOfAllRows += num_of_rows;
×
989
    if (!shellCmdkilled) {
×
990
      taos_fetch_rows_a(tres, shellDumpResultCallback, param);
×
991
    } else {
992
      tsem_post(&dump_info->sem);
×
993
    }
994
  } else {
995
    if (num_of_rows < 0) {
×
996
      printf("\033[31masync retrieve failed, code: %d\033[0m\n", num_of_rows);
×
997
    }
998
    tsem_post(&dump_info->sem);
×
999
  }
1000
}
×
1001

1002
int64_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
×
1003
  int64_t num_of_rows = 0;
×
1004
  if (fname != NULL) {
×
1005
    num_of_rows = shellDumpResultToFile(fname, tres);
×
1006
  } else {
1007
    tsDumpInfo dump_info;
1008
    if (!shellCmdkilled) {
×
1009
      init_dump_info(&dump_info, tres, sql, vertical);
×
1010
      taos_fetch_rows_a(tres, shellDumpResultCallback, &dump_info);
×
1011
      tsem_wait(&dump_info.sem);
×
1012
      num_of_rows = dump_info.numOfAllRows;
×
1013
    }
1014
  }
1015

1016
  *error_no = shellCmdkilled ? TSDB_CODE_TSC_QUERY_KILLED : taos_errno(tres);
×
1017
  return num_of_rows;
×
1018
}
1019

1020
void shellReadHistory() {
×
1021
  SShellHistory *pHistory = &shell.history;
×
1022
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_READ | TD_FILE_STREAM);
×
1023
  if (pFile == NULL) return;
×
1024

1025
  char   *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
×
1026
  int32_t read_size = 0;
×
1027
  while ((read_size = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) > 0) {
×
1028
    line[read_size - 1] = '\0';
×
1029
    taosMemoryFree(pHistory->hist[pHistory->hend]);
×
1030
    pHistory->hist[pHistory->hend] = taosStrdup(line);
×
1031

1032
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
×
1033

1034
    if (pHistory->hend == pHistory->hstart) {
×
1035
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
×
1036
    }
1037
  }
1038

1039
  taosMemoryFreeClear(line);
×
1040
  taosCloseFile(&pFile);
×
1041
  int64_t file_size;
1042
  if (taosStatFile(pHistory->file, &file_size, NULL, NULL) == 0 && file_size > SHELL_MAX_COMMAND_SIZE) {
×
1043
    TdFilePtr pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_TRUNC);
×
1044
    if (pFile == NULL) return;
×
1045
    int32_t endIndex = pHistory->hstart;
×
1046
    if (endIndex != 0) {
×
1047
      endIndex = pHistory->hend;
×
1048
    }
1049
    for (int32_t i = (pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE; i != endIndex;) {
×
1050
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
×
1051
      i = (i + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE;
×
1052
    }
1053
    taosFprintfFile(pFile, "%s\n", pHistory->hist[endIndex]);
×
1054

1055
    /* coverity[+retval] */
1056
    taosFsyncFile(pFile);
×
1057
    taosCloseFile(&pFile);
×
1058
  }
1059
  pHistory->hstart = pHistory->hend;
×
1060
}
1061

1062
void shellWriteHistory() {
×
1063
  SShellHistory *pHistory = &shell.history;
×
1064
  if (pHistory->hend == pHistory->hstart) return;
×
1065
  TdFilePtr pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_APPEND);
×
1066
  if (pFile == NULL) return;
×
1067

1068
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
×
1069
    if (pHistory->hist[i] != NULL) {
×
1070
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
×
1071
      taosMemoryFree(pHistory->hist[i]);
×
1072
      pHistory->hist[i] = NULL;
×
1073
    }
1074
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
×
1075
  }
1076
  taosCloseFile(&pFile);
×
1077
}
1078

1079
void shellCleanupHistory() {
×
1080
  SShellHistory *pHistory = &shell.history;
×
1081
  for (int32_t i = 0; i < SHELL_MAX_HISTORY_SIZE; ++i) {
×
1082
    if (pHistory->hist[i] != NULL) {
×
1083
      taosMemoryFree(pHistory->hist[i]);
×
1084
      pHistory->hist[i] = NULL;
×
1085
    }
1086
  }
1087
}
×
1088

1089
void shellPrintError(TAOS_RES *tres, int64_t st) {
×
1090
  int64_t et = taosGetTimestampUs();
×
1091
  fprintf(stderr, "\r\nDB error: %s[0x%08X] (%.6fs)\r\n", taos_errstr(tres), taos_errno(tres), (et - st) / 1E6);
×
1092
  taos_free_result(tres);
×
1093
}
×
1094

1095
bool shellIsCommentLine(char *line) {
×
1096
  if (line == NULL) return true;
×
1097
  return shellRegexMatch(line, "^\\s*#.*", REG_EXTENDED);
×
1098
}
1099

1100
void shellSourceFile(const char *file) {
×
1101
  int32_t read_len = 0;
×
1102
  char   *cmd = taosMemoryCalloc(1, TSDB_MAX_ALLOWED_SQL_LEN + 1);
×
1103
  size_t  cmd_len = 0;
×
1104
  char    fullname[PATH_MAX] = {0};
×
1105
  char    sourceFileCommand[PATH_MAX + 8] = {0};
×
1106

1107
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
×
1108
    tstrncpy(fullname, file, PATH_MAX);
×
1109
  }
1110

1111
  sprintf(sourceFileCommand, "source %s;", fullname);
×
1112
  shellRecordCommandToHistory(sourceFileCommand);
×
1113

1114
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_READ | TD_FILE_STREAM);
×
1115
  if (pFile == NULL) {
×
1116
    fprintf(stderr, "failed to open file %s\r\n", fullname);
×
1117
    taosMemoryFree(cmd);
×
1118
    return;
×
1119
  }
1120

1121
  char *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
×
1122
  while ((read_len = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) > 0) {
×
1123
    if (cmd_len + read_len >= TSDB_MAX_ALLOWED_SQL_LEN) {
×
1124
      printf("read command line too long over 1M, ignore this line. cmd_len = %d read_len=%d \n", (int32_t)cmd_len,
×
1125
             read_len);
1126
      cmd_len = 0;
×
1127
      memset(line, 0, TSDB_MAX_ALLOWED_SQL_LEN + 1);
×
1128
      continue;
×
1129
    }
1130
    line[--read_len] = '\0';
×
1131

1132
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
×
1133
      continue;
×
1134
    }
1135

1136
    if (line[read_len - 1] == '\\') {
×
1137
      line[read_len - 1] = ' ';
×
1138
      memcpy(cmd + cmd_len, line, read_len);
×
1139
      cmd_len += read_len;
×
1140
      continue;
×
1141
    }
1142

1143
    if (line[read_len - 1] == '\r') {
×
1144
      line[read_len - 1] = ' ';
×
1145
    }
1146

1147
    memcpy(cmd + cmd_len, line, read_len);
×
1148
    printf("%s%s\r\n", shell.info.promptHeader, cmd);
×
1149
    shellRunCommand(cmd, false);
×
1150
    memset(cmd, 0, TSDB_MAX_ALLOWED_SQL_LEN);
×
1151
    cmd_len = 0;
×
1152
  }
1153

1154
  taosMemoryFree(cmd);
×
1155
  taosMemoryFreeClear(line);
×
1156
  taosCloseFile(&pFile);
×
1157
}
1158

1159
int32_t shellGetGrantInfo(char *buf) {
×
1160
  int32_t verType = TSDB_VERSION_UNKNOWN;
×
1161
  char    sinfo[256] = {0};
×
1162
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
×
1163
  strtok(sinfo, "\r\n");
×
1164

1165
  char sql[] = "show grants";
×
1166

1167
  TAOS_RES *tres = taos_query(shell.conn, sql);
×
1168

1169
  int32_t code = taos_errno(tres);
×
1170
  if (code != TSDB_CODE_SUCCESS) {
×
1171
    if (code != TSDB_CODE_OPS_NOT_SUPPORT && code != TSDB_CODE_MND_NO_RIGHTS &&
×
1172
        code != TSDB_CODE_PAR_PERMISSION_DENIED) {
1173
      fprintf(stderr, "Failed to check Server Edition, Reason:0x%04x:%s\r\n\r\n", code, taos_errstr(tres));
×
1174
    }
1175
    taos_free_result(tres);
×
1176
    return verType;
×
1177
  }
1178

1179
  int32_t num_fields = taos_field_count(tres);
×
1180
  if (num_fields == 0) {
×
1181
    fprintf(stderr, "\r\nInvalid grant information.\r\n");
×
1182
    exit(0);
×
1183
  } else {
1184
    if (tres == NULL) {
×
1185
      fprintf(stderr, "\r\nGrant information is null.\r\n");
×
1186
      exit(0);
×
1187
    }
1188

1189
    TAOS_FIELD *fields = taos_fetch_fields(tres);
×
1190
    TAOS_ROW    row = taos_fetch_row(tres);
×
1191
    if (row == NULL) {
×
1192
      fprintf(stderr, "\r\nFailed to get grant information from server. Abort.\r\n");
×
1193
      exit(0);
×
1194
    }
1195
    char serverVersion[64] = {0};
×
1196
    char expiretime[32] = {0};
×
1197
    char expired[32] = {0};
×
1198

1199
    tstrncpy(serverVersion, row[0], 64);
×
1200
    memcpy(expiretime, row[1], fields[1].bytes);
×
1201
    memcpy(expired, row[2], fields[2].bytes);
×
1202

1203
    if (strcmp(serverVersion, "community") == 0) {
×
1204
      verType = TSDB_VERSION_OSS;
×
1205
    } else if (strcmp(expiretime, "unlimited") == 0) {
×
1206
      verType = TSDB_VERSION_ENTERPRISE;
×
1207
      sprintf(buf, "Server is %s, %s and will never expire.\r\n", serverVersion, sinfo);
×
1208
    } else {
1209
      verType = TSDB_VERSION_ENTERPRISE;
×
1210
      sprintf(buf, "Server is %s, %s and will expire at %s.\r\n", serverVersion, sinfo, expiretime);
×
1211
    }
1212

1213
    taos_free_result(tres);
×
1214
  }
1215

1216
  fprintf(stdout, "\r\n");
×
1217
  return verType;
×
1218
}
1219

1220
#ifdef WINDOWS
1221
BOOL shellQueryInterruptHandler(DWORD fdwCtrlType) {
1222
  tsem_post(&shell.cancelSem);
1223
  return TRUE;
1224
}
1225
#else
1226
void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) { tsem_post(&shell.cancelSem); }
×
1227
#endif
1228

1229
void shellCleanup(void *arg) { taosResetTerminalMode(); }
×
1230

1231
void *shellCancelHandler(void *arg) {
×
1232
  setThreadName("shellCancelHandler");
×
1233
  while (1) {
1234
    if (shell.exit == true) {
×
1235
      break;
×
1236
    }
1237

1238
    if (tsem_wait(&shell.cancelSem) != 0) {
×
1239
      taosMsleep(10);
×
1240
      continue;
×
1241
    }
1242

1243
#ifdef WEBSOCKET
1244
    if (shell.args.restful || shell.args.cloud) {
×
1245
      shell.stop_query = true;
×
1246
    } else {
1247
#endif
1248
      if (shell.conn) {
×
1249
        shellCmdkilled = true;
×
1250
        taos_kill_query(shell.conn);
×
1251
      }
1252
#ifdef WEBSOCKET
1253
    }
1254
#endif
1255
#ifdef WINDOWS
1256
    printf("\n%s", shell.info.promptHeader);
1257
#endif
1258
  }
1259

1260
  return NULL;
×
1261
}
1262

1263
#pragma GCC diagnostic push
1264
#pragma GCC diagnostic ignored "-Wstringop-overflow"
1265

1266
void *shellThreadLoop(void *arg) {
×
1267
  setThreadName("shellThreadLoop");
×
1268
  taosGetOldTerminalMode();
×
1269
  taosThreadCleanupPush(shellCleanup, NULL);
×
1270

1271
  do {
1272
    char *command = taosMemoryMalloc(SHELL_MAX_COMMAND_SIZE);
×
1273
    if (command == NULL) {
×
1274
      printf("failed to malloc command\r\n");
×
1275
      break;
×
1276
    }
1277

1278
    do {
1279
      memset(command, 0, SHELL_MAX_COMMAND_SIZE);
×
1280
      taosSetTerminalMode();
×
1281

1282
      if (shellReadCommand(command) != 0) {
×
1283
        break;
×
1284
      }
1285

1286
      taosResetTerminalMode();
×
1287
    } while (shellRunCommand(command, true) == 0);
×
1288

1289
    taosMemoryFreeClear(command);
×
1290
    shellWriteHistory();
×
1291
    shellExit();
×
1292
  } while (0);
1293

1294
  taosThreadCleanupPop(1);
×
1295
  return NULL;
×
1296
}
1297
#pragma GCC diagnostic pop
1298

1299
int32_t shellExecute() {
3✔
1300
  printf(shell.info.clientVersion, shell.info.cusName, taos_get_client_info(), shell.info.cusName);
3✔
1301
  fflush(stdout);
3✔
1302

1303
  SShellArgs *pArgs = &shell.args;
3✔
1304
#ifdef WEBSOCKET
1305
  if (shell.args.restful || shell.args.cloud) {
3!
1306
    if (shell_conn_ws_server(1)) {
×
1307
      printf("failed to connect to server, reason: %s[0x%08X]\n%s", ws_errstr(NULL), ws_errno(NULL), ERROR_CODE_DETAIL);
×
1308
      fflush(stdout);
×
1309
      return -1;
×
1310
    }
1311
  } else {
1312
#endif
1313
    if (shell.args.auth == NULL) {
3!
1314
      shell.conn = taos_connect(pArgs->host, pArgs->user, pArgs->password, pArgs->database, pArgs->port);
3✔
1315
    } else {
1316
      shell.conn = taos_connect_auth(pArgs->host, pArgs->user, pArgs->auth, pArgs->database, pArgs->port);
×
1317
    }
1318

1319
    if (shell.conn == NULL) {
3!
1320
      printf("failed to connect to server, reason: %s[0x%08X]\n%s", taos_errstr(NULL), taos_errno(NULL), ERROR_CODE_DETAIL);
3✔
1321
      fflush(stdout);
3✔
1322
      return -1;
3✔
1323
    }
1324
#ifdef WEBSOCKET
1325
  }
1326
#endif
1327

1328
  bool runOnce = pArgs->commands != NULL || pArgs->file[0] != 0;
×
1329
  shellSetConn(shell.conn, runOnce);
×
1330
  shellReadHistory();
×
1331

1332
  if (shell.args.is_bi_mode) {
×
1333
    // need set bi mode
1334
    printf("Set BI mode is true.\n");
×
1335
#ifndef WEBSOCKET
1336
    taos_set_conn_mode(shell.conn, TAOS_CONN_MODE_BI, 1);
1337
#endif
1338
  }
1339

1340
  if (runOnce) {
×
1341
    if (pArgs->commands != NULL) {
×
1342
      printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
×
1343
      char *cmd = taosStrdup(pArgs->commands);
×
1344
      shellRunCommand(cmd, true);
×
1345
      taosMemoryFree(cmd);
×
1346
    }
1347

1348
    if (pArgs->file[0] != 0) {
×
1349
      shellSourceFile(pArgs->file);
×
1350
    }
1351
#ifdef WEBSOCKET
1352
    if (shell.args.restful || shell.args.cloud) {
×
1353
      ws_close(shell.ws_conn);
×
1354
    } else {
1355
#endif
1356
      taos_close(shell.conn);
×
1357
#ifdef WEBSOCKET
1358
    }
1359
#endif
1360

1361
    shellWriteHistory();
×
1362
    shellCleanupHistory();
×
1363
    return 0;
×
1364
  }
1365

1366
  if (tsem_init(&shell.cancelSem, 0, 0) != 0) {
×
1367
    printf("failed to create cancel semaphore\r\n");
×
1368
    return -1;
×
1369
  }
1370

1371
  TdThread spid = {0};
×
1372
  taosThreadCreate(&spid, NULL, shellCancelHandler, NULL);
×
1373

1374
  taosSetSignal(SIGTERM, shellQueryInterruptHandler);
×
1375
  taosSetSignal(SIGHUP, shellQueryInterruptHandler);
×
1376
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
×
1377

1378
#ifdef WEBSOCKET
1379
  if (!shell.args.restful && !shell.args.cloud) {
×
1380
#endif
1381
    char    buf[512] = {0};
×
1382
    int32_t verType = shellGetGrantInfo(buf);
×
1383
#ifndef WINDOWS
1384
    printfIntroduction(verType);
×
1385
#else
1386
#ifndef WEBSOCKET
1387
  if (verType == TSDB_VERSION_OSS) {
1388
    showAD(false);
1389
  }
1390
#endif
1391
#endif
1392
    // printf version
1393
    if (verType == TSDB_VERSION_ENTERPRISE || verType == TSDB_VERSION_CLOUD) {
×
1394
      printf("%s\n", buf);
×
1395
    }
1396

1397
#ifdef WEBSOCKET
1398
  }
1399
#endif
1400
  while (1) {
1401
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, NULL);
×
1402
    taosThreadJoin(shell.pid, NULL);
×
1403
    taosThreadClear(&shell.pid);
×
1404
    if (shell.exit) {
×
1405
      tsem_post(&shell.cancelSem);
×
1406
      break;
×
1407
    }
1408
  }
1409
#ifndef WEBSOCKET
1410
  // commnuity
1411
  if (verType == TSDB_VERSION_OSS) {
1412
    showAD(true);
1413
  }
1414
#endif
1415

1416
  taosThreadJoin(spid, NULL);
×
1417

1418
  shellCleanupHistory();
×
1419
  taos_kill_query(shell.conn);
×
1420
  taos_close(shell.conn);
×
1421

1422
  return 0;
×
1423
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc