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

taosdata / TDengine / #3796

31 Mar 2025 10:39AM UTC coverage: 30.372% (-7.1%) from 37.443%
#3796

push

travis-ci

happyguoxy
test:add test cases

69287 of 309062 branches covered (22.42%)

Branch coverage included in aggregate %.

118044 of 307720 relevant lines covered (38.36%)

278592.15 hits per line

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

46.95
/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
#include "../../inc/pub.h"
25

26
SShellObj shell = {0};
27

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

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

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

42
  uint64_t resShowMaxNum;
43
} tsDumpInfo;
44

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

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

68
static bool shellCmdkilled = false;
69

70
bool shellIsEmptyCommand(const char *cmd) {
10,603✔
71
  for (char c = *cmd++; c != 0; c = *cmd++) {
10,603✔
72
    if (c != ' ' && c != '\t' && c != ';') {
7,086!
73
      return false;
7,086✔
74
    }
75
  }
76
  return true;
3,517✔
77
}
78

79
int32_t shellRunSingleCommand(char *command) {
7,060✔
80
  shellCmdkilled = false;
7,060✔
81

82
  if (shellIsEmptyCommand(command)) {
7,060✔
83
    return 0;
3,517✔
84
  }
85

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

90
  if (shellRegexMatch(command, "^[\t ]*clear[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
3,543!
91
#pragma GCC diagnostic push
92
#pragma GCC diagnostic ignored "-Wunused-result"
93
#ifndef TD_ASTRA
94
    system("clear");
×
95
#else
96
    printf("\033[2J\033[H");
97
#endif
98
#pragma GCC diagnostic pop
99
    return 0;
×
100
  }
101

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

117
  if (shellRegexMatch(command, "^[ \t]*source[\t ]+[^ ]+[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
3,543!
118
    /* If source file. */
119
    char *c_ptr = strtok(command, " ;");
×
120
    if (c_ptr == NULL) {
×
121
      shellRunSingleCommandImp(command);
×
122
      return 0;
×
123
    }
124
    c_ptr = strtok(NULL, " ;");
×
125
    if (c_ptr == NULL) {
×
126
      shellRunSingleCommandImp(command);
×
127
      return 0;
×
128
    }
129
    shellSourceFile(c_ptr);
×
130
    return 0;
×
131
  }
132
  shellRunSingleCommandImp(command);
3,543✔
133
  return 0;
3,543✔
134
}
135

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

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

153
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
62✔
154
    if (pHistory->hend == pHistory->hstart) {
62!
155
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
×
156
    }
157
  }
158
}
159

160
int32_t shellRunCommand(char *command, bool recordHistory) {
3,543✔
161
  if (shellIsEmptyCommand(command)) {
3,543!
162
    return 0;
×
163
  }
164

165
  // add help or help;
166
  if (strncasecmp(command, "help", 4) == 0) {
3,543!
167
    if (command[4] == ';' || command[4] == ' ' || command[4] == 0) {
×
168
      showHelp();
×
169
      return 0;
×
170
    }
171
  }
172

173
  if (recordHistory) shellRecordCommandToHistory(command);
3,543✔
174

175
  char quote = 0, *cmd = command;
3,543✔
176
  for (char c = *command++; c != 0; c = *command++) {
586,319✔
177
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
582,776!
178
      command++;
×
179
      continue;
×
180
    }
181

182
    if (quote == c) {
582,776✔
183
      quote = 0;
369✔
184
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
582,407✔
185
      quote = c;
369✔
186
    } else if (c == ';' && quote == 0) {
582,038!
187
      c = *command;
3,517✔
188
      *command = 0;
3,517✔
189
      if (shellRunSingleCommand(cmd) < 0) {
3,517!
190
        return -1;
×
191
      }
192
      *command = c;
3,517✔
193
      cmd = command;
3,517✔
194
    }
195
  }
196
  return shellRunSingleCommand(cmd);
3,543✔
197
}
198

199
char *strendG(const char *pstr) {
3,543✔
200
  if (pstr == NULL) {
3,543!
201
    return NULL;
×
202
  }
203

204
  size_t len = strlen(pstr);
3,543✔
205
  if (len < 4) {
3,543!
206
    return NULL;
×
207
  }
208

209
  char *p = (char *)pstr + len - 2;
3,543✔
210
  if (strcmp(p, "\\G") == 0) {
3,543!
211
    return p;
×
212
  }
213

214
  p = (char *)pstr + len - 3;
3,543✔
215
  if (strcmp(p, "\\G;") == 0) {
3,543✔
216
    return p;
2✔
217
  }
218

219
  return NULL;
3,541✔
220
}
221

222
void shellRunSingleCommandImp(char *command) {
3,543✔
223
  int64_t st, et;
224
  char   *sptr = NULL;
3,543✔
225
  char   *cptr = NULL;
3,543✔
226
  char   *fname = NULL;
3,543✔
227
  bool    printMode = false;
3,543✔
228

229
  if ((sptr = strstr(command, ">>")) != NULL) {
3,543!
230
    fname = sptr + 2;
×
231
    while (*fname == ' ') fname++;
×
232
    *sptr = '\0';
×
233

234
    cptr = strstr(fname, ";");
×
235
    if (cptr != NULL) {
×
236
      *cptr = '\0';
×
237
    }
238
  }
239

240
  if ((sptr = strendG(command)) != NULL) {
3,543✔
241
    *sptr = '\0';
2✔
242
    printMode = true;  // When output to a file, the switch does not work.
2✔
243
  }
244

245
  st = taosGetTimestampUs();
3,543✔
246

247
  TAOS_RES *pSql = taos_query(shell.conn, command);
3,543✔
248
  if (taos_errno(pSql)) {
3,543✔
249
    shellPrintError(pSql, st);
25✔
250
    return;
25✔
251
  }
252

253
  if (shellRegexMatch(command, "^\\s*use\\s+[a-zA-Z0-9_]+\\s*;\\s*$", REG_EXTENDED | REG_ICASE)) {
3,518!
254
    printf("Database changed.\r\n\r\n");
×
255

256
    // call back auto tab module
257
    callbackAutoTab(command, pSql, true);
×
258

259
    taos_free_result(pSql);
×
260

261
    return;
×
262
  }
263

264
  // pre string
265
  char *pre = "Query OK";
3,518✔
266
  if (shellRegexMatch(command, "^\\s*delete\\s*from\\s*.*", REG_EXTENDED | REG_ICASE)) {
3,518!
267
    pre = "Delete OK";
×
268
  } else if (shellRegexMatch(command, "^\\s*insert\\s*into\\s*.*", REG_EXTENDED | REG_ICASE)) {
3,518!
269
    pre = "Insert OK";
×
270
  } else if (shellRegexMatch(command, "^\\s*create\\s*.*", REG_EXTENDED | REG_ICASE)) {
3,518✔
271
    pre = "Create OK";
2✔
272
  } else if (shellRegexMatch(command, "^\\s*drop\\s*.*", REG_EXTENDED | REG_ICASE)) {
3,516!
273
    pre = "Drop OK";
×
274
  }
275

276
  TAOS_FIELD *pFields = taos_fetch_fields(pSql);
3,518✔
277
  if (pFields != NULL) {  // select and show kinds of commands
3,518✔
278
    int32_t error_no = 0;
3,516✔
279

280
    int64_t numOfRows = shellDumpResult(pSql, fname, &error_no, printMode, command);
3,516✔
281
    if (numOfRows < 0) return;
3,516!
282

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

297
    // call auto tab
298
    callbackAutoTab(command, NULL, false);
2✔
299
  }
300

301
  printf("\r\n");
3,518✔
302
}
303

304
char *shellFormatTimestamp(char *buf, int32_t bufSize, int64_t val, int32_t precision) {
420,690✔
305
  if (shell.args.is_raw_time) {
420,690!
306
    sprintf(buf, "%" PRId64, val);
×
307
    return buf;
×
308
  }
309

310
  time_t  tt;
311
  int32_t ms = 0;
420,690✔
312
  if (precision == TSDB_TIME_PRECISION_NANO) {
420,690!
313
    tt = (time_t)(val / 1000000000);
×
314
    ms = val % 1000000000;
×
315
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
420,690!
316
    tt = (time_t)(val / 1000000);
×
317
    ms = val % 1000000;
×
318
  } else {
319
    tt = (time_t)(val / 1000);
420,690✔
320
    ms = val % 1000;
420,690✔
321
  }
322

323
  if (tt <= 0 && ms < 0) {
420,690!
324
    tt--;
×
325
    if (precision == TSDB_TIME_PRECISION_NANO) {
×
326
      ms += 1000000000;
×
327
    } else if (precision == TSDB_TIME_PRECISION_MICRO) {
×
328
      ms += 1000000;
×
329
    } else {
330
      ms += 1000;
×
331
    }
332
  }
333

334
  struct tm ptm = {0};
420,690✔
335
  if (taosLocalTime(&tt, &ptm, buf, bufSize, NULL) == NULL) {
420,690!
336
    return buf;
×
337
  }
338
  size_t pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
420,690✔
339

340
  if (precision == TSDB_TIME_PRECISION_NANO) {
420,690!
341
    sprintf(buf + pos, ".%09d", ms);
×
342
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
420,690!
343
    sprintf(buf + pos, ".%06d", ms);
×
344
  } else {
345
    sprintf(buf + pos, ".%03d", ms);
420,690✔
346
  }
347

348
  return buf;
420,690✔
349
}
350

351
char *shellDumpHexValue(char *buf, const char *val, int32_t length) {
×
352
  for (int32_t i = 0; i < length; i++) {
×
353
    sprintf(buf + (i * 2), "%02X", val[i]);
×
354
  }
355
  buf[length * 2] = 0;
×
356

357
  return buf;
×
358
}
359

360
void shellDumpFieldToFile(TdFilePtr pFile, const char *val, TAOS_FIELD *field, int32_t length, int32_t precision) {
×
361
  if (val == NULL) {
×
362
    taosFprintfFile(pFile, "NULL");
×
363
    return;
×
364
  }
365

366
  char    quotationStr[2] = {'"', 0};
×
367
  int32_t width;
368

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

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

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

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

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

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

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

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

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

520
  taosCloseFile(&pFile);
×
521

522
  return numOfRows;
×
523
}
524

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

529
  while (pos < length) {
5,811,881✔
530
    TdWchar wc;
531
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
5,433,586✔
532
    if (bytes <= 0) {
5,433,586✔
533
      break;
781✔
534
    }
535

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

547
    if (w <= 0) {
5,433,476✔
548
      continue;
1,751✔
549
    }
550

551
    if (width <= 0) {
5,433,440✔
552
      printf("%lc", wc);
1,715✔
553
      continue;
1,715✔
554
    }
555

556
    totalCols += w;
5,431,725✔
557
    if (totalCols > width) {
5,431,725✔
558
      break;
671✔
559
    }
560
    if (totalCols <= (width - 3)) {
5,431,054✔
561
      printf("%lc", wc);
5,428,806✔
562
      cols += w;
5,428,806✔
563
    } else {
564
      tail[tailLen] = wc;
2,248✔
565
      tailLen++;
2,248✔
566
    }
567
  }
568

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

585
  for (; cols < width; cols++) {
5,050,987✔
586
    putchar(' ');
4,671,911✔
587
  }
588
}
379,076✔
589

590
void shellPrintString(const char *str, int32_t width) {
1,613,960✔
591
  int32_t len = strlen(str);
1,613,960✔
592

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

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

612
  int32_t code = TSDB_CODE_FAILED;
×
613

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

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

627
  shellPrintString(outputWKT, width);
×
628

629
  geosFreeBuffer(outputWKT);
×
630
}
631

632
void shellPrintField(const char *val, TAOS_FIELD *field, int32_t width, int32_t length, int32_t precision) {
3,480,962✔
633
  if (val == NULL) {
3,480,962✔
634
    shellPrintString(TSDB_DATA_NULL_STR, width);
1,500,871✔
635
    return;
1,500,871✔
636
  }
637

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

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

741
  return false;
×
742
}
743

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

750
  return false;
×
751
}
752

753
void init_dump_info(tsDumpInfo *dump_info, TAOS_RES *tres, const char *sql, bool vertical) {
3,516✔
754
  dump_info->sql = sql;
3,516✔
755
  dump_info->vertical = vertical;
3,516✔
756
  tsem_init(&dump_info->sem, 0, 0);
3,516✔
757
  dump_info->numOfAllRows = 0;
3,516✔
758

759
  dump_info->numFields = taos_num_fields(tres);
3,516✔
760
  dump_info->fields = taos_fetch_fields(tres);
3,516✔
761
  dump_info->precision = taos_result_precision(tres);
3,516✔
762

763
  dump_info->resShowMaxNum = UINT64_MAX;
3,516✔
764

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

769
  if (vertical) {
3,516✔
770
    dump_info->maxColNameLen = 0;
2✔
771
    for (int32_t col = 0; col < dump_info->numFields; col++) {
6✔
772
      int32_t len = (int32_t)strlen(dump_info->fields[col].name);
4✔
773
      if (len > dump_info->maxColNameLen) {
4!
774
        dump_info->maxColNameLen = len;
4✔
775
      }
776
    }
777
  } else {
778
    for (int32_t col = 0; col < dump_info->numFields; col++) {
22,328✔
779
      dump_info->width[col] = shellCalcColWidth(dump_info->fields + col, dump_info->precision);
18,814✔
780
    }
781
  }
782
}
3,516✔
783

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

791
  int64_t numOfPintRows = dump_info->numOfAllRows;
2✔
792
  int     numOfPrintRowsThisOne = 0;
2✔
793

794
  while (row != NULL) {
2!
795
    printf("*************************** %" PRId64 ".row ***************************\r\n", numOfPintRows + 1);
2✔
796

797
    int32_t *length = taos_fetch_lengths(tres);
2✔
798

799
    for (int32_t i = 0; i < dump_info->numFields; i++) {
6✔
800
      TAOS_FIELD *field = dump_info->fields + i;
4✔
801

802
      int32_t padding = (int32_t)(dump_info->maxColNameLen - strlen(field->name));
4✔
803
      printf("%*.s%s: ", padding, " ", field->name);
4✔
804

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

810
    numOfPintRows++;
2✔
811
    numOfPrintRowsThisOne++;
2✔
812

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

824
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
2!
825
      return;
2✔
826
    }
827

828
    row = taos_fetch_row(tres);
×
829
  }
830
  return;
×
831
}
832

833
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
18,814✔
834
  int32_t width = (int32_t)strlen(field->name);
18,814✔
835

836
  switch (field->type) {
18,814!
837
    case TSDB_DATA_TYPE_NULL:
×
838
      return TMAX(4, width);  // null
×
839
    case TSDB_DATA_TYPE_BOOL:
1,015✔
840
      return TMAX(5, width);  // 'false'
1,015✔
841

842
    case TSDB_DATA_TYPE_TINYINT:
2,509✔
843
    case TSDB_DATA_TYPE_UTINYINT:
844
      return TMAX(4, width);  // '-127'
2,509✔
845

846
    case TSDB_DATA_TYPE_SMALLINT:
2,087✔
847
    case TSDB_DATA_TYPE_USMALLINT:
848
      return TMAX(6, width);  // '-32767'
2,087✔
849

850
    case TSDB_DATA_TYPE_INT:
1,992✔
851
    case TSDB_DATA_TYPE_UINT:
852
      return TMAX(11, width);  // '-2147483648'
1,992✔
853

854
    case TSDB_DATA_TYPE_BIGINT:
2,649✔
855
    case TSDB_DATA_TYPE_UBIGINT:
856
      return TMAX(21, width);  // '-9223372036854775807'
2,649✔
857

858
    case TSDB_DATA_TYPE_FLOAT:
886✔
859
      return TMAX(SHELL_FLOAT_WIDTH, width);
886✔
860

861
    case TSDB_DATA_TYPE_DOUBLE:
1,971✔
862
      return TMAX(SHELL_DOUBLE_WIDTH, width);
1,971✔
863

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

889
    case TSDB_DATA_TYPE_TIMESTAMP:
2,225✔
890
      if (shell.args.is_raw_time) {
2,225!
891
        return TMAX(14, width);
×
892
      }
893
      if (precision == TSDB_TIME_PRECISION_NANO) {
2,225!
894
        return TMAX(29, width);
×
895
      } else if (precision == TSDB_TIME_PRECISION_MICRO) {
2,225!
896
        return TMAX(26, width);  // '2020-01-01 00:00:00.000000'
×
897
      } else {
898
        return TMAX(23, width);  // '2020-01-01 00:00:00.000'
2,225✔
899
      }
900
    case TSDB_DATA_TYPE_DECIMAL64:
×
901
      return TMAX(width, 20);
×
902
    case TSDB_DATA_TYPE_DECIMAL:
×
903
      return TMAX(width, 40);
×
904
    default:
×
905
      ASSERT(false);
×
906
  }
907

908
  return 0;
×
909
}
910

911
void shellPrintHeader(TAOS_FIELD *fields, int32_t *width, int32_t num_fields) {
3,319✔
912
  int32_t rowWidth = 0;
3,319✔
913
  for (int32_t col = 0; col < num_fields; col++) {
20,502✔
914
    TAOS_FIELD *field = fields + col;
17,183✔
915
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
17,183✔
916
    int32_t     left = padding / 2;
17,183✔
917
    printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
17,183✔
918
    rowWidth += width[col] + 3;
17,183✔
919
  }
920

921
  putchar('\r');
3,319✔
922
  putchar('\n');
3,319✔
923
  for (int32_t i = 0; i < rowWidth; i++) {
401,912✔
924
    putchar('=');
398,593✔
925
  }
926
  putchar('\r');
3,319✔
927
  putchar('\n');
3,319✔
928
}
3,319✔
929

930
void shellHorizontalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
5,165✔
931
  TAOS_ROW row = taos_fetch_row(tres);
5,165✔
932
  if (row == NULL) {
5,165!
933
    printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
934
    return;
×
935
  }
936

937
  int64_t numOfPintRows = dump_info->numOfAllRows;
5,165✔
938
  int     numOfPrintRowsThisOne = 0;
5,165✔
939
  if (numOfPintRows == 0) {
5,165✔
940
    shellPrintHeader(dump_info->fields, dump_info->width, dump_info->numFields);
3,319✔
941
  }
942

943
  while (row != NULL) {
470,305!
944
    int32_t *length = taos_fetch_lengths(tres);
470,305✔
945
    for (int32_t i = 0; i < dump_info->numFields; i++) {
3,951,263✔
946
      putchar(' ');
3,480,958✔
947
      shellPrintField((const char *)row[i], dump_info->fields + i, dump_info->width[i], length[i],
3,480,958✔
948
                      dump_info->precision);
949
      putchar(' ');
3,480,958✔
950
      putchar('|');
3,480,958✔
951
    }
952
    putchar('\r');
470,305✔
953
    putchar('\n');
470,305✔
954

955
    numOfPintRows++;
470,305✔
956
    numOfPrintRowsThisOne++;
470,305✔
957

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

973
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
470,305✔
974
      return;
5,165✔
975
    }
976

977
    row = taos_fetch_row(tres);
465,140✔
978
  }
979
  return;
×
980
}
981

982
void shellDumpResultCallback(void *param, TAOS_RES *tres, int num_of_rows) {
8,683✔
983
  tsDumpInfo *dump_info = (tsDumpInfo *)param;
8,683✔
984
  if (num_of_rows > 0) {
8,683✔
985
    dump_info->numOfRows = num_of_rows;
5,167✔
986
    if (dump_info->numOfAllRows < dump_info->resShowMaxNum) {
5,167!
987
      if (dump_info->vertical) {
5,167✔
988
        shellVerticalPrintResult(tres, dump_info);
2✔
989
      } else {
990
        shellHorizontalPrintResult(tres, dump_info);
5,165✔
991
      }
992
    }
993
    dump_info->numOfAllRows += num_of_rows;
5,167✔
994
    if (!shellCmdkilled) {
5,167!
995
      taos_fetch_rows_a(tres, shellDumpResultCallback, param);
5,167✔
996
    } else {
997
      tsem_post(&dump_info->sem);
×
998
    }
999
  } else {
1000
    if (num_of_rows < 0) {
3,516!
1001
      printf("\033[31masync retrieve failed, code: %d\033, %s[0m\n", num_of_rows, tstrerror(num_of_rows));
×
1002
    }
1003
    tsem_post(&dump_info->sem);
3,516✔
1004
  }
1005
}
8,683✔
1006

1007
int64_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
3,516✔
1008
  int64_t num_of_rows = 0;
3,516✔
1009
  if (fname != NULL) {
3,516!
1010
    num_of_rows = shellDumpResultToFile(fname, tres);
×
1011
  } else {
1012
    tsDumpInfo dump_info;
1013
    if (!shellCmdkilled) {
3,516!
1014
      init_dump_info(&dump_info, tres, sql, vertical);
3,516✔
1015
      taos_fetch_rows_a(tres, shellDumpResultCallback, &dump_info);
3,516✔
1016
      tsem_wait(&dump_info.sem);
3,516✔
1017
      num_of_rows = dump_info.numOfAllRows;
3,516✔
1018
    }
1019
  }
1020

1021
  *error_no = shellCmdkilled ? TSDB_CODE_TSC_QUERY_KILLED : taos_errno(tres);
3,516!
1022
  return num_of_rows;
3,516✔
1023
}
1024

1025
void shellReadHistory() {
62✔
1026
  SShellHistory *pHistory = &shell.history;
62✔
1027
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_READ | TD_FILE_STREAM);
62✔
1028
  if (pFile == NULL) return;
62!
1029

1030
  char   *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
62!
1031
  int32_t read_size = 0;
62✔
1032
  while ((read_size = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) > 0) {
654,627✔
1033
    line[read_size - 1] = '\0';
654,565✔
1034
    taosMemoryFree(pHistory->hist[pHistory->hend]);
654,565!
1035
    pHistory->hist[pHistory->hend] = taosStrdup(line);
654,565!
1036

1037
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
654,565✔
1038

1039
    if (pHistory->hend == pHistory->hstart) {
654,565✔
1040
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
592,627✔
1041
    }
1042
  }
1043

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

1060
    /* coverity[+retval] */
1061
    taosFsyncFile(pFile);
×
1062
    taosCloseFile(&pFile);
×
1063
  }
1064
  pHistory->hstart = pHistory->hend;
62✔
1065
}
1066

1067
void shellWriteHistory() {
62✔
1068
  SShellHistory *pHistory = &shell.history;
62✔
1069
  if (pHistory->hend == pHistory->hstart) return;
62!
1070
  TdFilePtr pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_APPEND);
62✔
1071
  if (pFile == NULL) return;
62!
1072

1073
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
124✔
1074
    if (pHistory->hist[i] != NULL) {
62!
1075
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
62✔
1076
      taosMemoryFree(pHistory->hist[i]);
62!
1077
      pHistory->hist[i] = NULL;
62✔
1078
    }
1079
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
62✔
1080
  }
1081
  taosCloseFile(&pFile);
62✔
1082
}
1083

1084
void shellCleanupHistory() {
62✔
1085
  SShellHistory *pHistory = &shell.history;
62✔
1086
  for (int32_t i = 0; i < SHELL_MAX_HISTORY_SIZE; ++i) {
62,062✔
1087
    if (pHistory->hist[i] != NULL) {
62,000✔
1088
      taosMemoryFree(pHistory->hist[i]);
61,938!
1089
      pHistory->hist[i] = NULL;
61,938✔
1090
    }
1091
  }
1092
}
62✔
1093

1094
void shellPrintError(TAOS_RES *tres, int64_t st) {
25✔
1095
  int64_t et = taosGetTimestampUs();
25✔
1096
  fprintf(stderr, "\r\nDB error: %s [0x%08X] (%.6fs)\r\n", taos_errstr(tres), taos_errno(tres), (et - st) / 1E6);
25✔
1097
  taos_free_result(tres);
25✔
1098
}
25✔
1099

1100
bool shellIsCommentLine(char *line) {
3,538✔
1101
  if (line == NULL) return true;
3,538!
1102
  return shellRegexMatch(line, "^\\s*#.*", REG_EXTENDED);
3,538✔
1103
}
1104

1105
void shellSourceFile(const char *file) {
57✔
1106
  int32_t read_len = 0;
57✔
1107
  char   *cmd = taosMemoryCalloc(1, TSDB_MAX_ALLOWED_SQL_LEN + 1);
57!
1108
  size_t  cmd_len = 0;
57✔
1109
  char    fullname[PATH_MAX] = {0};
57✔
1110
  char    sourceFileCommand[PATH_MAX + 8] = {0};
57✔
1111

1112
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
57!
1113
    tstrncpy(fullname, file, PATH_MAX);
×
1114
  }
1115

1116
  sprintf(sourceFileCommand, "source %s;", fullname);
57✔
1117
  shellRecordCommandToHistory(sourceFileCommand);
57✔
1118

1119
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_READ | TD_FILE_STREAM);
57✔
1120
  if (pFile == NULL) {
57!
1121
    fprintf(stderr, "failed to open file %s\r\n", fullname);
×
1122
    taosMemoryFree(cmd);
×
1123
    return;
×
1124
  }
1125

1126
  char *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
57!
1127
  while ((read_len = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) > 0) {
3,828✔
1128
    if (cmd_len + read_len >= TSDB_MAX_ALLOWED_SQL_LEN) {
3,771!
1129
      printf("read command line too long over 1M, ignore this line. cmd_len = %d read_len=%d \n", (int32_t)cmd_len,
×
1130
             read_len);
1131
      cmd_len = 0;
×
1132
      memset(line, 0, TSDB_MAX_ALLOWED_SQL_LEN + 1);
×
1133
      continue;
×
1134
    }
1135
    line[--read_len] = '\0';
3,771✔
1136

1137
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
3,771!
1138
      continue;
233✔
1139
    }
1140

1141
    if (line[read_len - 1] == '\\') {
3,538!
1142
      line[read_len - 1] = ' ';
×
1143
      memcpy(cmd + cmd_len, line, read_len);
×
1144
      cmd_len += read_len;
×
1145
      continue;
×
1146
    }
1147

1148
    if (line[read_len - 1] == '\r') {
3,538!
1149
      line[read_len - 1] = ' ';
×
1150
    }
1151

1152
    memcpy(cmd + cmd_len, line, read_len);
3,538✔
1153
    printf("%s%s\r\n", shell.info.promptHeader, cmd);
3,538✔
1154
    shellRunCommand(cmd, false);
3,538✔
1155
    memset(cmd, 0, TSDB_MAX_ALLOWED_SQL_LEN);
3,538✔
1156
    cmd_len = 0;
3,538✔
1157
  }
1158

1159
  taosMemoryFree(cmd);
57!
1160
  taosMemoryFreeClear(line);
57!
1161
  taosCloseFile(&pFile);
57✔
1162
}
1163

1164
int32_t shellGetGrantInfo(char *buf) {
×
1165
  int32_t verType = TSDB_VERSION_UNKNOWN;
×
1166
  char    sinfo[256] = {0};
×
1167
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
×
1168
  strtok(sinfo, "\r\n");
×
1169

1170
#ifndef TD_ASTRA
1171
  char sql[] = "show grants";
×
1172

1173
  TAOS_RES *tres = taos_query(shell.conn, sql);
×
1174

1175
  int32_t code = taos_errno(tres);
×
1176
  if (code != TSDB_CODE_SUCCESS) {
×
1177
    if (code != TSDB_CODE_OPS_NOT_SUPPORT && code != TSDB_CODE_MND_NO_RIGHTS &&
×
1178
        code != TSDB_CODE_PAR_PERMISSION_DENIED) {
1179
      fprintf(stderr, "Failed to check Server Edition, Reason:0x%04x:%s\r\n\r\n", code, taos_errstr(tres));
×
1180
    }
1181
    taos_free_result(tres);
×
1182
    return verType;
×
1183
  }
1184

1185
  int32_t num_fields = taos_field_count(tres);
×
1186
  if (num_fields == 0) {
×
1187
    fprintf(stderr, "\r\nInvalid grant information.\r\n");
×
1188
    exit(0);
×
1189
  } else {
1190
    if (tres == NULL) {
×
1191
      fprintf(stderr, "\r\nGrant information is null.\r\n");
×
1192
      exit(0);
×
1193
    }
1194

1195
    TAOS_FIELD *fields = taos_fetch_fields(tres);
×
1196
    TAOS_ROW    row = taos_fetch_row(tres);
×
1197
    if (row == NULL) {
×
1198
      fprintf(stderr, "\r\nFailed to get grant information from server. Abort.\r\n");
×
1199
      exit(0);
×
1200
    }
1201
    char serverVersion[64] = {0};
×
1202
    char expiretime[32] = {0};
×
1203
    char expired[32] = {0};
×
1204

1205
    tstrncpy(serverVersion, row[0], 64);
×
1206
    memcpy(expiretime, row[1], fields[1].bytes);
×
1207
    memcpy(expired, row[2], fields[2].bytes);
×
1208

1209
    if (strcmp(serverVersion, "community") == 0) {
×
1210
      verType = TSDB_VERSION_OSS;
×
1211
    } else if (strcmp(expiretime, "unlimited") == 0) {
×
1212
      verType = TSDB_VERSION_ENTERPRISE;
×
1213
      sprintf(buf, "Server is %s, %s and will never expire.\r\n", serverVersion, sinfo);
×
1214
    } else {
1215
      verType = TSDB_VERSION_ENTERPRISE;
×
1216
      sprintf(buf, "Server is %s, %s and will expire at %s.\r\n", serverVersion, sinfo, expiretime);
×
1217
    }
1218

1219
    taos_free_result(tres);
×
1220
  }
1221

1222
  fprintf(stdout, "\r\n");
×
1223
#else
1224
  verType = TSDB_VERSION_ENTERPRISE;
1225
  sprintf(buf, "Server is %s, %s and will never expire.\r\n", TD_PRODUCT_NAME, sinfo);
1226
#endif
1227
  return verType;
×
1228
}
1229

1230
#ifdef WINDOWS
1231
BOOL shellQueryInterruptHandler(DWORD fdwCtrlType) {
1232
  tsem_post(&shell.cancelSem);
1233
  return TRUE;
1234
}
1235
#else
1236
void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) { tsem_post(&shell.cancelSem); }
×
1237
#endif
1238

1239
void shellCleanup(void *arg) { taosResetTerminalMode(); }
×
1240

1241
void *shellCancelHandler(void *arg) {
×
1242
  setThreadName("shellCancelHandler");
×
1243
  while (1) {
1244
    if (shell.exit == true) {
×
1245
      break;
×
1246
    }
1247

1248
    if (tsem_wait(&shell.cancelSem) != 0) {
×
1249
      taosMsleep(10);
×
1250
      continue;
×
1251
    }
1252

1253
    if (shell.conn) {
×
1254
      shellCmdkilled = true;
×
1255
      taos_kill_query(shell.conn);
×
1256
    }
1257

1258
#ifdef WINDOWS
1259
    printf("\n%s", shell.info.promptHeader);
1260
#endif
1261
  }
1262

1263
  return NULL;
×
1264
}
1265

1266
#pragma GCC diagnostic push
1267
#pragma GCC diagnostic ignored "-Wstringop-overflow"
1268

1269
void *shellThreadLoop(void *arg) {
×
1270
  setThreadName("shellThreadLoop");
×
1271
  taosGetOldTerminalMode();
×
1272
  taosThreadCleanupPush(shellCleanup, NULL);
×
1273

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

1281
    do {
1282
      memset(command, 0, SHELL_MAX_COMMAND_SIZE);
×
1283
      taosSetTerminalMode();
×
1284

1285
      if (shellReadCommand(command) != 0) {
×
1286
        break;
×
1287
      }
1288

1289
      taosResetTerminalMode();
×
1290
    } while (shellRunCommand(command, true) == 0);
×
1291

1292
    taosMemoryFreeClear(command);
×
1293
    shellWriteHistory();
×
1294
    shellExit();
×
1295
  } while (0);
1296

1297
  taosThreadCleanupPop(1);
×
1298
  return NULL;
×
1299
}
1300
#pragma GCC diagnostic pop
1301

1302
TAOS* createConnect(SShellArgs *pArgs) {
62✔
1303
  char     show[256] = "\0";
62✔
1304
  char *   host = NULL;
62✔
1305
  uint16_t port = 0;
62✔
1306
  char *   user = NULL;
62✔
1307
  char *   pwd  = NULL;
62✔
1308
  int32_t  code = 0;
62✔
1309
  char *   dsnc = NULL;
62✔
1310

1311
  // set mode
1312
  if (pArgs->connMode != CONN_MODE_NATIVE && pArgs->dsn) {
62!
1313
      dsnc = strToLowerCopy(pArgs->dsn);
×
1314
      if (dsnc == NULL) {
×
1315
          return NULL;
×
1316
      }
1317

1318
      char *cport = NULL;
×
1319
      char error[512] = "\0";
×
1320
      code = parseDsn(dsnc, &host, &cport, &user, &pwd, error);
×
1321
      if (code) {
×
1322
          printf("%s dsn=%s\n", error, dsnc);
×
1323
          free(dsnc);
×
1324
          return NULL;
×
1325
      }
1326

1327
      // default ws port
1328
      if (cport == NULL) {
×
1329
          if (user)
×
1330
              port = DEFAULT_PORT_WS_CLOUD;
×
1331
          else
1332
              port = DEFAULT_PORT_WS_LOCAL;
×
1333
      } else {
1334
          port = atoi(cport);
×
1335
      }
1336

1337
      // websocket
1338
      memcpy(show, pArgs->dsn, 20);
×
1339
      memcpy(show + 20, "...", 3);
×
1340
      memcpy(show + 23, pArgs->dsn + strlen(pArgs->dsn) - 10, 10);
×
1341

1342
  } else {
1343

1344
      host = (char *)pArgs->host;
62✔
1345
      user = (char *)pArgs->user;
62✔
1346
      pwd  = pArgs->password;
62✔
1347

1348
      if (pArgs->port_inputted) {
62✔
1349
          port = pArgs->port;
4✔
1350
      } else {
1351
          port = defaultPort(pArgs->connMode, pArgs->dsn);
58✔
1352
      }
1353

1354
      sprintf(show, "host:%s port:%d ", host, port);
62✔
1355
  }
1356

1357
  // connect main
1358
  TAOS * taos = NULL;
62✔
1359
  if (pArgs->auth) {
62!
1360
    taos = taos_connect_auth(host, user, pArgs->auth, pArgs->database, port);
×
1361
  } else {
1362
    taos = taos_connect(host, user, pwd, pArgs->database, port);
62✔
1363
  }
1364

1365
  // host user pointer in dsnc address
1366
  free(dsnc);
62✔
1367
  return taos;
62✔
1368
}
1369

1370
int32_t shellExecute(int argc, char *argv[]) {
62✔
1371
  int32_t code = 0;
62✔
1372
  printf(shell.info.clientVersion, shell.info.cusName, 
124!
1373
             workingMode(shell.args.connMode, shell.args.dsn) == CONN_MODE_NATIVE ? STR_NATIVE : STR_WEBSOCKET,
62✔
1374
             taos_get_client_info(), shell.info.cusName);
1375
  fflush(stdout);
62✔
1376

1377
  SShellArgs *pArgs = &shell.args;
62✔
1378
  shell.conn = createConnect(pArgs);
62✔
1379

1380
  if (shell.conn == NULL) {
62!
1381
    printf("failed to connect to server, reason: %s [0x%08X]\n%s", taos_errstr(NULL), taos_errno(NULL),
×
1382
           ERROR_CODE_DETAIL);
1383
    fflush(stdout);
×
1384
    return -1;
×
1385
  }
1386

1387
  bool runOnce = pArgs->commands != NULL || pArgs->file[0] != 0;
62!
1388
  shellSetConn(shell.conn, runOnce);
62✔
1389
  shellReadHistory();
62✔
1390

1391
  if (shell.args.is_bi_mode) {
62!
1392
    // need set bi mode
1393
    printf("Set BI mode is true.\n");
×
1394
    taos_set_conn_mode(shell.conn, TAOS_CONN_MODE_BI, 1);
×
1395
  }
1396

1397
  if (runOnce) {
62!
1398
    if (pArgs->commands != NULL) {
62✔
1399
      printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
5✔
1400
      char *cmd = taosStrdup(pArgs->commands);
5!
1401
      shellRunCommand(cmd, true);
5✔
1402
      taosMemoryFree(cmd);
5!
1403
    }
1404

1405
    if (pArgs->file[0] != 0) {
62✔
1406
      shellSourceFile(pArgs->file);
57✔
1407
    }
1408

1409
    taos_close(shell.conn);
62✔
1410

1411
    shellWriteHistory();
62✔
1412
    shellCleanupHistory();
62✔
1413
    return 0;
62✔
1414
  }
1415

1416
  if ((code = tsem_init(&shell.cancelSem, 0, 0)) != 0) {
×
1417
    printf("failed to create cancel semaphore since %s\r\n", tstrerror(code));
×
1418
    return code;
×
1419
  }
1420

1421
  TdThread spid = {0};
×
1422
  taosThreadCreate(&spid, NULL, shellCancelHandler, NULL);
×
1423

1424
  taosSetSignal(SIGTERM, shellQueryInterruptHandler);
×
1425
  taosSetSignal(SIGHUP, shellQueryInterruptHandler);
×
1426
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
×
1427

1428
  char    buf[512] = {0};
×
1429
  int32_t verType = shellGetGrantInfo(buf);
×
1430
#ifndef WINDOWS
1431
  printfIntroduction(verType);
×
1432
#else
1433
  if (verType == TSDB_VERSION_OSS) {
1434
    showAD(false);
1435
  }
1436
#endif
1437
  // printf version
1438
  if (verType == TSDB_VERSION_ENTERPRISE || verType == TSDB_VERSION_CLOUD) {
×
1439
    printf("%s\n", buf);
×
1440
  }
1441

1442
  while (1) {
1443
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, NULL);
×
1444
    taosThreadJoin(shell.pid, NULL);
×
1445
    taosThreadClear(&shell.pid);
×
1446
    if (shell.exit) {
×
1447
      tsem_post(&shell.cancelSem);
×
1448
      break;
×
1449
    }
1450
  }
1451

1452
  if (verType == TSDB_VERSION_OSS) {
×
1453
    showAD(true);
×
1454
  }
1455

1456
  taosThreadJoin(spid, NULL);
×
1457

1458
  shellCleanupHistory();
×
1459
  taos_kill_query(shell.conn);
×
1460
  taos_close(shell.conn);
×
1461

1462
  TAOS_RETURN(code);
×
1463
}
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