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

taosdata / TDengine / #4986

15 Mar 2026 08:32AM UTC coverage: 37.305% (-31.3%) from 68.601%
#4986

push

travis-ci

tomchon
test: keep docs and unit test

125478 of 336361 relevant lines covered (37.3%)

1134847.06 hits per line

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

15.26
/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 "../../inc/pub.h"
22
#include "geosWrapper.h"
23
#include "shellAuto.h"
24
#include "shellInt.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) {
12✔
71
  for (char c = *cmd++; c != 0; c = *cmd++) {
12✔
72
    if (c != ' ' && c != '\t' && c != ';') {
12✔
73
      return false;
12✔
74
    }
75
  }
76
  return true;
×
77
}
78

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

82
  if (shellIsEmptyCommand(command)) {
6✔
83
    return 0;
×
84
  }
85

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

90
  if (shellRegexMatch(command, "^[\t ]*clear[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
6✔
91
#pragma GCC diagnostic push
92
#pragma GCC diagnostic ignored "-Wunused-result"
93
#ifndef TD_ASTRA
94
    (void)system("clear");
×
95
#else
96
    (void)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;]*$",
6✔
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)) {
6✔
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);
6✔
133
  return 0;
6✔
134
}
135

136
void shellRecordCommandToHistory(char *command) {
6✔
137
  if (strncasecmp(command, "create user ", 12) == 0 || strncasecmp(command, "alter user ", 11) == 0) {
6✔
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;
6✔
145
  if (pHistory->hstart == pHistory->hend ||
6✔
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) {
6✔
149
      taosMemoryFreeClear(pHistory->hist[pHistory->hend]);
×
150
    }
151
    pHistory->hist[pHistory->hend] = taosStrdup(command);
6✔
152

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

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

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

173
  if (recordHistory) shellRecordCommandToHistory(command);
6✔
174

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

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

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

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

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

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

219
  return NULL;
6✔
220
}
221

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

229
  if ((sptr = strstr(command, ">>")) != NULL) {
6✔
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) {
6✔
241
    *sptr = '\0';
×
242
    printMode = true;  // When output to a file, the switch does not work.
×
243
  }
244

245
  st = taosGetTimestampUs();
6✔
246

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

253
  if (shellRegexMatch(command, "^\\s*use\\s+[a-zA-Z0-9_]+\\s*;\\s*$", REG_EXTENDED | REG_ICASE)) {
6✔
254
    (void)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";
6✔
266
  if (shellRegexMatch(command, "^\\s*delete\\s*from\\s*.*", REG_EXTENDED | REG_ICASE)) {
6✔
267
    pre = "Delete OK";
×
268
  } else if (shellRegexMatch(command, "^\\s*insert\\s*into\\s*.*", REG_EXTENDED | REG_ICASE)) {
6✔
269
    pre = "Insert OK";
×
270
  } else if (shellRegexMatch(command, "^\\s*create\\s*.*", REG_EXTENDED | REG_ICASE)) {
6✔
271
    pre = "Create OK";
×
272
  } else if (shellRegexMatch(command, "^\\s*drop\\s*.*", REG_EXTENDED | REG_ICASE)) {
6✔
273
    pre = "Drop OK";
6✔
274
  }
275

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

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

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

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

301
  (void)printf("\r\n");
6✔
302
}
303

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

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

323
  if (tt <= 0 && ms < 0) {
×
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};
×
335
  if (taosLocalTime(&tt, &ptm, buf, bufSize, NULL) == NULL) {
×
336
    return buf;
×
337
  }
338
  size_t pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
×
339

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

348
  return buf;
×
349
}
350

351
char *shellDumpHexValue(char *buf, const char *val, int32_t length) {
×
352
  for (int32_t i = 0; i < length; i++) {
×
353
    (void)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
        (void)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
      break;
×
472
    case TSDB_DATA_TYPE_BLOB:
×
473
    case TSDB_DATA_TYPE_MEDIUMBLOB: {
474
      void    *tmp = NULL;
×
475
      uint32_t size = 0;
×
476
      if (taosAscii2Hex(val, length, &tmp, &size) < 0) {
×
477
        break;
×
478
      }
479
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
×
480
      taosMemoryFree(tmp);
×
481

482
      break;
×
483
    }
484
    default:
×
485
      break;
×
486
  }
487
}
488

489
int64_t shellDumpResultToFile(const char *fname, TAOS_RES *tres) {
×
490
  char fullname[PATH_MAX] = {0};
×
491
  if (taosExpandDir(fname, fullname, PATH_MAX) != 0) {
×
492
    tstrncpy(fullname, fname, PATH_MAX);
×
493
  }
494

495
  TAOS_ROW row = taos_fetch_row(tres);
×
496
  if (row == NULL) {
×
497
    return 0;
×
498
  }
499

500
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_TRUNC | TD_FILE_STREAM);
×
501
  if (pFile == NULL) {
×
502
    (void)fprintf(stderr, "failed to open file: %s\r\n", fullname);
×
503
    return -1;
×
504
  }
505

506
  TAOS_FIELD *fields = taos_fetch_fields(tres);
×
507
  int32_t     num_fields = taos_num_fields(tres);
×
508
  int32_t     precision = taos_result_precision(tres);
×
509

510
  for (int32_t col = 0; col < num_fields; col++) {
×
511
    if (col > 0) {
×
512
      taosFprintfFile(pFile, ",");
×
513
    }
514
    taosFprintfFile(pFile, "%s", fields[col].name);
×
515
  }
516
  taosFprintfFile(pFile, "\r\n");
×
517

518
  int64_t numOfRows = 0;
×
519
  do {
520
    int32_t *length = taos_fetch_lengths(tres);
×
521
    for (int32_t i = 0; i < num_fields; i++) {
×
522
      if (i > 0) {
×
523
        taosFprintfFile(pFile, ",");
×
524
      }
525
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision);
×
526
    }
527
    taosFprintfFile(pFile, "\r\n");
×
528

529
    numOfRows++;
×
530
    row = taos_fetch_row(tres);
×
531
  } while (row != NULL);
×
532

533
  taosCloseFile(&pFile);
×
534

535
  return numOfRows;
×
536
}
537

538
void shellPrintNChar(const char *str, int32_t length, int32_t width) {
×
539
  TdWchar tail[3];
540
  int32_t pos = 0, cols = 0, totalCols = 0, tailLen = 0;
×
541

542
  while (pos < length) {
×
543
    TdWchar wc;
544
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
×
545
    if (bytes <= 0) {
×
546
      break;
×
547
    }
548

549
    if (pos + bytes > length) {
×
550
      break;
×
551
    }
552
    int w = 0;
×
553
    if (*(str + pos) == '\t' || *(str + pos) == '\n' || *(str + pos) == '\r') {
×
554
      w = bytes;
×
555
    } else {
556
      w = taosWcharWidth(wc);
×
557
    }
558
    pos += bytes;
×
559

560
    if (w <= 0) {
×
561
      continue;
×
562
    }
563

564
    if (width <= 0) {
×
565
      (void)printf("%lc", wc);
×
566
      continue;
×
567
    }
568

569
    totalCols += w;
×
570
    if (totalCols > width) {
×
571
      break;
×
572
    }
573
    if (totalCols <= (width - 3)) {
×
574
      (void)printf("%lc", wc);
×
575
      cols += w;
×
576
    } else {
577
      tail[tailLen] = wc;
×
578
      tailLen++;
×
579
    }
580
  }
581

582
  if (totalCols > width) {
×
583
    // width could be 1 or 2, so printf("...") cannot be used
584
    for (int32_t i = 0; i < 3; i++) {
×
585
      if (cols >= width) {
×
586
        break;
×
587
      }
588
      putchar('.');
×
589
      ++cols;
×
590
    }
591
  } else {
592
    for (int32_t i = 0; i < tailLen; i++) {
×
593
      (void)printf("%lc", tail[i]);
×
594
    }
595
    cols = totalCols;
×
596
  }
597

598
  for (; cols < width; cols++) {
×
599
    putchar(' ');
×
600
  }
601
}
×
602

603
void shellPrintString(const char *str, int32_t width) {
×
604
  int32_t len = strlen(str);
×
605

606
  if (width == 0) {
×
607
    (void)printf("%s", str);
×
608
  } else if (len > width) {
×
609
    if (width <= 3) {
×
610
      (void)printf("%.*s.", width - 1, str);
×
611
    } else {
612
      (void)printf("%.*s...", width - 3, str);
×
613
    }
614
  } else {
615
    (void)printf("%s%*.s", str, width - len, "");
×
616
  }
617
}
×
618

619
void shellPrintGeometry(const unsigned char *val, int32_t length, int32_t width) {
×
620
  if (length == 0) {  // empty value
×
621
    shellPrintString("", width);
×
622
    return;
×
623
  }
624

625
  int32_t code = TSDB_CODE_FAILED;
×
626

627
  code = initCtxAsText();
×
628
  if (code != TSDB_CODE_SUCCESS) {
×
629
    shellPrintString(getGeosErrMsg(code), width);
×
630
    return;
×
631
  }
632

633
  char *outputWKT = NULL;
×
634
  code = doAsText(val, length, &outputWKT);
×
635
  if (code != TSDB_CODE_SUCCESS) {
×
636
    shellPrintString(getGeosErrMsg(code), width);  // should NOT happen
×
637
    return;
×
638
  }
639

640
  shellPrintString(outputWKT, width);
×
641

642
  geosFreeBuffer(outputWKT);
×
643
}
644

645
void shellPrintField(const char *val, TAOS_FIELD *field, int32_t width, int32_t length, int32_t precision) {
×
646
  if (val == NULL) {
×
647
    shellPrintString(TSDB_DATA_NULL_STR, width);
×
648
    return;
×
649
  }
650

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

724
    case TSDB_DATA_TYPE_BLOB:
×
725
    case TSDB_DATA_TYPE_MEDIUMBLOB: {
726
      void    *data = NULL;
×
727
      uint32_t size = 0;
×
728
      if (taosAscii2Hex(val, length, &data, &size) < 0) {
×
729
        break;
×
730
      }
731
      shellPrintNChar(data, size, width);
×
732
      taosMemoryFree(data);
×
733
      break;
×
734
    }
735
    case TSDB_DATA_TYPE_DECIMAL:
×
736
    case TSDB_DATA_TYPE_DECIMAL64:
737
      (void)printf("%*s", width, val);
×
738
    default:
×
739
      break;
×
740
  }
741
}
742

743
// show whole result for this query return true, like limit or describe
744
bool shellIsShowWhole(const char *sql) {
×
745
  // limit
746
  char * p = taosStrCaseStr(sql, " limit ");
×
747
  if (p != NULL) {
×
748
    // except subquery, like "select * from (select * from t limit 10) limit 3", only the last limit is valid
749
    char * p1 = taosStrCaseStr(p + 7, ")");
×
750
    if (p1 == NULL) {
×
751
      return true;
×
752
    }
753
    if (taosStrCaseStr(p1 + 1, " limit ")) {
×
754
      return true;
×
755
    }
756
  }
757
  // describe
758
  if (taosStrCaseStr(sql, "describe ") != NULL) {
×
759
    return true;
×
760
  }
761
  // desc
762
  if (taosStrCaseStr(sql, "desc ") != NULL) {
×
763
    return true;
×
764
  }
765
  // show
766
  if (taosStrCaseStr(sql, "show ") != NULL) {
×
767
    return true;
×
768
  }
769
  // explain
770
  if (taosStrCaseStr(sql, "explain ") != NULL) {
×
771
    return true;
×
772
  }
773

774
  return false;
×
775
}
776

777
bool shellIsShowQuery(const char *sql) {
×
778
  // todo refactor
779
  if (taosStrCaseStr(sql, "show ") != NULL) {
×
780
    return true;
×
781
  }
782

783
  return false;
×
784
}
785

786
void init_dump_info(tsDumpInfo *dump_info, TAOS_RES *tres, const char *sql, bool vertical) {
×
787
  dump_info->sql = sql;
×
788
  dump_info->vertical = vertical;
×
789
  tsem_init(&dump_info->sem, 0, 0);
×
790
  dump_info->numOfAllRows = 0;
×
791

792
  dump_info->numFields = taos_num_fields(tres);
×
793
  dump_info->fields = taos_fetch_fields(tres);
×
794
  dump_info->precision = taos_result_precision(tres);
×
795

796
  dump_info->resShowMaxNum = UINT64_MAX;
×
797

798
  if (shell.args.commands == NULL && shell.args.file[0] == 0 && !shellIsShowWhole(dump_info->sql)) {
×
799
    dump_info->resShowMaxNum = SHELL_DEFAULT_RES_SHOW_NUM;
×
800
  }
801

802
  if (vertical) {
×
803
    dump_info->maxColNameLen = 0;
×
804
    for (int32_t col = 0; col < dump_info->numFields; col++) {
×
805
      int32_t len = (int32_t)strlen(dump_info->fields[col].name);
×
806
      if (len > dump_info->maxColNameLen) {
×
807
        dump_info->maxColNameLen = len;
×
808
      }
809
    }
810
  } else {
811
    for (int32_t col = 0; col < dump_info->numFields; col++) {
×
812
      dump_info->width[col] = shellCalcColWidth(dump_info->fields + col, dump_info->precision);
×
813
    }
814
    // set an appropriate width for token and totp_secret display
815
    if (shellRegexMatch(sql, "^[\t ]*create[ \t]+token[ \t]+.*", REG_EXTENDED | REG_ICASE)) {
×
816
      dump_info->width[0] = TMAX(dump_info->width[0], SHELL_SHOW_TOKEN_DISPLAY_WIDTH);
×
817
    } else if (shellRegexMatch(sql, "^[\t ]*create[ \t]+totp_secret[ \t]+.*", REG_EXTENDED | REG_ICASE)) {
×
818
      dump_info->width[0] = TMAX(dump_info->width[0], SHELL_SHOW_TOTP_SECRET_DISPLAY_WIDTH);
×
819
    }
820
  }
821
}
×
822

823
void shellVerticalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
×
824
  TAOS_ROW row = taos_fetch_row(tres);
×
825
  if (row == NULL) {
×
826
    (void)printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
827
    return;
×
828
  }
829

830
  int64_t numOfPintRows = dump_info->numOfAllRows;
×
831
  int     numOfPrintRowsThisOne = 0;
×
832

833
  while (row != NULL) {
×
834
    (void)printf("*************************** %" PRId64 ".row ***************************\r\n", numOfPintRows + 1);
×
835

836
    int32_t *length = taos_fetch_lengths(tres);
×
837

838
    for (int32_t i = 0; i < dump_info->numFields; i++) {
×
839
      TAOS_FIELD *field = dump_info->fields + i;
×
840

841
      int32_t padding = (int32_t)(dump_info->maxColNameLen - strlen(field->name));
×
842
      (void)printf("%*.s%s: ", padding, " ", field->name);
×
843

844
      shellPrintField((const char *)row[i], field, 0, length[i], dump_info->precision);
×
845
      putchar('\r');
×
846
      putchar('\n');
×
847
    }
848

849
    numOfPintRows++;
×
850
    numOfPrintRowsThisOne++;
×
851

852
    if (numOfPintRows == dump_info->resShowMaxNum) {
×
853
      (void)printf("\r\n");
×
854
      (void)printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
×
855
      (void)printf("         You can use the `LIMIT` clause to get fewer result to show.\r\n");
×
856
      (void)printf("           Or use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
857
      (void)printf("\r\n");
×
858
      (void)printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
×
859
      (void)printf("\r\n");
×
860
      return;
×
861
    }
862

863
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
×
864
      return;
×
865
    }
866

867
    row = taos_fetch_row(tres);
×
868
  }
869
  return;
×
870
}
871

872
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
×
873
  int32_t width = (int32_t)strlen(field->name);
×
874

875
  switch (field->type) {
×
876
    case TSDB_DATA_TYPE_NULL:
×
877
      return TMAX(4, width);  // null
×
878
    case TSDB_DATA_TYPE_BOOL:
×
879
      return TMAX(5, width);  // 'false'
×
880

881
    case TSDB_DATA_TYPE_TINYINT:
×
882
    case TSDB_DATA_TYPE_UTINYINT:
883
      return TMAX(4, width);  // '-127'
×
884

885
    case TSDB_DATA_TYPE_SMALLINT:
×
886
    case TSDB_DATA_TYPE_USMALLINT:
887
      return TMAX(6, width);  // '-32767'
×
888

889
    case TSDB_DATA_TYPE_INT:
×
890
    case TSDB_DATA_TYPE_UINT:
891
      return TMAX(11, width);  // '-2147483648'
×
892

893
    case TSDB_DATA_TYPE_BIGINT:
×
894
    case TSDB_DATA_TYPE_UBIGINT:
895
      return TMAX(21, width);  // '-9223372036854775807'
×
896

897
    case TSDB_DATA_TYPE_FLOAT:
×
898
      return TMAX(SHELL_FLOAT_WIDTH, width);
×
899

900
    case TSDB_DATA_TYPE_DOUBLE:
×
901
      return TMAX(SHELL_DOUBLE_WIDTH, width);
×
902

903
    case TSDB_DATA_TYPE_BINARY:
×
904
    case TSDB_DATA_TYPE_GEOMETRY:
905
      if (field->bytes > shell.args.displayWidth) {
×
906
        return TMAX(shell.args.displayWidth, width);
×
907
      } else {
908
        return TMAX(field->bytes + 2, width);
×
909
      }
910
    case TSDB_DATA_TYPE_VARBINARY: {
×
911
      int32_t bytes = field->bytes * 2 + 2;
×
912
      if (bytes > shell.args.displayWidth) {
×
913
        return TMAX(shell.args.displayWidth, width);
×
914
      } else {
915
        return TMAX(bytes + 2, width);
×
916
      }
917
    }
918
    case TSDB_DATA_TYPE_NCHAR:
×
919
    case TSDB_DATA_TYPE_JSON: {
920
      uint16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
×
921
      if (bytes > shell.args.displayWidth) {
×
922
        return TMAX(shell.args.displayWidth, width);
×
923
      } else {
924
        return TMAX(bytes + 2, width);
×
925
      }
926
    }
927

928
    case TSDB_DATA_TYPE_TIMESTAMP:
×
929
      if (shell.args.is_raw_time) {
×
930
        return TMAX(14, width);
×
931
      }
932
      if (precision == TSDB_TIME_PRECISION_NANO) {
×
933
        return TMAX(29, width);
×
934
      } else if (precision == TSDB_TIME_PRECISION_MICRO) {
×
935
        return TMAX(26, width);  // '2020-01-01 00:00:00.000000'
×
936
      } else {
937
        return TMAX(23, width);  // '2020-01-01 00:00:00.000'
×
938
      }
939
    case TSDB_DATA_TYPE_BLOB:
×
940
    case TSDB_DATA_TYPE_MEDIUMBLOB: {
941
      int32_t bytes = TSDB_MAX_BLOB_LEN;
×
942
      if (bytes > shell.args.displayWidth) {
×
943
        return TMAX(shell.args.displayWidth, width);
×
944
      } else {
945
        return TMAX(bytes + 2, width);
×
946
      }
947
    } break;
948

949
    case TSDB_DATA_TYPE_DECIMAL64:
×
950
      return TMAX(width, 20);
×
951
    case TSDB_DATA_TYPE_DECIMAL:
×
952
      return TMAX(width, 40);
×
953
    default:
×
954
      ASSERT(false);
×
955
  }
956

957
  return 0;
×
958
}
959

960
void shellPrintHeader(TAOS_FIELD *fields, int32_t *width, int32_t num_fields) {
×
961
  int32_t rowWidth = 0;
×
962
  for (int32_t col = 0; col < num_fields; col++) {
×
963
    TAOS_FIELD *field = fields + col;
×
964
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
×
965
    int32_t     left = padding / 2;
×
966
    (void)printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
×
967
    rowWidth += width[col] + 3;
×
968
  }
969

970
  putchar('\r');
×
971
  putchar('\n');
×
972
  for (int32_t i = 0; i < rowWidth; i++) {
×
973
    putchar('=');
×
974
  }
975
  putchar('\r');
×
976
  putchar('\n');
×
977
}
×
978

979
void shellHorizontalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
×
980
  TAOS_ROW row = taos_fetch_row(tres);
×
981
  if (row == NULL) {
×
982
    (void)printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
983
    return;
×
984
  }
985

986
  int64_t numOfPintRows = dump_info->numOfAllRows;
×
987
  int     numOfPrintRowsThisOne = 0;
×
988
  if (numOfPintRows == 0) {
×
989
    shellPrintHeader(dump_info->fields, dump_info->width, dump_info->numFields);
×
990
  }
991

992
  while (row != NULL) {
×
993
    int32_t *length = taos_fetch_lengths(tres);
×
994
    for (int32_t i = 0; i < dump_info->numFields; i++) {
×
995
      putchar(' ');
×
996
      shellPrintField((const char *)row[i], dump_info->fields + i, dump_info->width[i], length[i],
×
997
                      dump_info->precision);
998
      putchar(' ');
×
999
      putchar('|');
×
1000
    }
1001
    putchar('\r');
×
1002
    putchar('\n');
×
1003

1004
    numOfPintRows++;
×
1005
    numOfPrintRowsThisOne++;
×
1006

1007
    if (numOfPintRows == dump_info->resShowMaxNum) {
×
1008
      (void)printf("\r\n");
×
1009
      (void)printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
×
1010
      if (shellIsShowQuery(dump_info->sql)) {
×
1011
        (void)printf("         You can use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
1012
      } else {
1013
        (void)printf("         You can use the `LIMIT` clause to get fewer result to show.\r\n");
×
1014
        (void)printf("           Or use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
1015
      }
1016
      (void)printf("\r\n");
×
1017
      (void)printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
×
1018
      (void)printf("\r\n");
×
1019
      return;
×
1020
    }
1021

1022
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
×
1023
      return;
×
1024
    }
1025

1026
    row = taos_fetch_row(tres);
×
1027
  }
1028
  return;
×
1029
}
1030

1031
void shellDumpResultCallback(void *param, TAOS_RES *tres, int num_of_rows) {
×
1032
  tsDumpInfo *dump_info = (tsDumpInfo *)param;
×
1033
  if (num_of_rows > 0) {
×
1034
    dump_info->numOfRows = num_of_rows;
×
1035
    if (dump_info->numOfAllRows < dump_info->resShowMaxNum) {
×
1036
      if (dump_info->vertical) {
×
1037
        shellVerticalPrintResult(tres, dump_info);
×
1038
      } else {
1039
        shellHorizontalPrintResult(tres, dump_info);
×
1040
      }
1041
    }
1042
    dump_info->numOfAllRows += num_of_rows;
×
1043
    if (!shellCmdkilled) {
×
1044
      taos_fetch_rows_a(tres, shellDumpResultCallback, param);
×
1045
    } else {
1046
      tsem_post(&dump_info->sem);
×
1047
    }
1048
  } else {
1049
    if (num_of_rows < 0) {
×
1050
      (void)printf("\033[31masync retrieve failed, code: %d, %s\033[0m\n", num_of_rows, tstrerror(num_of_rows));
×
1051
    }
1052
    tsem_post(&dump_info->sem);
×
1053
  }
1054
}
×
1055

1056
int64_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
×
1057
  int64_t num_of_rows = 0;
×
1058
  if (fname != NULL) {
×
1059
    num_of_rows = shellDumpResultToFile(fname, tres);
×
1060
  } else {
1061
    tsDumpInfo dump_info;
1062
    if (!shellCmdkilled) {
×
1063
      init_dump_info(&dump_info, tres, sql, vertical);
×
1064
      taos_fetch_rows_a(tres, shellDumpResultCallback, &dump_info);
×
1065
      tsem_wait(&dump_info.sem);
×
1066
      num_of_rows = dump_info.numOfAllRows;
×
1067
    }
1068
  }
1069

1070
  *error_no = shellCmdkilled ? TSDB_CODE_TSC_QUERY_KILLED : taos_errno(tres);
×
1071
  return num_of_rows;
×
1072
}
1073

1074
void shellReadHistory() {
6✔
1075
  SShellHistory *pHistory = &shell.history;
6✔
1076
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_READ | TD_FILE_STREAM);
6✔
1077
  if (pFile == NULL) return;
6✔
1078

1079
  char   *line = taosMemoryMalloc(tsMaxSQLLength + 1);
4✔
1080
  int32_t read_size = 0;
4✔
1081
  while ((read_size = taosGetsFile(pFile, tsMaxSQLLength, line)) > 0) {
10✔
1082
    line[read_size - 1] = '\0';
6✔
1083
    taosMemoryFree(pHistory->hist[pHistory->hend]);
6✔
1084
    pHistory->hist[pHistory->hend] = taosStrdup(line);
6✔
1085

1086
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
6✔
1087

1088
    if (pHistory->hend == pHistory->hstart) {
6✔
1089
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
×
1090
    }
1091
  }
1092

1093
  taosMemoryFreeClear(line);
4✔
1094
  taosCloseFile(&pFile);
4✔
1095
  int64_t file_size;
1096
  if (taosStatFile(pHistory->file, &file_size, NULL, NULL) == 0 && file_size > SHELL_MAX_COMMAND_SIZE) {
4✔
1097
    TdFilePtr pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_TRUNC);
×
1098
    if (pFile == NULL) return;
×
1099
    int32_t endIndex = pHistory->hstart;
×
1100
    if (endIndex != 0) {
×
1101
      endIndex = pHistory->hend;
×
1102
    }
1103
    for (int32_t i = (pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE; i != endIndex;) {
×
1104
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
×
1105
      i = (i + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE;
×
1106
    }
1107
    taosFprintfFile(pFile, "%s\n", pHistory->hist[endIndex]);
×
1108

1109
    /* coverity[+retval] */
1110
    taosFsyncFile(pFile);
×
1111
    taosCloseFile(&pFile);
×
1112
  }
1113
  pHistory->hstart = pHistory->hend;
4✔
1114
}
1115

1116
void shellWriteHistory() {
6✔
1117
  SShellHistory *pHistory = &shell.history;
6✔
1118
  if (pHistory->hend == pHistory->hstart) return;
6✔
1119
  TdFilePtr pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_APPEND);
6✔
1120
  if (pFile == NULL) return;
6✔
1121

1122
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
12✔
1123
    if (pHistory->hist[i] != NULL) {
6✔
1124
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
6✔
1125
      taosMemoryFree(pHistory->hist[i]);
6✔
1126
      pHistory->hist[i] = NULL;
6✔
1127
    }
1128
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
6✔
1129
  }
1130
  taosCloseFile(&pFile);
6✔
1131
}
1132

1133
void shellCleanupHistory() {
6✔
1134
  SShellHistory *pHistory = &shell.history;
6✔
1135
  for (int32_t i = 0; i < SHELL_MAX_HISTORY_SIZE; ++i) {
6,006✔
1136
    if (pHistory->hist[i] != NULL) {
6,000✔
1137
      taosMemoryFree(pHistory->hist[i]);
6✔
1138
      pHistory->hist[i] = NULL;
6✔
1139
    }
1140
  }
1141
}
6✔
1142

1143
void shellPrintError(TAOS_RES *tres, int64_t st) {
×
1144
  int code = taos_errno(tres);
×
1145
  int64_t et = taosGetTimestampUs();
×
1146
  (void)printf("\r\nDB error: %s [0x%08X] (%.6fs)\r\n", taos_errstr(tres), code, (et - st) / 1E6);
×
1147
  taos_free_result(tres);
×
1148

1149
  // tip
1150
  if (code == TSDB_CODE_MND_USER_PASSWORD_EXPIRED) {
×
1151
    (void)fprintf(stdout, "******************** TIPS ********************\n");
×
1152
    (void)fprintf(stdout, "Please reset your password using the `ALTER USER <user_name> PASS 'new_password'` command.\n");
×
1153
    (void)fprintf(stdout, "**********************************************\n");
×
1154
  }
1155
}
×
1156

1157
bool shellIsCommentLine(char *line) {
×
1158
  if (line == NULL) return true;
×
1159
  return shellRegexMatch(line, "^\\s*#.*", REG_EXTENDED);
×
1160
}
1161

1162
void shellSourceFile(const char *file) {
×
1163
  int32_t read_len = 0;
×
1164
  char   *cmd = taosMemoryCalloc(1, tsMaxSQLLength + 1);
×
1165
  size_t  cmd_len = 0;
×
1166
  char    fullname[PATH_MAX] = {0};
×
1167
  char    sourceFileCommand[PATH_MAX + 8] = {0};
×
1168

1169
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
×
1170
    tstrncpy(fullname, file, PATH_MAX);
×
1171
  }
1172

1173
  (void)sprintf(sourceFileCommand, "source %s;", fullname);
×
1174
  shellRecordCommandToHistory(sourceFileCommand);
×
1175

1176
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_READ | TD_FILE_STREAM);
×
1177
  if (pFile == NULL) {
×
1178
    (void)fprintf(stderr, "failed to open file %s\r\n", fullname);
×
1179
    taosMemoryFree(cmd);
×
1180
    return;
×
1181
  }
1182

1183
  char *line = taosMemoryMalloc(tsMaxSQLLength + 1);
×
1184
  while ((read_len = taosGetsFile(pFile, tsMaxSQLLength, line)) > 0) {
×
1185
    if (cmd_len + read_len >= tsMaxSQLLength) {
×
1186
      (void)printf("read command line too long over 1M, ignore this line. cmd_len = %d read_len=%d \n", (int32_t)cmd_len,
×
1187
             read_len);
1188
      cmd_len = 0;
×
1189
      memset(line, 0, tsMaxSQLLength + 1);
×
1190
      continue;
×
1191
    }
1192
    line[--read_len] = '\0';
×
1193

1194
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
×
1195
      continue;
×
1196
    }
1197

1198
    if (line[read_len - 1] == '\\') {
×
1199
      line[read_len - 1] = ' ';
×
1200
      memcpy(cmd + cmd_len, line, read_len);
×
1201
      cmd_len += read_len;
×
1202
      continue;
×
1203
    }
1204

1205
    if (line[read_len - 1] == '\r') {
×
1206
      line[read_len - 1] = ' ';
×
1207
    }
1208

1209
    memcpy(cmd + cmd_len, line, read_len);
×
1210
    (void)printf("%s%s\r\n", shell.info.promptHeader, cmd);
×
1211
    shellRunCommand(cmd, false);
×
1212
    memset(cmd, 0, tsMaxSQLLength);
×
1213
    cmd_len = 0;
×
1214
  }
1215

1216
  taosMemoryFree(cmd);
×
1217
  taosMemoryFreeClear(line);
×
1218
  taosCloseFile(&pFile);
×
1219
}
1220

1221
int32_t shellGetGrantInfo(char *buf) {
×
1222
  int32_t verType = TSDB_VERSION_UNKNOWN;
×
1223
  char    sinfo[256] = {0};
×
1224
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
×
1225
  strtok(sinfo, "\r\n");
×
1226

1227
#ifndef TD_ASTRA
1228
  char sql[] = "show grants";
×
1229

1230
  TAOS_RES *tres = taos_query(shell.conn, sql);
×
1231

1232
  int32_t code = taos_errno(tres);
×
1233
  if (code != TSDB_CODE_SUCCESS) {
×
1234
    if (code != TSDB_CODE_OPS_NOT_SUPPORT && code != TSDB_CODE_MND_NO_RIGHTS &&
×
1235
        code != TSDB_CODE_PAR_PERMISSION_DENIED) {
1236
      (void)fprintf(stderr, "Failed to check Server Edition, Reason:0x%04x:%s\r\n\r\n", code, taos_errstr(tres));
×
1237
    }
1238
    taos_free_result(tres);
×
1239
    return verType;
×
1240
  }
1241

1242
  int32_t num_fields = taos_field_count(tres);
×
1243
  if (num_fields == 0) {
×
1244
    (void)fprintf(stderr, "\r\nInvalid grant information.\r\n");
×
1245
    exit(0);
×
1246
  } else {
1247
    if (tres == NULL) {
×
1248
      (void)fprintf(stderr, "\r\nGrant information is null.\r\n");
×
1249
      exit(0);
×
1250
    }
1251

1252
    TAOS_FIELD *fields = taos_fetch_fields(tres);
×
1253
    TAOS_ROW    row = taos_fetch_row(tres);
×
1254
    if (row == NULL) {
×
1255
      (void)fprintf(stderr, "\r\nFailed to get grant information from server. Abort.\r\n");
×
1256
      exit(0);
×
1257
    }
1258
    char serverVersion[64] = {0};
×
1259
    char expiretime[32] = {0};
×
1260
    char expired[32] = {0};
×
1261

1262
    tstrncpy(serverVersion, row[0], 64);
×
1263
    memcpy(expiretime, row[1], fields[1].bytes);
×
1264
    memcpy(expired, row[2], fields[2].bytes);
×
1265

1266
    trimStr(serverVersion, "trial");
×
1267

1268
    if (strcmp(serverVersion, "community") == 0) {
×
1269
      verType = TSDB_VERSION_OSS;
×
1270
    } else if (strcmp(expiretime, "unlimited") == 0) {
×
1271
      verType = TSDB_VERSION_ENTERPRISE;
×
1272
      (void)sprintf(buf, "Server is %s %s. License will never expire.\r\n", serverVersion, sinfo);
×
1273
    } else {
1274
      verType = TSDB_VERSION_ENTERPRISE;
×
1275
      (void)sprintf(buf, "Server is %s %s. License will expire at %s.\r\n", serverVersion, sinfo, expiretime);
×
1276
    }
1277

1278
    taos_free_result(tres);
×
1279
  }
1280

1281
  (void)fprintf(stdout, "\r\n");
×
1282
#else
1283
  verType = TSDB_VERSION_ENTERPRISE;
1284
  (void)sprintf(buf, "Server is %s %s. License will never expire.\r\n", TD_PRODUCT_NAME, sinfo);
1285
#endif
1286
  return verType;
×
1287
}
1288

1289
#ifdef WINDOWS
1290
BOOL shellQueryInterruptHandler(DWORD fdwCtrlType) {
1291
  tsem_post(&shell.cancelSem);
1292
  return TRUE;
1293
}
1294
#else
1295
void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) { tsem_post(&shell.cancelSem); }
×
1296
#endif
1297

1298
void shellCleanup(void *arg) { taosResetTerminalMode(); }
×
1299

1300
void *shellCancelHandler(void *arg) {
×
1301
  setThreadName("shellCancelHandler");
×
1302
  while (1) {
1303
    if (shell.exit == true) {
×
1304
      break;
×
1305
    }
1306

1307
    if (tsem_wait(&shell.cancelSem) != 0) {
×
1308
      taosMsleep(10);
×
1309
      continue;
×
1310
    }
1311

1312
    if (shell.conn) {
×
1313
      shellCmdkilled = true;
×
1314
      taos_kill_query(shell.conn);
×
1315
    }
1316

1317
#ifdef WINDOWS
1318
    (void)printf("\n%s", shell.info.promptHeader);
1319
#endif
1320
  }
1321

1322
  return NULL;
×
1323
}
1324

1325
#pragma GCC diagnostic push
1326
#pragma GCC diagnostic ignored "-Wstringop-overflow"
1327

1328
void *shellThreadLoop(void *arg) {
×
1329
  setThreadName("shellThreadLoop");
×
1330
  taosGetOldTerminalMode();
×
1331
  taosThreadCleanupPush(shellCleanup, NULL);
×
1332

1333
  do {
1334
    char *command = taosMemoryMalloc(SHELL_MAX_COMMAND_SIZE);
×
1335
    if (command == NULL) {
×
1336
      (void)printf("failed to malloc command\r\n");
×
1337
      break;
×
1338
    }
1339

1340
    do {
1341
      memset(command, 0, SHELL_MAX_COMMAND_SIZE);
×
1342
      taosSetTerminalMode();
×
1343

1344
      if (shellReadCommand(command) != 0) {
×
1345
        break;
×
1346
      }
1347

1348
      taosResetTerminalMode();
×
1349
    } while (shellRunCommand(command, true) == 0);
×
1350

1351
    taosMemoryFreeClear(command);
×
1352
    shellWriteHistory();
×
1353
    shellExit();
×
1354
  } while (0);
1355

1356
  taosThreadCleanupPop(1);
×
1357
  return NULL;
×
1358
}
1359

1360
bool inputTotpCode(char *totpCode) {
×
1361
  bool ret = true;
×
1362
  (void)printf("Please enter your TOTP code:");
×
1363
  if (scanf("%255s", totpCode) != 1) {
×
1364
    (void)fprintf(stderr, "TOTP code reading error\n");
×
1365
    ret = false;
×
1366
  }
1367
  if (EOF == getchar()) {
×
1368
    // tip
1369
    (void)fprintf(stdout, "getchar() return EOF\r\n");    
×
1370
  }
1371
  return ret;
×
1372
}
1373

1374
#pragma GCC diagnostic pop
1375

1376
TAOS *createConnect(SShellArgs *pArgs) {
6✔
1377
  char     show[256] = "\0";
6✔
1378
  char    *host = NULL;
6✔
1379
  uint16_t port = 0;
6✔
1380
  char    *user = NULL;
6✔
1381
  char    *pwd = NULL;
6✔
1382
  TAOS    *taos = NULL;
6✔
1383

1384
  // set mode
1385
  if (pArgs->connMode != CONN_MODE_NATIVE && pArgs->dsn) {
6✔
1386
    // websocket
1387
    memcpy(show, pArgs->dsn, 20);
×
1388
    memcpy(show + 20, "...", 3);
×
1389
    memcpy(show + 23, pArgs->dsn + strlen(pArgs->dsn) - 10, 10);
×
1390

1391
    // connect dsn
1392
    taos = taos_connect_with_dsn(pArgs->dsn);
×
1393
  } else {
1394
    host = (char *)pArgs->host;
6✔
1395
    user = (char *)pArgs->user;
6✔
1396
    pwd = pArgs->password;
6✔
1397

1398
    if (pArgs->port_inputted) {
6✔
1399
      port = pArgs->port;
×
1400
    } else {
1401
      port = defaultPort(pArgs->connMode, pArgs->dsn);
6✔
1402
    }
1403

1404
    (void)sprintf(show, "host:%s port:%d ", host, port);
6✔
1405

1406
    // connect normal
1407
    if (pArgs->auth) {
6✔
1408
      taos = taos_connect_auth(host, user, pArgs->auth, pArgs->database, port);
×
1409
    } else {
1410
#ifdef TD_ENTERPRISE 
1411
      if (strlen(pArgs->token) > 0) {
6✔
1412
        // token
1413
        (void)printf("Connect with token ...");
×
1414
        taos = taos_connect_token(host, pArgs->token, pArgs->database, port);
×
1415
        if (taos != NULL) {
×
1416
          (void)printf("... [ OK ]\n");
×
1417
          return taos;
×
1418
        }
1419
        (void)printf("... [ FAILED ]\n");
×
1420
        return NULL;
×
1421
      }
1422
#endif      
1423
      taos = taos_connect(host, user, pwd, pArgs->database, port);
6✔
1424
    }
1425

1426
    if (taos == NULL) {
6✔
1427
      // failed
1428
      int code = taos_errno(NULL);
×
1429
      if (code == TSDB_CODE_MND_WRONG_TOTP_CODE) {
×
1430
         // totp
1431
        char totpCode[TSDB_USER_PASSWORD_LONGLEN];
1432
        memset(totpCode, 0, sizeof(totpCode));  
×
1433
        if (inputTotpCode(totpCode)) {
×
1434
          (void)printf("Connect with TOTP code:%s ...", totpCode);
×
1435
          taos = taos_connect_totp(host, user, pwd, totpCode, pArgs->database, port);
×
1436
          if (taos != NULL) {
×
1437
            (void)printf("... [ OK ]\n");
×
1438
            return taos;
×
1439
          }
1440
          (void)printf("... [ FAILED ]\n");
×
1441
          return NULL;
×
1442
        }
1443
      }
1444
      // token
1445
    }
1446
  }
1447

1448
  return taos;
6✔
1449
}
1450

1451
int32_t shellExecute(int argc, char *argv[]) {
6✔
1452
  int32_t code = 0;
6✔
1453
  (void)printf(shell.info.clientVersion, shell.info.cusName,
12✔
1454
         workingMode(shell.args.connMode, shell.args.dsn) == CONN_MODE_NATIVE ? STR_NATIVE : STR_WEBSOCKET,
6✔
1455
         taos_get_client_info(), shell.info.cusName);
1456
  fflush(stdout);
6✔
1457

1458
  SShellArgs *pArgs = &shell.args;
6✔
1459
  shell.conn = createConnect(pArgs);
6✔
1460

1461
  if (shell.conn == NULL) {
6✔
1462
    (void)printf("failed to connect to server, reason: %s [0x%08X]\n%s", taos_errstr(NULL), taos_errno(NULL),
×
1463
           ERROR_CODE_DETAIL);
1464
    fflush(stdout);
×
1465
    return -1;
×
1466
  }
1467

1468
  bool runOnce = pArgs->commands != NULL || pArgs->file[0] != 0;
6✔
1469
  shellSetConn(shell.conn, runOnce);
6✔
1470
  shellReadHistory();
6✔
1471

1472
  if (shell.args.is_bi_mode) {
6✔
1473
    // need set bi mode
1474
    (void)printf("Set BI mode is true.\n");
×
1475
    taos_set_conn_mode(shell.conn, TAOS_CONN_MODE_BI, 1);
×
1476
  }
1477

1478
  if (runOnce) {
6✔
1479
    if (pArgs->commands != NULL) {
6✔
1480
      (void)printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
6✔
1481
      char *cmd = taosStrdup(pArgs->commands);
6✔
1482
      shellRunCommand(cmd, true);
6✔
1483
      taosMemoryFree(cmd);
6✔
1484
    }
1485

1486
    if (pArgs->file[0] != 0) {
6✔
1487
      shellSourceFile(pArgs->file);
×
1488
    }
1489

1490
    taos_close(shell.conn);
6✔
1491

1492
    shellWriteHistory();
6✔
1493
    shellCleanupHistory();
6✔
1494
    return 0;
6✔
1495
  }
1496

1497
  if ((code = tsem_init(&shell.cancelSem, 0, 0)) != 0) {
×
1498
    (void)printf("failed to create cancel semaphore since %s\r\n", tstrerror(code));
×
1499
    return code;
×
1500
  }
1501

1502
  TdThread spid = {0};
×
1503
  taosThreadCreate(&spid, NULL, shellCancelHandler, NULL);
×
1504

1505
  taosSetSignal(SIGTERM, shellQueryInterruptHandler);
×
1506
  taosSetSignal(SIGHUP, shellQueryInterruptHandler);
×
1507
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
×
1508

1509
  char    buf[512] = {0};
×
1510
  int32_t verType = shellGetGrantInfo(buf);
×
1511
#ifndef WINDOWS
1512
  printfIntroduction(verType);
×
1513
#else
1514
  if (verType == TSDB_VERSION_OSS) {
1515
    showAD(false);
1516
  }
1517
#endif
1518
  // printf version
1519
  if (verType == TSDB_VERSION_ENTERPRISE || verType == TSDB_VERSION_CLOUD) {
×
1520
    (void)printf("%s\n", buf);
×
1521
  }
1522

1523
  while (1) {
1524
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, NULL);
×
1525
    taosThreadJoin(shell.pid, NULL);
×
1526
    taosThreadClear(&shell.pid);
×
1527
    if (shell.exit) {
×
1528
      tsem_post(&shell.cancelSem);
×
1529
      break;
×
1530
    }
1531
  }
1532

1533
  if (verType == TSDB_VERSION_OSS) {
×
1534
    showAD(true);
×
1535
  }
1536

1537
  taosThreadJoin(spid, NULL);
×
1538

1539
  shellCleanupHistory();
×
1540
  taos_kill_query(shell.conn);
×
1541
  taos_close(shell.conn);
×
1542

1543
  TAOS_RETURN(code);
×
1544
}
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