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

taosdata / TDengine / #5099

17 May 2026 01:15AM UTC coverage: 73.343% (+0.04%) from 73.301%
#5099

push

travis-ci

web-flow
feat (TDgpt): Dynamic Model Synchronization Enhancements (#35344)

* refactor: do some internal refactor.

* fix: fix multiprocess sync issue.

* feat: add dynamic anomaly detection and forecasting services

* fix: log error message for undeploying model in exception handling

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* fix: handle undeploy when model exists only on disk

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/286aafa0-c3ce-4c27-b803-2707571e9dc1

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* fix: guard dynamic registry concurrent access

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/5e4db858-6458-40f4-ac28-d1b1b7f97c18

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* fix: tighten service list locking scope

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/5e4db858-6458-40f4-ac28-d1b1b7f97c18

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* fix: restore prophet support and update tests per review feedback

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/92298ae1-7da6-4d07-b20e-101c7cd0b26b

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* fix: improve test name and move copy inside lock scope

Agent-Logs-Url: https://github.com/taosdata/TDengine/sessions/92298ae1-7da6-4d07-b20e-101c7cd0b26b

Co-authored-by: hjxilinx <8252296+hjxilinx@users.noreply.github.com>

* Potential fix for pull request finding

Co-au... (continued)

281487 of 383795 relevant lines covered (73.34%)

130678481.36 hits per line

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

83.02
/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
static bool  shellHasBinaryNonPrintable(const char *val, int32_t length);
68
static void  shellHexEncode(char *dst, const char *val, int32_t length);
69
static char *shellAllocHexString(const char *val, int32_t length);
70
static void  shellPrintHex(const char *val, int32_t length, int32_t width);
71
void shellPrintString(const char *str, int32_t width);
72

73
static bool shellCmdkilled = false;
74

75
bool shellIsEmptyCommand(const char *cmd) {
254,006,797✔
76
  for (char c = *cmd++; c != 0; c = *cmd++) {
254,156,914✔
77
    if (c != ' ' && c != '\t' && c != ';') {
171,049,374✔
78
      return false;
170,899,257✔
79
    }
80
  }
81
  return true;
83,107,540✔
82
}
83

84
int32_t shellRunSingleCommand(char *command) {
168,631,783✔
85
  shellCmdkilled = false;
168,631,783✔
86

87
  if (shellIsEmptyCommand(command)) {
168,631,783✔
88
    return 0;
83,107,540✔
89
  }
90

91
  if (shellRegexMatch(command, "^[ \t]*(quit|q|exit)[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
85,524,243✔
92
    return -1;
729✔
93
  }
94

95
  if (shellRegexMatch(command, "^[\t ]*clear[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
85,523,514✔
96
#pragma GCC diagnostic push
97
#pragma GCC diagnostic ignored "-Wunused-result"
98
#ifndef TD_ASTRA
99
    (void)system("clear");
×
100
#else
101
    (void)printf("\033[2J\033[H");
102
#endif
103
#pragma GCC diagnostic pop
104
    return 0;
×
105
  }
106

107
  if (shellRegexMatch(command, "^[\t ]*set[ \t]+max_binary_display_width[ \t]+(default|[1-9][0-9]*)[ \t;]*$",
85,523,514✔
108
                      REG_EXTENDED | REG_ICASE)) {
109
    strtok(command, " \t");
9,501✔
110
    strtok(NULL, " \t");
9,501✔
111
    char *p = strtok(NULL, " \t");
9,501✔
112
    if (strncasecmp(p, "default", 7) == 0) {
9,501✔
113
      shell.args.displayWidth = SHELL_DEFAULT_MAX_BINARY_DISPLAY_WIDTH;
×
114
    } else {
115
      int32_t displayWidth = atoi(p);
9,501✔
116
      displayWidth = TRANGE(displayWidth, 1, 10 * 1024);
9,501✔
117
      shell.args.displayWidth = displayWidth;
9,501✔
118
    }
119
    return 0;
9,501✔
120
  }
121

122
  if (shellRegexMatch(command, "^[ \t]*source[\t ]+[^ ]+[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
85,514,013✔
123
    /* If source file. */
124
    char *c_ptr = strtok(command, " ;");
160✔
125
    if (c_ptr == NULL) {
160✔
126
      shellRunSingleCommandImp(command);
×
127
      return 0;
×
128
    }
129
    c_ptr = strtok(NULL, " ;");
160✔
130
    if (c_ptr == NULL) {
160✔
131
      shellRunSingleCommandImp(command);
×
132
      return 0;
×
133
    }
134
    shellSourceFile(c_ptr);
160✔
135
    return 0;
160✔
136
  }
137
  shellRunSingleCommandImp(command);
85,513,853✔
138
  return 0;
85,513,853✔
139
}
140

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

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

158
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
1,228,661✔
159
    if (pHistory->hend == pHistory->hstart) {
1,228,661✔
160
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
×
161
    }
162
  }
163
}
164

165
int32_t shellRunCommand(char *command, bool recordHistory) {
85,375,014✔
166
  if (shellIsEmptyCommand(command)) {
85,375,014✔
167
    return 0;
×
168
  }
169

170
  // add help or help;
171
  if (strncasecmp(command, "help", 4) == 0) {
85,375,014✔
172
    if (command[4] == ';' || command[4] == ' ' || command[4] == 0) {
166✔
173
      showHelp();
166✔
174
      return 0;
166✔
175
    }
176
  }
177

178
  if (recordHistory) shellRecordCommandToHistory(command);
85,374,848✔
179

180
  char quote = 0, *cmd = command;
85,374,848✔
181
  for (char c = *command++; c != 0; c = *command++) {
2,147,483,647✔
182
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
2,147,483,647✔
183
      command++;
1,166✔
184
      continue;
1,166✔
185
    }
186

187
    if (quote == c) {
2,147,483,647✔
188
      quote = 0;
14,953,555✔
189
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
2,147,483,647✔
190
      quote = c;
14,953,555✔
191
    } else if (c == ';' && quote == 0) {
2,147,483,647✔
192
      c = *command;
83,257,664✔
193
      *command = 0;
83,257,664✔
194
      if (shellRunSingleCommand(cmd) < 0) {
83,257,664✔
195
        return -1;
729✔
196
      }
197
      *command = c;
83,256,935✔
198
      cmd = command;
83,256,935✔
199
    }
200
  }
201
  return shellRunSingleCommand(cmd);
85,374,119✔
202
}
203

204
char *strendG(const char *pstr) {
85,513,853✔
205
  if (pstr == NULL) {
85,513,853✔
206
    return NULL;
×
207
  }
208

209
  size_t len = strlen(pstr);
85,513,853✔
210
  if (len < 4) {
85,513,853✔
211
    return NULL;
×
212
  }
213

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

219
  p = (char *)pstr + len - 3;
85,506,873✔
220
  if (strcmp(p, "\\G;") == 0) {
85,506,873✔
221
    return p;
157,759✔
222
  }
223

224
  return NULL;
85,349,114✔
225
}
226

227
void shellRunSingleCommandImp(char *command) {
85,513,853✔
228
  int64_t st, et;
229
  char   *sptr = NULL;
85,513,853✔
230
  char   *cptr = NULL;
85,513,853✔
231
  char   *fname = NULL;
85,513,853✔
232
  bool    printMode = false;
85,513,853✔
233

234
  if ((sptr = strstr(command, ">>")) != NULL) {
85,513,853✔
235
    fname = sptr + 2;
829,634✔
236
    while (*fname == ' ') fname++;
1,658,400✔
237
    *sptr = '\0';
829,634✔
238

239
    cptr = strstr(fname, ";");
829,634✔
240
    if (cptr != NULL) {
829,634✔
241
      *cptr = '\0';
1,791✔
242
    }
243
  }
244

245
  if ((sptr = strendG(command)) != NULL) {
85,513,853✔
246
    *sptr = '\0';
164,739✔
247
    printMode = true;  // When output to a file, the switch does not work.
164,739✔
248
  }
249

250
  st = taosGetTimestampUs();
85,513,853✔
251

252
  TAOS_RES *pSql = taos_query(shell.conn, command);
85,513,853✔
253
  if (taos_errno(pSql)) {
85,513,853✔
254
    shellPrintError(pSql, st);
30,685,800✔
255
    return;
30,685,800✔
256
  }
257

258
  if (shellRegexMatch(command, "^[[:space:]]*use[[:space:]]+[a-zA-Z0-9_]+[[:space:]]*;?[[:space:]]*$", REG_EXTENDED | REG_ICASE)) {
54,828,053✔
259
    (void)printf("Database changed.\r\n\r\n");
28,926✔
260

261
    // call back auto tab module
262
    callbackAutoTab(command, pSql, true);
28,926✔
263

264
    taos_free_result(pSql);
28,926✔
265

266
    return;
28,926✔
267
  }
268

269
  // pre string
270
  char *pre = "Query OK";
54,799,127✔
271
  if (shellRegexMatch(command, "^[[:space:]]*delete[[:space:]]+from[[:space:]]*.*", REG_EXTENDED | REG_ICASE)) {
54,799,127✔
272
    pre = "Delete OK";
81✔
273
  } else if (shellRegexMatch(command, "^[[:space:]]*insert[[:space:]]+into[[:space:]]*.*", REG_EXTENDED | REG_ICASE)) {
54,799,046✔
274
    pre = "Insert OK";
7,449✔
275
  } else if (shellRegexMatch(command, "^[[:space:]]*create[[:space:]]*.*", REG_EXTENDED | REG_ICASE)) {
54,791,597✔
276
    pre = "Create OK";
6,800✔
277
  } else if (shellRegexMatch(command, "^[[:space:]]*drop[[:space:]]*.*", REG_EXTENDED | REG_ICASE)) {
54,784,797✔
278
    pre = "Drop OK";
1,173✔
279
  }
280

281
  TAOS_FIELD *pFields = taos_fetch_fields(pSql);
54,799,127✔
282
  if (pFields != NULL) {  // select and show kinds of commands
54,799,127✔
283
    int32_t error_no = 0;
53,268,948✔
284

285
    int64_t numOfRows = shellDumpResult(pSql, fname, &error_no, printMode, command);
53,268,948✔
286
    if (numOfRows < 0) {
53,268,948✔
287
      taos_free_result(pSql);
×
288
      return;
×
289
    }
290

291
    et = taosGetTimestampUs();
53,268,948✔
292
    if (error_no == 0) {
53,268,948✔
293
      (void)printf("Query OK, %" PRId64 " row(s) in set (%.6fs)\r\n", numOfRows, (et - st) / 1E6);
53,268,948✔
294
    } else {
295
      (void)printf("Query interrupted (%s), %" PRId64 " row(s) in set (%.6fs)\r\n", tstrerror(error_no), numOfRows,
×
296
             (et - st) / 1E6);
×
297
    }
298
    taos_free_result(pSql);
53,268,948✔
299
  } else {
300
    int64_t num_rows_affacted = taos_affected_rows64(pSql);
1,530,179✔
301
    taos_free_result(pSql);
1,530,179✔
302
    et = taosGetTimestampUs();
1,530,179✔
303
    (void)printf("%s, %" PRId64 " row(s) affected (%.6fs)\r\n", pre, num_rows_affacted, (et - st) / 1E6);
1,530,179✔
304

305
    // call auto tab
306
    callbackAutoTab(command, NULL, false);
1,530,179✔
307
  }
308

309
  (void)printf("\r\n");
54,799,127✔
310
}
311

312
char *shellFormatTimestamp(char *buf, int32_t bufSize, int64_t val, int32_t precision) {
922,204,472✔
313
  if (shell.args.is_raw_time) {
922,204,472✔
314
    (void)sprintf(buf, "%" PRId64, val);
28,365✔
315
    return buf;
28,365✔
316
  }
317

318
  time_t  tt;
921,682,486✔
319
  int32_t ms = 0;
922,176,107✔
320
  if (precision == TSDB_TIME_PRECISION_NANO) {
922,176,107✔
321
    tt = (time_t)(val / 1000000000);
1,600✔
322
    ms = val % 1000000000;
1,600✔
323
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
922,174,507✔
324
    tt = (time_t)(val / 1000000);
1,600✔
325
    ms = val % 1000000;
1,600✔
326
  } else {
327
    tt = (time_t)(val / 1000);
922,172,907✔
328
    ms = val % 1000;
922,172,907✔
329
  }
330

331
  if (tt <= 0 && ms < 0) {
922,176,107✔
332
    tt--;
11,231✔
333
    if (precision == TSDB_TIME_PRECISION_NANO) {
11,231✔
334
      ms += 1000000000;
×
335
    } else if (precision == TSDB_TIME_PRECISION_MICRO) {
11,231✔
336
      ms += 1000000;
×
337
    } else {
338
      ms += 1000;
11,231✔
339
    }
340
  }
341

342
  struct tm ptm = {0};
922,176,107✔
343
  if (taosLocalTime(&tt, &ptm, buf, bufSize, NULL) == NULL) {
922,176,107✔
344
    return buf;
×
345
  }
346
  size_t pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
922,176,107✔
347

348
  if (precision == TSDB_TIME_PRECISION_NANO) {
922,176,107✔
349
    (void)sprintf(buf + pos, ".%09d", ms);
1,600✔
350
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
922,174,507✔
351
    (void)sprintf(buf + pos, ".%06d", ms);
1,600✔
352
  } else {
353
    (void)sprintf(buf + pos, ".%03d", ms);
922,172,907✔
354
  }
355

356
  return buf;
922,176,107✔
357
}
358

359
char *shellDumpHexValue(char *buf, const char *val, int32_t length) {
×
360
  for (int32_t i = 0; i < length; i++) {
×
361
    (void)sprintf(buf + (i * 2), "%02X", val[i]);
×
362
  }
363
  buf[length * 2] = 0;
×
364

365
  return buf;
×
366
}
367

368
void shellDumpFieldToFile(TdFilePtr pFile, const char *val, TAOS_FIELD *field, int32_t length, int32_t precision) {
1,721,709,176✔
369
  if (val == NULL) {
1,721,709,176✔
370
    taosFprintfFile(pFile, "NULL");
16,619,972✔
371
    return;
16,619,972✔
372
  }
373

374
  char    quotationStr[2] = {'"', 0};
1,705,089,204✔
375
  int32_t width;
376

377
  int n = 0;
1,705,089,204✔
378
#define LENGTH 64
379
  char buf[LENGTH] = {0};
1,705,089,204✔
380
  switch (field->type) {
1,705,089,204✔
381
    case TSDB_DATA_TYPE_BOOL:
318,707,784✔
382
      taosFprintfFile(pFile, "%d", ((((int32_t)(*((char *)val))) == 1) ? 1 : 0));
318,707,784✔
383
      break;
318,707,784✔
384
    case TSDB_DATA_TYPE_TINYINT:
20,396,332✔
385
      taosFprintfFile(pFile, "%d", *((int8_t *)val));
20,396,332✔
386
      break;
20,396,332✔
387
    case TSDB_DATA_TYPE_UTINYINT:
818,892✔
388
      taosFprintfFile(pFile, "%u", *((uint8_t *)val));
818,892✔
389
      break;
818,892✔
390
    case TSDB_DATA_TYPE_SMALLINT:
2,455,182✔
391
      taosFprintfFile(pFile, "%d", *((int16_t *)val));
2,455,182✔
392
      break;
2,455,182✔
393
    case TSDB_DATA_TYPE_USMALLINT:
815,580✔
394
      taosFprintfFile(pFile, "%u", *((uint16_t *)val));
815,580✔
395
      break;
815,580✔
396
    case TSDB_DATA_TYPE_INT:
169,917,160✔
397
      taosFprintfFile(pFile, "%d", *((int32_t *)val));
169,917,160✔
398
      break;
169,917,160✔
399
    case TSDB_DATA_TYPE_UINT:
2,455,182✔
400
      taosFprintfFile(pFile, "%u", *((uint32_t *)val));
2,455,182✔
401
      break;
2,455,182✔
402
    case TSDB_DATA_TYPE_BIGINT:
203,465,289✔
403
      taosFprintfFile(pFile, "%" PRId64, *((int64_t *)val));
203,465,289✔
404
      break;
203,465,289✔
405
    case TSDB_DATA_TYPE_UBIGINT:
×
406
      taosFprintfFile(pFile, "%" PRIu64, *((uint64_t *)val));
×
407
      break;
×
408
    case TSDB_DATA_TYPE_FLOAT:
20,398,760✔
409
      width = SHELL_FLOAT_WIDTH;
20,398,760✔
410
      if (tsEnableScience) {
20,398,760✔
411
        taosFprintfFile(pFile, "%*.7e", width, GET_FLOAT_VAL(val));
×
412
      } else {
413
        n = tsnprintf(buf, LENGTH, "%*.7f", width, GET_FLOAT_VAL(val));
20,398,760✔
414
        if (n > SHELL_FLOAT_WIDTH) {
20,398,760✔
415
          taosFprintfFile(pFile, "%*.7e", width, GET_FLOAT_VAL(val));
348,588✔
416
        } else {
417
          taosFprintfFile(pFile, "%s", buf);
20,050,172✔
418
        }
419
      }
420
      break;
20,398,760✔
421
    case TSDB_DATA_TYPE_DOUBLE:
273,111,722✔
422
      width = SHELL_DOUBLE_WIDTH;
273,111,722✔
423
      if (tsEnableScience) {
273,111,722✔
424
        (void)snprintf(buf, LENGTH, "%*.15e", width, GET_DOUBLE_VAL(val));
×
425
        taosFprintfFile(pFile, "%s", buf);
×
426
      } else {
427
        n = tsnprintf(buf, LENGTH, "%*.15f", width, GET_DOUBLE_VAL(val));
273,111,722✔
428
        if (n > SHELL_DOUBLE_WIDTH) {
273,111,722✔
429
          taosFprintfFile(pFile, "%*.15e", width, GET_DOUBLE_VAL(val));
141,205,884✔
430
        } else {
431
          taosFprintfFile(pFile, "%s", buf);
131,905,838✔
432
        }
433
      }
434
      break;
273,111,722✔
435
    case TSDB_DATA_TYPE_BINARY:
167,603,484✔
436
      if (shell.args.is_binary_as_hex && shellHasBinaryNonPrintable(val, length)) {
167,603,484✔
437
        char *tmp = shellAllocHexString(val, length);
354✔
438
        if (tmp == NULL) break;
354✔
439
        taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
354✔
440
        taosMemoryFree(tmp);
354✔
441
        break;
354✔
442
      }
443
      /* falls through */ // printable binary handled as NCHAR/JSON
444
    case TSDB_DATA_TYPE_NCHAR:
445
    case TSDB_DATA_TYPE_JSON: {
446
      int32_t bufIndex = 0;
264,521,742✔
447
      char   *tmp = (char *)taosMemoryCalloc(length * 2 + 1, 1);
264,521,742✔
448
      if (tmp == NULL) break;
264,521,742✔
449
      for (int32_t i = 0; i < length; i++) {
2,147,483,647✔
450
        tmp[bufIndex] = val[i];
2,147,483,647✔
451
        bufIndex++;
2,147,483,647✔
452
        if (val[i] == '\"') {
2,147,483,647✔
453
          tmp[bufIndex] = val[i];
×
454
          bufIndex++;
×
455
        }
456
      }
457
      tmp[bufIndex] = 0;
264,521,742✔
458

459
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
264,521,742✔
460
      taosMemoryFree(tmp);
264,521,742✔
461
    } break;
264,521,742✔
462
    case TSDB_DATA_TYPE_VARBINARY: {
×
463
      void    *tmp = NULL;
×
464
      uint32_t size = 0;
×
465
      if (taosAscii2Hex(val, length, &tmp, &size) < 0) {
×
466
        break;
×
467
      }
468
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
×
469
      taosMemoryFree(tmp);
×
470
      break;
×
471
    }
472
    case TSDB_DATA_TYPE_GEOMETRY: {
×
473
      char *tmp = (char *)taosMemoryCalloc(length * 2 + 1, 1);
×
474
      if (tmp == NULL) break;
×
475
      shellDumpHexValue(tmp, val, length);
×
476
      taosFprintfFile(pFile, "%s", buf);
×
477
      taosMemoryFree(tmp);
×
478
      break;
×
479
    }
480
    case TSDB_DATA_TYPE_TIMESTAMP:
196,972,494✔
481
      shellFormatTimestamp(buf, sizeof(buf), *(int64_t *)val, precision);
196,972,494✔
482
      taosFprintfFile(pFile, "%s%s%s", quotationStr, buf, quotationStr);
196,972,494✔
483
      break;
196,972,494✔
484
    case TSDB_DATA_TYPE_DECIMAL64:
231,052,731✔
485
    case TSDB_DATA_TYPE_DECIMAL:
486
      taosFprintfFile(pFile, "%s", val);
231,052,731✔
487
      break;
231,052,731✔
488
    case TSDB_DATA_TYPE_BLOB:
×
489
    case TSDB_DATA_TYPE_MEDIUMBLOB: {
490
      void    *tmp = NULL;
×
491
      uint32_t size = 0;
×
492
      if (taosAscii2Hex(val, length, &tmp, &size) < 0) {
×
493
        break;
×
494
      }
495
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
×
496
      taosMemoryFree(tmp);
×
497

498
      break;
×
499
    }
500
    default:
×
501
      break;
×
502
  }
503
}
504

505
int64_t shellDumpResultToFile(const char *fname, TAOS_RES *tres) {
805,513✔
506
  char fullname[PATH_MAX] = {0};
805,513✔
507
  if (taosExpandDir(fname, fullname, PATH_MAX) != 0) {
805,513✔
508
    tstrncpy(fullname, fname, PATH_MAX);
×
509
  }
510

511
  TAOS_ROW row = taos_fetch_row(tres);
805,513✔
512
  if (row == NULL) {
805,513✔
513
    return 0;
×
514
  }
515

516
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_TRUNC | TD_FILE_STREAM);
805,513✔
517
  if (pFile == NULL) {
805,513✔
518
    (void)fprintf(stderr, "failed to open file: %s\r\n", fullname);
×
519
    return -1;
×
520
  }
521

522
  TAOS_FIELD *fields = taos_fetch_fields(tres);
805,513✔
523
  int32_t     num_fields = taos_num_fields(tres);
805,513✔
524
  int32_t     precision = taos_result_precision(tres);
805,513✔
525

526
  for (int32_t col = 0; col < num_fields; col++) {
2,034,576✔
527
    if (col > 0) {
1,229,063✔
528
      taosFprintfFile(pFile, ",");
423,550✔
529
    }
530
    taosFprintfFile(pFile, "%s", fields[col].name);
1,229,063✔
531
  }
532
  taosFprintfFile(pFile, "\r\n");
805,513✔
533

534
  int64_t numOfRows = 0;
805,513✔
535
  do {
536
    int32_t *length = taos_fetch_lengths(tres);
778,104,941✔
537
    for (int32_t i = 0; i < num_fields; i++) {
2,147,483,647✔
538
      if (i > 0) {
1,721,709,176✔
539
        taosFprintfFile(pFile, ",");
943,604,235✔
540
      }
541
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision);
1,721,709,176✔
542
    }
543
    taosFprintfFile(pFile, "\r\n");
778,104,941✔
544

545
    numOfRows++;
778,104,941✔
546
    row = taos_fetch_row(tres);
778,104,941✔
547
  } while (row != NULL);
778,104,941✔
548

549
  taosCloseFile(&pFile);
805,513✔
550

551
  return numOfRows;
805,513✔
552
}
553

554
static bool shellHasBinaryNonPrintable(const char *val, int32_t length) {
2,687✔
555
  for (int32_t i = 0; i < length; i++) {
4,552✔
556
    unsigned char c = (unsigned char)val[i];
3,129✔
557

558
    if (c < 0x20 || c == 0x7F) {
3,129✔
559
      return true;
1,264✔
560
    }
561
  }
562

563
  int32_t pos = 0;
1,423✔
564
  while (pos < length) {
2,229✔
565
    TdWchar wc;
1,688✔
566
    int32_t remain = length - pos;
1,688✔
567
    int32_t bytes = taosMbToWchar(&wc, val + pos, TMIN(MB_CUR_MAX, remain));
1,688✔
568
    if (bytes <= 0) {
1,688✔
569
      return true;
882✔
570
    }
571

572
    if (wc == 0x7F || (wc >= 0x80 && wc <= 0x9F)) {
806✔
573
      return true;
×
574
    }
575

576
    if (taosWcharWidth(wc) <= 0) {
806✔
577
      return true;
×
578
    }
579

580
    pos += bytes;
806✔
581
  }
582

583
  return false;
541✔
584
}
585

586
static void shellHexEncode(char *dst, const char *val, int32_t length) {
2,146✔
587
  static const char hexMap[] = "0123456789ABCDEF";
588

589
  for (int32_t i = 0; i < length; i++) {
5,271✔
590
    unsigned char c = (unsigned char)val[i];
3,125✔
591
    dst[i * 2] = hexMap[c >> 4];
3,125✔
592
    dst[i * 2 + 1] = hexMap[c & 0x0F];
3,125✔
593
  }
594

595
  dst[length * 2] = 0;
2,146✔
596
}
2,146✔
597

598
static char *shellAllocHexString(const char *val, int32_t length) {
2,146✔
599
  int32_t hexLen = 2 + length * 2;
2,146✔
600
  char   *hexBuf = (char *)taosMemoryCalloc(1, hexLen + 1);
2,146✔
601
  if (hexBuf == NULL) {
2,146✔
602
    return NULL;
×
603
  }
604

605
  hexBuf[0] = '0';
2,146✔
606
  hexBuf[1] = 'x';
2,146✔
607
  shellHexEncode(hexBuf + 2, val, length);
2,146✔
608
  return hexBuf;
2,146✔
609
}
610

611
static void shellPrintHex(const char *val, int32_t length, int32_t width) {
1,792✔
612
  char *hexBuf = shellAllocHexString(val, length);
1,792✔
613
  if (hexBuf == NULL) return;
1,792✔
614

615
  shellPrintString(hexBuf, width > 0 ? width : 0);
1,792✔
616

617
  taosMemoryFree(hexBuf);
1,792✔
618
}
619

620
void shellPrintNChar(const char *str, int32_t length, int32_t width) {
354,119,767✔
621
  TdWchar tail[3];
353,906,153✔
622
  int32_t pos = 0, cols = 0, totalCols = 0, tailLen = 0;
354,119,767✔
623

624
  while (pos < length) {
2,147,483,647✔
625
    TdWchar wc;
2,147,483,647✔
626
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
2,147,483,647✔
627
    if (bytes <= 0) {
2,147,483,647✔
628
      break;
190,660✔
629
    }
630

631
    if (pos + bytes > length) {
2,147,483,647✔
632
      break;
×
633
    }
634
    int w = 0;
2,147,483,647✔
635
    if (*(str + pos) == '\t' || *(str + pos) == '\n' || *(str + pos) == '\r') {
2,147,483,647✔
636
      w = bytes;
×
637
    } else {
638
      w = taosWcharWidth(wc);
2,147,483,647✔
639
    }
640
    pos += bytes;
2,147,483,647✔
641

642
    if (w <= 0) {
2,147,483,647✔
643
      continue;
6,155,669✔
644
    }
645

646
    if (width <= 0) {
2,147,483,647✔
647
      (void)printf("%lc", wc);
272,252,385✔
648
      continue;
272,252,385✔
649
    }
650

651
    totalCols += w;
2,147,483,647✔
652
    if (totalCols > width) {
2,147,483,647✔
653
      break;
1,148,983✔
654
    }
655
    if (totalCols <= (width - 3)) {
2,147,483,647✔
656
      (void)printf("%lc", wc);
2,147,483,647✔
657
      cols += w;
2,147,483,647✔
658
    } else {
659
      tail[tailLen] = wc;
3,706,309✔
660
      tailLen++;
3,706,309✔
661
    }
662
  }
663

664
  if (totalCols > width) {
354,119,767✔
665
    // width could be 1 or 2, so printf("...") cannot be used
666
    for (int32_t i = 0; i < 3; i++) {
4,595,932✔
667
      if (cols >= width) {
3,446,949✔
668
        break;
×
669
      }
670
      putchar('.');
3,446,949✔
671
      ++cols;
3,446,949✔
672
    }
673
  } else {
674
    for (int32_t i = 0; i < tailLen; i++) {
353,235,382✔
675
      (void)printf("%lc", tail[i]);
264,598✔
676
    }
677
    cols = totalCols;
352,970,784✔
678
  }
679

680
  for (; cols < width; cols++) {
2,147,483,647✔
681
    putchar(' ');
2,147,483,647✔
682
  }
683
}
354,119,767✔
684

685
void shellPrintString(const char *str, int32_t width) {
1,689,524,087✔
686
  int32_t len = strlen(str);
1,689,524,087✔
687

688
  if (width == 0) {
1,689,524,087✔
689
    (void)printf("%s", str);
×
690
  } else if (len > width) {
1,689,524,087✔
691
    if (width <= 3) {
8,016✔
692
      (void)printf("%.*s.", width - 1, str);
7,539✔
693
    } else {
694
      (void)printf("%.*s...", width - 3, str);
477✔
695
    }
696
  } else {
697
    (void)printf("%s%*.s", str, width - len, "");
1,689,516,071✔
698
  }
699
}
1,689,524,087✔
700

701
void shellPrintGeometry(const unsigned char *val, int32_t length, int32_t width) {
954✔
702
  if (length == 0) {  // empty value
954✔
703
    shellPrintString("", width);
×
704
    return;
×
705
  }
706

707
  int32_t code = TSDB_CODE_FAILED;
954✔
708

709
  code = initCtxAsText();
954✔
710
  if (code != TSDB_CODE_SUCCESS) {
954✔
711
    shellPrintString(getGeosErrMsg(code), width);
×
712
    return;
×
713
  }
714

715
  char *outputWKT = NULL;
954✔
716
  code = doAsText(val, length, &outputWKT);
954✔
717
  if (code != TSDB_CODE_SUCCESS) {
954✔
718
    shellPrintString(getGeosErrMsg(code), width);  // should NOT happen
×
719
    return;
×
720
  }
721

722
  shellPrintString(outputWKT, width);
954✔
723

724
  geosFreeBuffer(outputWKT);
954✔
725
}
726

727
void shellPrintField(const char *val, TAOS_FIELD *field, int32_t width, int32_t length, int32_t precision) {
2,147,483,647✔
728
  if (val == NULL) {
2,147,483,647✔
729
    shellPrintString(TSDB_DATA_NULL_STR, width);
1,427,855,232✔
730
    return;
1,427,855,232✔
731
  }
732

733
  int n = 0;
2,147,483,647✔
734
#define LENGTH 64
735
  char buf[LENGTH] = {0};
2,147,483,647✔
736
  switch (field->type) {
2,147,483,647✔
737
    case TSDB_DATA_TYPE_BOOL:
261,666,109✔
738
      shellPrintString(((((int32_t)(*((char *)val))) == TSDB_FALSE) ? "false" : "true"), width);
261,666,109✔
739
      break;
261,666,109✔
740
    case TSDB_DATA_TYPE_TINYINT:
69,169,072✔
741
      (void)printf("%*d", width, *((int8_t *)val));
69,169,072✔
742
      break;
69,169,072✔
743
    case TSDB_DATA_TYPE_UTINYINT:
152,643,086✔
744
      (void)printf("%*u", width, *((uint8_t *)val));
152,643,086✔
745
      break;
152,643,086✔
746
    case TSDB_DATA_TYPE_SMALLINT:
54,586,258✔
747
      (void)printf("%*d", width, *((int16_t *)val));
54,586,258✔
748
      break;
54,586,258✔
749
    case TSDB_DATA_TYPE_USMALLINT:
133,179,357✔
750
      (void)printf("%*u", width, *((uint16_t *)val));
133,179,357✔
751
      break;
133,179,357✔
752
    case TSDB_DATA_TYPE_INT:
180,059,687✔
753
      (void)printf("%*d", width, *((int32_t *)val));
180,059,687✔
754
      break;
180,059,687✔
755
    case TSDB_DATA_TYPE_UINT:
186,216,017✔
756
      (void)printf("%*u", width, *((uint32_t *)val));
186,216,017✔
757
      break;
186,216,017✔
758
    case TSDB_DATA_TYPE_BIGINT:
598,550,961✔
759
      (void)printf("%*" PRId64, width, taosGetInt64Aligned((int64_t *)val));
598,550,961✔
760
      break;
598,550,961✔
761
    case TSDB_DATA_TYPE_UBIGINT:
194,659,243✔
762
      (void)printf("%*" PRIu64, width, taosGetUInt64Aligned((uint64_t *)val));
194,659,243✔
763
      break;
194,659,243✔
764
    case TSDB_DATA_TYPE_FLOAT:
85,737,096✔
765
      width = width >= LENGTH ? LENGTH - 1 : width;
85,737,096✔
766
      if (tsEnableScience) {
85,737,096✔
767
        (void)printf("%*.7e", width, taosGetFloatAligned((float *)val));
×
768
      } else {
769
        (void)snprintf(buf, LENGTH, "%*.*g", width, FLT_DIG, taosGetFloatAligned((float *)val));
85,737,096✔
770
        (void)printf("%s", buf);
85,737,096✔
771
      }
772
      break;
85,737,096✔
773
    case TSDB_DATA_TYPE_DOUBLE:
386,681,263✔
774
      width = width >= LENGTH ? LENGTH - 1 : width;
386,681,263✔
775
      if (tsEnableScience) {
386,681,263✔
776
        (void)snprintf(buf, LENGTH, "%*.15e", width, taosGetDoubleAligned((double *)val));
×
777
        (void)printf("%s", buf);
×
778
      } else {
779
        (void)snprintf(buf, LENGTH, "%*.*g", width, DBL_DIG, taosGetDoubleAligned((double *)val));
386,681,263✔
780
        (void)printf("%*s", width, buf);
386,681,263✔
781
      }
782
      break;
386,681,263✔
783
    case TSDB_DATA_TYPE_VARBINARY: {
×
784
      void    *data = NULL;
×
785
      uint32_t size = 0;
×
786
      if (taosAscii2Hex(val, length, &data, &size) < 0) {
×
787
        break;
×
788
      }
789
      shellPrintNChar(data, size, width);
×
790
      taosMemoryFree(data);
×
791
      break;
×
792
    }
793
    case TSDB_DATA_TYPE_BINARY:
181,268,342✔
794
      if (shell.args.is_binary_as_hex && shellHasBinaryNonPrintable(val, length)) {
181,268,342✔
795
        shellPrintHex(val, length, width);
1,792✔
796
      } else {
797
        shellPrintNChar(val, length, width);
181,266,550✔
798
      }
799
      break;
181,268,342✔
800
    case TSDB_DATA_TYPE_NCHAR:
172,853,217✔
801
    case TSDB_DATA_TYPE_JSON:
802
      shellPrintNChar(val, length, width);
172,853,217✔
803
      break;
172,853,217✔
804
    case TSDB_DATA_TYPE_GEOMETRY:
954✔
805
      shellPrintGeometry(val, length, width);
954✔
806
      break;
954✔
807
    case TSDB_DATA_TYPE_TIMESTAMP:
725,231,978✔
808
      shellFormatTimestamp(buf, sizeof(buf), taosGetInt64Aligned((int64_t *)val), precision);
725,231,978✔
809
      (void)printf("%s", buf);
725,231,978✔
810
      break;
725,231,978✔
811

812
    case TSDB_DATA_TYPE_BLOB:
×
813
    case TSDB_DATA_TYPE_MEDIUMBLOB: {
814
      void    *data = NULL;
×
815
      uint32_t size = 0;
×
816
      if (taosAscii2Hex(val, length, &data, &size) < 0) {
×
817
        break;
×
818
      }
819
      shellPrintNChar(data, size, width);
×
820
      taosMemoryFree(data);
×
821
      break;
×
822
    }
823
    case TSDB_DATA_TYPE_DECIMAL:
176✔
824
    case TSDB_DATA_TYPE_DECIMAL64:
825
      (void)printf("%*s", width, val);
176✔
826
    default:
176✔
827
      break;
176✔
828
  }
829
}
830

831
// show whole result for this query return true, like limit or describe
832
bool shellIsShowWhole(const char *sql) {
558✔
833
  // limit
834
  char * p = taosStrCaseStr(sql, " limit ");
558✔
835
  if (p != NULL) {
558✔
836
    // except subquery, like "select * from (select * from t limit 10) limit 3", only the last limit is valid
837
    char * p1 = taosStrCaseStr(p + 7, ")");
279✔
838
    if (p1 == NULL) {
279✔
839
      return true;
93✔
840
    }
841
    if (taosStrCaseStr(p1 + 1, " limit ")) {
186✔
842
      return true;
93✔
843
    }
844
  }
845
  // describe
846
  if (taosStrCaseStr(sql, "describe ") != NULL) {
372✔
847
    return true;
93✔
848
  }
849
  // desc
850
  if (taosStrCaseStr(sql, "desc ") != NULL) {
279✔
851
    return true;
93✔
852
  }
853
  // show
854
  if (taosStrCaseStr(sql, "show ") != NULL) {
186✔
855
    return true;
×
856
  }
857
  // explain
858
  if (taosStrCaseStr(sql, "explain ") != NULL) {
186✔
859
    return true;
93✔
860
  }
861

862
  return false;
93✔
863
}
864

865
bool shellIsShowQuery(const char *sql) {
93✔
866
  // todo refactor
867
  if (taosStrCaseStr(sql, "show ") != NULL) {
93✔
868
    return true;
×
869
  }
870

871
  return false;
93✔
872
}
873

874
void init_dump_info(tsDumpInfo *dump_info, TAOS_RES *tres, const char *sql, bool vertical) {
52,463,435✔
875
  dump_info->sql = sql;
52,463,435✔
876
  dump_info->vertical = vertical;
52,463,435✔
877
  tsem_init(&dump_info->sem, 0, 0);
52,463,435✔
878
  dump_info->numOfAllRows = 0;
52,463,435✔
879

880
  dump_info->numFields = taos_num_fields(tres);
52,463,435✔
881
  dump_info->fields = taos_fetch_fields(tres);
52,463,435✔
882
  dump_info->precision = taos_result_precision(tres);
52,463,435✔
883

884
  dump_info->resShowMaxNum = UINT64_MAX;
52,463,435✔
885

886
  if (shell.args.commands == NULL && shell.args.file[0] == 0 && !shellIsShowWhole(dump_info->sql)) {
52,463,435✔
887
    dump_info->resShowMaxNum = SHELL_DEFAULT_RES_SHOW_NUM;
93✔
888
  }
889

890
  if (vertical) {
52,463,435✔
891
    dump_info->maxColNameLen = 0;
154,547✔
892
    for (int32_t col = 0; col < dump_info->numFields; col++) {
317,367✔
893
      int32_t len = (int32_t)strlen(dump_info->fields[col].name);
162,820✔
894
      if (len > dump_info->maxColNameLen) {
162,820✔
895
        dump_info->maxColNameLen = len;
157,047✔
896
      }
897
    }
898
  } else {
899
    for (int32_t col = 0; col < dump_info->numFields; col++) {
148,219,491✔
900
      dump_info->width[col] = shellCalcColWidth(dump_info->fields + col, dump_info->precision);
95,910,603✔
901
    }
902
    // set an appropriate width for token and totp_secret display
903
    if (shellRegexMatch(sql, "^[\t ]*create[ \t]+token[ \t]+.*", REG_EXTENDED | REG_ICASE)) {
52,308,888✔
904
      dump_info->width[0] = TMAX(dump_info->width[0], SHELL_SHOW_TOKEN_DISPLAY_WIDTH);
×
905
    } else if (shellRegexMatch(sql, "^[\t ]*create[ \t]+totp_secret[ \t]+.*", REG_EXTENDED | REG_ICASE)) {
52,308,888✔
906
      dump_info->width[0] = TMAX(dump_info->width[0], SHELL_SHOW_TOTP_SECRET_DISPLAY_WIDTH);
×
907
    }
908
  }
909
}
52,463,435✔
910

911
void shellVerticalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
154,547✔
912
  TAOS_ROW row = taos_fetch_row(tres);
154,547✔
913
  if (row == NULL) {
154,547✔
914
    (void)printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
915
    return;
×
916
  }
917

918
  int64_t numOfPintRows = dump_info->numOfAllRows;
154,547✔
919
  int     numOfPrintRowsThisOne = 0;
154,547✔
920

921
  while (row != NULL) {
3,872,516✔
922
    (void)printf("*************************** %" PRId64 ".row ***************************\r\n", numOfPintRows + 1);
3,872,516✔
923

924
    int32_t *length = taos_fetch_lengths(tres);
3,872,516✔
925

926
    for (int32_t i = 0; i < dump_info->numFields; i++) {
7,762,509✔
927
      TAOS_FIELD *field = dump_info->fields + i;
3,889,993✔
928

929
      int32_t padding = (int32_t)(dump_info->maxColNameLen - strlen(field->name));
3,889,993✔
930
      (void)printf("%*.s%s: ", padding, " ", field->name);
3,889,993✔
931

932
      shellPrintField((const char *)row[i], field, 0, length[i], dump_info->precision);
3,889,993✔
933
      putchar('\r');
3,889,993✔
934
      putchar('\n');
3,889,993✔
935
    }
936

937
    numOfPintRows++;
3,872,516✔
938
    numOfPrintRowsThisOne++;
3,872,516✔
939

940
    if (numOfPintRows == dump_info->resShowMaxNum) {
3,872,516✔
941
      (void)printf("\r\n");
×
942
      (void)printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
×
943
      (void)printf("         You can use the `LIMIT` clause to get fewer result to show.\r\n");
×
944
      (void)printf("           Or use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
945
      (void)printf("\r\n");
×
946
      (void)printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
×
947
      (void)printf("\r\n");
×
948
      return;
×
949
    }
950

951
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
3,872,516✔
952
      return;
154,547✔
953
    }
954

955
    row = taos_fetch_row(tres);
3,717,969✔
956
  }
957
  return;
×
958
}
959

960
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
95,910,603✔
961
  int32_t width = (int32_t)strlen(field->name);
95,910,603✔
962

963
  switch (field->type) {
95,910,603✔
964
    case TSDB_DATA_TYPE_NULL:
×
965
      return TMAX(4, width);  // null
×
966
    case TSDB_DATA_TYPE_BOOL:
22,274,449✔
967
      return TMAX(5, width);  // 'false'
22,274,449✔
968

969
    case TSDB_DATA_TYPE_TINYINT:
5,017,811✔
970
    case TSDB_DATA_TYPE_UTINYINT:
971
      return TMAX(4, width);  // '-127'
5,017,811✔
972

973
    case TSDB_DATA_TYPE_SMALLINT:
3,951,441✔
974
    case TSDB_DATA_TYPE_USMALLINT:
975
      return TMAX(6, width);  // '-32767'
3,951,441✔
976

977
    case TSDB_DATA_TYPE_INT:
9,394,785✔
978
    case TSDB_DATA_TYPE_UINT:
979
      return TMAX(11, width);  // '-2147483648'
9,394,785✔
980

981
    case TSDB_DATA_TYPE_BIGINT:
9,382,749✔
982
    case TSDB_DATA_TYPE_UBIGINT:
983
      return TMAX(21, width);  // '-9223372036854775807'
9,382,749✔
984

985
    case TSDB_DATA_TYPE_FLOAT:
2,576,529✔
986
      return TMAX(SHELL_FLOAT_WIDTH, width);
2,576,529✔
987

988
    case TSDB_DATA_TYPE_DOUBLE:
8,943,520✔
989
      return TMAX(SHELL_DOUBLE_WIDTH, width);
8,943,520✔
990

991
    case TSDB_DATA_TYPE_BINARY:
6,292,006✔
992
    case TSDB_DATA_TYPE_GEOMETRY:
993
      if (field->bytes > shell.args.displayWidth) {
6,292,006✔
994
        return TMAX(shell.args.displayWidth, width);
4,231,256✔
995
      } else {
996
        return TMAX(field->bytes + 2, width);
2,060,750✔
997
      }
998
    case TSDB_DATA_TYPE_VARBINARY: {
1,072✔
999
      int32_t bytes = field->bytes * 2 + 2;
1,072✔
1000
      if (bytes > shell.args.displayWidth) {
1,072✔
1001
        return TMAX(shell.args.displayWidth, width);
×
1002
      } else {
1003
        return TMAX(bytes + 2, width);
1,072✔
1004
      }
1005
    }
1006
    case TSDB_DATA_TYPE_NCHAR:
4,126,319✔
1007
    case TSDB_DATA_TYPE_JSON: {
1008
      uint16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
4,126,319✔
1009
      if (bytes > shell.args.displayWidth) {
4,126,319✔
1010
        return TMAX(shell.args.displayWidth, width);
4,126,319✔
1011
      } else {
1012
        return TMAX(bytes + 2, width);
×
1013
      }
1014
    }
1015

1016
    case TSDB_DATA_TYPE_TIMESTAMP:
23,949,746✔
1017
      if (shell.args.is_raw_time) {
23,949,746✔
1018
        return TMAX(14, width);
547✔
1019
      }
1020
      if (precision == TSDB_TIME_PRECISION_NANO) {
23,949,199✔
1021
        return TMAX(29, width);
160✔
1022
      } else if (precision == TSDB_TIME_PRECISION_MICRO) {
23,949,039✔
1023
        return TMAX(26, width);  // '2020-01-01 00:00:00.000000'
160✔
1024
      } else {
1025
        return TMAX(23, width);  // '2020-01-01 00:00:00.000'
23,948,879✔
1026
      }
1027
    case TSDB_DATA_TYPE_BLOB:
×
1028
    case TSDB_DATA_TYPE_MEDIUMBLOB: {
1029
      int32_t bytes = TSDB_MAX_BLOB_LEN;
×
1030
      if (bytes > shell.args.displayWidth) {
×
1031
        return TMAX(shell.args.displayWidth, width);
×
1032
      } else {
1033
        return TMAX(bytes + 2, width);
×
1034
      }
1035
    } break;
1036

1037
    case TSDB_DATA_TYPE_DECIMAL64:
88✔
1038
      return TMAX(width, 20);
88✔
1039
    case TSDB_DATA_TYPE_DECIMAL:
88✔
1040
      return TMAX(width, 40);
88✔
1041
    default:
×
1042
      ASSERT(false);
×
1043
  }
1044

1045
  return 0;
×
1046
}
1047

1048
void shellPrintHeader(TAOS_FIELD *fields, int32_t *width, int32_t num_fields) {
37,230,143✔
1049
  int32_t rowWidth = 0;
37,230,143✔
1050
  for (int32_t col = 0; col < num_fields; col++) {
112,852,247✔
1051
    TAOS_FIELD *field = fields + col;
75,622,104✔
1052
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
75,622,104✔
1053
    int32_t     left = padding / 2;
75,622,104✔
1054
    (void)printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
75,622,104✔
1055
    rowWidth += width[col] + 3;
75,622,104✔
1056
  }
1057

1058
  putchar('\r');
37,230,143✔
1059
  putchar('\n');
37,230,143✔
1060
  for (int32_t i = 0; i < rowWidth; i++) {
2,147,483,647✔
1061
    putchar('=');
2,147,483,647✔
1062
  }
1063
  putchar('\r');
37,230,143✔
1064
  putchar('\n');
37,230,143✔
1065
}
37,230,143✔
1066

1067
void shellHorizontalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
38,815,014✔
1068
  TAOS_ROW row = taos_fetch_row(tres);
38,815,014✔
1069
  if (row == NULL) {
38,815,014✔
1070
    (void)printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
1071
    return;
×
1072
  }
1073

1074
  int64_t numOfPintRows = dump_info->numOfAllRows;
38,815,014✔
1075
  int     numOfPrintRowsThisOne = 0;
38,815,014✔
1076
  if (numOfPintRows == 0) {
38,815,014✔
1077
    shellPrintHeader(dump_info->fields, dump_info->width, dump_info->numFields);
37,230,143✔
1078
  }
1079

1080
  while (row != NULL) {
700,067,216✔
1081
    int32_t *length = taos_fetch_lengths(tres);
700,067,216✔
1082
    for (int32_t i = 0; i < dump_info->numFields; i++) {
2,147,483,647✔
1083
      putchar(' ');
2,147,483,647✔
1084
      shellPrintField((const char *)row[i], dump_info->fields + i, dump_info->width[i], length[i],
2,147,483,647✔
1085
                      dump_info->precision);
1086
      putchar(' ');
2,147,483,647✔
1087
      putchar('|');
2,147,483,647✔
1088
    }
1089
    putchar('\r');
700,067,216✔
1090
    putchar('\n');
700,067,216✔
1091

1092
    numOfPintRows++;
700,067,216✔
1093
    numOfPrintRowsThisOne++;
700,067,216✔
1094

1095
    if (numOfPintRows == dump_info->resShowMaxNum) {
700,067,216✔
1096
      (void)printf("\r\n");
93✔
1097
      (void)printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
93✔
1098
      if (shellIsShowQuery(dump_info->sql)) {
93✔
1099
        (void)printf("         You can use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
1100
      } else {
1101
        (void)printf("         You can use the `LIMIT` clause to get fewer result to show.\r\n");
93✔
1102
        (void)printf("           Or use '>>' to redirect the whole set of the result to a specified file.\r\n");
93✔
1103
      }
1104
      (void)printf("\r\n");
93✔
1105
      (void)printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
93✔
1106
      (void)printf("\r\n");
93✔
1107
      return;
93✔
1108
    }
1109

1110
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
700,067,123✔
1111
      return;
38,814,921✔
1112
    }
1113

1114
    row = taos_fetch_row(tres);
661,252,202✔
1115
  }
1116
  return;
×
1117
}
1118

1119
void shellDumpResultCallback(void *param, TAOS_RES *tres, int num_of_rows) {
91,432,996✔
1120
  tsDumpInfo *dump_info = (tsDumpInfo *)param;
91,432,996✔
1121
  if (num_of_rows > 0) {
91,432,996✔
1122
    dump_info->numOfRows = num_of_rows;
38,969,561✔
1123
    if (dump_info->numOfAllRows < dump_info->resShowMaxNum) {
38,969,561✔
1124
      if (dump_info->vertical) {
38,969,561✔
1125
        shellVerticalPrintResult(tres, dump_info);
154,547✔
1126
      } else {
1127
        shellHorizontalPrintResult(tres, dump_info);
38,815,014✔
1128
      }
1129
    }
1130
    dump_info->numOfAllRows += num_of_rows;
38,969,561✔
1131
    if (!shellCmdkilled) {
38,969,561✔
1132
      taos_fetch_rows_a(tres, shellDumpResultCallback, param);
38,969,561✔
1133
    } else {
1134
      tsem_post(&dump_info->sem);
×
1135
    }
1136
  } else {
1137
    if (num_of_rows < 0) {
52,463,435✔
1138
      (void)printf("\033[31masync retrieve failed, code: %d, %s\033[0m\n", num_of_rows, tstrerror(num_of_rows));
×
1139
    }
1140
    tsem_post(&dump_info->sem);
52,463,435✔
1141
  }
1142
}
91,432,996✔
1143

1144
int64_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
53,268,948✔
1145
  int64_t num_of_rows = 0;
53,268,948✔
1146
  if (fname != NULL) {
53,268,948✔
1147
    num_of_rows = shellDumpResultToFile(fname, tres);
805,513✔
1148
  } else {
1149
    tsDumpInfo dump_info;
47,658,826✔
1150
    if (!shellCmdkilled) {
52,463,435✔
1151
      init_dump_info(&dump_info, tres, sql, vertical);
52,463,435✔
1152
      taos_fetch_rows_a(tres, shellDumpResultCallback, &dump_info);
52,463,435✔
1153
      tsem_wait(&dump_info.sem);
52,463,435✔
1154
      num_of_rows = dump_info.numOfAllRows;
52,463,435✔
1155
    }
1156
  }
1157

1158
  *error_no = shellCmdkilled ? TSDB_CODE_TSC_QUERY_KILLED : taos_errno(tres);
53,268,948✔
1159
  return num_of_rows;
53,268,948✔
1160
}
1161

1162
void shellReadHistory() {
1,228,667✔
1163
  SShellHistory *pHistory = &shell.history;
1,228,667✔
1164
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_READ | TD_FILE_STREAM);
1,228,667✔
1165
  if (pFile == NULL) return;
1,228,667✔
1166

1167
  char   *line = taosMemoryMalloc(tsMaxSQLLength + 1);
1,174,360✔
1168
  int32_t read_size = 0;
1,174,360✔
1169
  while ((read_size = taosGetsFile(pFile, tsMaxSQLLength, line)) > 0) {
216,534,282✔
1170
    line[read_size - 1] = '\0';
215,359,922✔
1171
    taosMemoryFree(pHistory->hist[pHistory->hend]);
215,359,922✔
1172
    pHistory->hist[pHistory->hend] = taosStrdup(line);
215,359,922✔
1173

1174
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
215,359,922✔
1175

1176
    if (pHistory->hend == pHistory->hstart) {
215,359,922✔
1177
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
×
1178
    }
1179
  }
1180

1181
  taosMemoryFreeClear(line);
1,174,360✔
1182
  taosCloseFile(&pFile);
1,174,360✔
1183
  int64_t file_size;
1,172,479✔
1184
  if (taosStatFile(pHistory->file, &file_size, NULL, NULL) == 0 && file_size > SHELL_MAX_COMMAND_SIZE) {
1,174,360✔
1185
    TdFilePtr pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_TRUNC);
×
1186
    if (pFile == NULL) return;
×
1187
    int32_t endIndex = pHistory->hstart;
×
1188
    if (endIndex != 0) {
×
1189
      endIndex = pHistory->hend;
×
1190
    }
1191
    for (int32_t i = (pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE; i != endIndex;) {
×
1192
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
×
1193
      i = (i + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE;
×
1194
    }
1195
    taosFprintfFile(pFile, "%s\n", pHistory->hist[endIndex]);
×
1196

1197
    /* coverity[+retval] */
1198
    taosFsyncFile(pFile);
×
1199
    taosCloseFile(&pFile);
×
1200
  }
1201
  pHistory->hstart = pHistory->hend;
1,174,360✔
1202
}
1203

1204
void shellWriteHistory() {
1,228,667✔
1205
  SShellHistory *pHistory = &shell.history;
1,228,667✔
1206
  if (pHistory->hend == pHistory->hstart) return;
1,228,667✔
1207
  TdFilePtr pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_APPEND);
1,228,501✔
1208
  if (pFile == NULL) return;
1,228,501✔
1209

1210
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
2,457,162✔
1211
    if (pHistory->hist[i] != NULL) {
1,228,661✔
1212
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
1,228,661✔
1213
      taosMemoryFree(pHistory->hist[i]);
1,228,661✔
1214
      pHistory->hist[i] = NULL;
1,228,661✔
1215
    }
1216
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
1,228,661✔
1217
  }
1218
  taosCloseFile(&pFile);
1,228,501✔
1219
}
1220

1221
void shellCleanupHistory() {
1,228,667✔
1222
  SShellHistory *pHistory = &shell.history;
1,228,667✔
1223
  for (int32_t i = 0; i < SHELL_MAX_HISTORY_SIZE; ++i) {
1,229,895,667✔
1224
    if (pHistory->hist[i] != NULL) {
1,228,667,000✔
1225
      taosMemoryFree(pHistory->hist[i]);
215,359,922✔
1226
      pHistory->hist[i] = NULL;
215,359,922✔
1227
    }
1228
  }
1229
}
1,228,667✔
1230

1231
void shellPrintError(TAOS_RES *tres, int64_t st) {
30,685,800✔
1232
  int code = taos_errno(tres);
30,685,800✔
1233
  int64_t et = taosGetTimestampUs();
30,685,800✔
1234
  (void)printf("\r\nDB error: %s [0x%08X] (%.6fs)\r\n", taos_errstr(tres), code, (et - st) / 1E6);
30,685,800✔
1235
  taos_free_result(tres);
30,685,800✔
1236

1237
  // tip
1238
  if (code == TSDB_CODE_MND_USER_PASSWORD_EXPIRED) {
30,685,800✔
1239
    (void)fprintf(stdout, "******************** TIPS ********************\n");
78✔
1240
    (void)fprintf(stdout, "Please reset your password using the `ALTER USER <user_name> PASS 'new_password'` command.\n");
78✔
1241
    (void)fprintf(stdout, "**********************************************\n");
78✔
1242
  }
1243
}
30,685,800✔
1244

1245
bool shellIsCommentLine(char *line) {
84,391,122✔
1246
  if (line == NULL) return true;
84,391,122✔
1247
  return shellRegexMatch(line, "^[[:space:]]*#.*", REG_EXTENDED);
84,391,122✔
1248
}
1249

1250
void shellSourceFile(const char *file) {
165,476✔
1251
  int32_t read_len = 0;
165,476✔
1252
  char   *cmd = taosMemoryCalloc(1, tsMaxSQLLength + 1);
165,476✔
1253
  size_t  cmd_len = 0;
165,476✔
1254
  char    fullname[PATH_MAX] = {0};
165,476✔
1255
  char    sourceFileCommand[PATH_MAX + 8] = {0};
165,476✔
1256

1257
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
165,476✔
1258
    tstrncpy(fullname, file, PATH_MAX);
×
1259
  }
1260

1261
  (void)sprintf(sourceFileCommand, "source %s;", fullname);
165,476✔
1262
  shellRecordCommandToHistory(sourceFileCommand);
165,476✔
1263

1264
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_READ | TD_FILE_STREAM);
165,476✔
1265
  if (pFile == NULL) {
165,476✔
1266
    (void)fprintf(stderr, "failed to open file %s\r\n", fullname);
22,958✔
1267
    taosMemoryFree(cmd);
22,958✔
1268
    return;
22,958✔
1269
  }
1270

1271
  char *line = taosMemoryMalloc(tsMaxSQLLength + 1);
142,518✔
1272
  while ((read_len = taosGetsFile(pFile, tsMaxSQLLength, line)) > 0) {
85,604,366✔
1273
    if (cmd_len + read_len >= tsMaxSQLLength) {
85,461,848✔
1274
      (void)printf("read command line too long over 1M, ignore this line. cmd_len = %d read_len=%d \n", (int32_t)cmd_len,
×
1275
             read_len);
1276
      cmd_len = 0;
×
1277
      memset(line, 0, tsMaxSQLLength + 1);
×
1278
      continue;
×
1279
    }
1280
    line[--read_len] = '\0';
85,461,848✔
1281

1282
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
85,461,848✔
1283
      continue;
1,150,185✔
1284
    }
1285

1286
    if (line[read_len - 1] == '\\') {
84,311,663✔
1287
      line[read_len - 1] = ' ';
×
1288
      memcpy(cmd + cmd_len, line, read_len);
×
1289
      cmd_len += read_len;
×
1290
      continue;
×
1291
    }
1292

1293
    if (line[read_len - 1] == '\r') {
84,311,663✔
1294
      line[--read_len] = '\0';
129,574✔
1295
    }
1296

1297
    memcpy(cmd + cmd_len, line, read_len);
84,311,663✔
1298
    (void)printf("%s%s\r\n", shell.info.promptHeader, cmd);
84,311,663✔
1299
    shellRunCommand(cmd, false);
84,311,663✔
1300
    memset(cmd, 0, tsMaxSQLLength);
84,311,663✔
1301
    cmd_len = 0;
84,311,663✔
1302
  }
1303

1304
  taosMemoryFree(cmd);
142,518✔
1305
  taosMemoryFreeClear(line);
142,518✔
1306
  taosCloseFile(&pFile);
142,518✔
1307
}
1308

1309
int32_t shellGetGrantInfo(char *buf) {
1,015✔
1310
  int32_t verType = TSDB_VERSION_UNKNOWN;
1,015✔
1311
  char    sinfo[256] = {0};
1,015✔
1312
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
1,015✔
1313
  strtok(sinfo, "\r\n");
1,015✔
1314

1315
#ifndef TD_ASTRA
1316
  char sql[] = "show grants";
1,015✔
1317

1318
  TAOS_RES *tres = taos_query(shell.conn, sql);
1,015✔
1319

1320
  int32_t code = taos_errno(tres);
1,015✔
1321
  if (code != TSDB_CODE_SUCCESS) {
1,015✔
1322
    if (code != TSDB_CODE_OPS_NOT_SUPPORT && code != TSDB_CODE_MND_NO_RIGHTS &&
×
1323
        code != TSDB_CODE_PAR_PERMISSION_DENIED) {
1324
      (void)fprintf(stderr, "Failed to check Server Edition, Reason:0x%04x:%s\r\n\r\n", code, taos_errstr(tres));
×
1325
    }
1326
    taos_free_result(tres);
×
1327
    return verType;
×
1328
  }
1329

1330
  int32_t num_fields = taos_field_count(tres);
1,015✔
1331
  if (num_fields == 0) {
1,015✔
1332
    (void)fprintf(stderr, "\r\nInvalid grant information.\r\n");
×
1333
    exit(0);
×
1334
  } else {
1335
    if (tres == NULL) {
1,015✔
1336
      (void)fprintf(stderr, "\r\nGrant information is null.\r\n");
×
1337
      exit(0);
×
1338
    }
1339

1340
    TAOS_FIELD *fields = taos_fetch_fields(tres);
1,015✔
1341
    TAOS_ROW    row = taos_fetch_row(tres);
1,015✔
1342
    if (row == NULL) {
1,015✔
1343
      (void)fprintf(stderr, "\r\nFailed to get grant information from server. Abort.\r\n");
×
1344
      exit(0);
×
1345
    }
1346
    char serverVersion[64] = {0};
1,015✔
1347
    char expiretime[32] = {0};
1,015✔
1348
    char expired[32] = {0};
1,015✔
1349

1350
    tstrncpy(serverVersion, row[0], 64);
1,015✔
1351
    memcpy(expiretime, row[1], fields[1].bytes);
1,015✔
1352
    memcpy(expired, row[2], fields[2].bytes);
1,015✔
1353

1354
    trimStr(serverVersion, "trial");
1,015✔
1355

1356
    if (strcmp(serverVersion, "community") == 0) {
1,015✔
1357
      verType = TSDB_VERSION_OSS;
×
1358
    } else if (strcmp(expiretime, "unlimited") == 0) {
1,015✔
1359
      verType = TSDB_VERSION_ENTERPRISE;
×
1360
      (void)sprintf(buf, "Server is %s %s. License will never expire.\r\n", serverVersion, sinfo);
×
1361
    } else {
1362
      verType = TSDB_VERSION_ENTERPRISE;
1,015✔
1363
      (void)sprintf(buf, "Server is %s %s. License will expire at %s.\r\n", serverVersion, sinfo, expiretime);
1,015✔
1364
    }
1365

1366
    taos_free_result(tres);
1,015✔
1367
  }
1368

1369
  (void)fprintf(stdout, "\r\n");
1,015✔
1370
#else
1371
  verType = TSDB_VERSION_ENTERPRISE;
1372
  (void)sprintf(buf, "Server is %s %s. License will never expire.\r\n", TD_PRODUCT_NAME, sinfo);
1373
#endif
1374
  return verType;
1,015✔
1375
}
1376

1377
#ifdef WINDOWS
1378
BOOL shellQueryInterruptHandler(DWORD fdwCtrlType) {
1379
  tsem_post(&shell.cancelSem);
1380
  return TRUE;
1381
}
1382
#else
1383
void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) { tsem_post(&shell.cancelSem); }
914✔
1384
#endif
1385

1386
void shellCleanup(void *arg) { taosResetTerminalMode(); }
1,015✔
1387

1388
void *shellCancelHandler(void *arg) {
1,015✔
1389
  setThreadName("shellCancelHandler");
1,015✔
1390
  while (1) {
1391
    if (shell.exit == true) {
2,487✔
1392
      break;
1,015✔
1393
    }
1394

1395
    if (tsem_wait(&shell.cancelSem) != 0) {
1,472✔
1396
      taosMsleep(10);
×
1397
      continue;
×
1398
    }
1399

1400
    if (shell.conn) {
1,472✔
1401
      shellCmdkilled = true;
457✔
1402
      taos_kill_query(shell.conn);
457✔
1403
    }
1404

1405
#ifdef WINDOWS
1406
    (void)printf("\n%s", shell.info.promptHeader);
1407
#endif
1408
  }
1409

1410
  return NULL;
1,015✔
1411
}
1412

1413
#pragma GCC diagnostic push
1414
#pragma GCC diagnostic ignored "-Wstringop-overflow"
1415

1416
void *shellThreadLoop(void *arg) {
1,015✔
1417
  setThreadName("shellThreadLoop");
1,015✔
1418
  taosGetOldTerminalMode();
1,015✔
1419
  taosThreadCleanupPush(shellCleanup, NULL);
1,015✔
1420

1421
  do {
1422
    char *command = taosMemoryMalloc(SHELL_MAX_COMMAND_SIZE);
1,015✔
1423
    if (command == NULL) {
1,015✔
1424
      (void)printf("failed to malloc command\r\n");
×
1425
      break;
×
1426
    }
1427

1428
    do {
1429
      memset(command, 0, SHELL_MAX_COMMAND_SIZE);
1,472✔
1430
      taosSetTerminalMode();
1,472✔
1431

1432
      if (shellReadCommand(command) != 0) {
1,472✔
1433
        break;
457✔
1434
      }
1435

1436
      taosResetTerminalMode();
1,015✔
1437
    } while (shellRunCommand(command, true) == 0);
1,015✔
1438

1439
    taosMemoryFreeClear(command);
1,015✔
1440
    shellWriteHistory();
1,015✔
1441
    shellExit();
1,015✔
1442
  } while (0);
1443

1444
  taosThreadCleanupPop(1);
1,015✔
1445
  return NULL;
1,015✔
1446
}
1447

1448
bool inputTotpCode(char *totpCode) {
2,891✔
1449
  bool ret = true;
2,891✔
1450
  (void)printf("Please enter your TOTP code:");
2,891✔
1451
  if (scanf("%255s", totpCode) != 1) {
2,891✔
1452
    (void)fprintf(stderr, "TOTP code reading error\n");
214✔
1453
    ret = false;
214✔
1454
  }
1455
  if (EOF == getchar()) {
2,891✔
1456
    // tip
1457
    (void)fprintf(stdout, "getchar() return EOF\r\n");
214✔
1458
  }
1459
  return ret;
2,891✔
1460
}
1461

1462
#pragma GCC diagnostic pop
1463

1464
TAOS *createConnect(SShellArgs *pArgs) {
1,234,775✔
1465
  char     show[256] = "\0";
1,234,775✔
1466
  char    *host = NULL;
1,234,775✔
1467
  uint16_t port = 0;
1,234,775✔
1468
  char    *user = NULL;
1,234,775✔
1469
  char    *pwd = NULL;
1,234,775✔
1470
  TAOS    *taos = NULL;
1,234,775✔
1471

1472
  // set mode
1473
  if (pArgs->connMode != CONN_MODE_NATIVE && pArgs->dsn) {
1,234,775✔
1474
    // websocket
1475
    memcpy(show, pArgs->dsn, 20);
1,995✔
1476
    memcpy(show + 20, "...", 3);
1,995✔
1477
    memcpy(show + 23, pArgs->dsn + strlen(pArgs->dsn) - 10, 10);
1,995✔
1478

1479
    // connect dsn
1480
    taos = taos_connect_with_dsn(pArgs->dsn);
1,995✔
1481
  } else {
1482
    host = (char *)pArgs->host;
1,232,780✔
1483
    user = (char *)pArgs->user;
1,232,780✔
1484
    pwd = pArgs->password;
1,232,780✔
1485

1486
    if (pArgs->port_inputted) {
1,232,780✔
1487
      port = pArgs->port;
1,035✔
1488
    } else {
1489
      port = defaultPort(pArgs->connMode, pArgs->dsn);
1,231,745✔
1490
    }
1491

1492
    (void)sprintf(show, "host:%s port:%d ", host, port);
1,232,780✔
1493

1494
    // connect normal
1495
    if (pArgs->auth) {
1,232,780✔
1496
      taos = taos_connect_auth(host, user, pArgs->auth, pArgs->database, port);
271✔
1497
    } else {
1498
#ifdef TD_ENTERPRISE
1499
      if (strlen(pArgs->token) > 0) {
1,232,509✔
1500
        // token
1501
        (void)printf("Connect with token ...");
3,171✔
1502
        taos = taos_connect_token(host, pArgs->token, pArgs->database, port);
3,171✔
1503
        if (taos != NULL) {
3,171✔
1504
          (void)printf("... [ OK ]\n");
1,476✔
1505
          return taos;
1,476✔
1506
        }
1507
        (void)printf("... [ FAILED ]\n");
1,695✔
1508
        return NULL;
1,695✔
1509
      }
1510
#endif
1511
      taos = taos_connect(host, user, pwd, pArgs->database, port);
1,229,338✔
1512
    }
1513

1514
    if (taos == NULL) {
1,229,609✔
1515
      // failed
1516
      int code = taos_errno(NULL);
5,913✔
1517
      if (code == TSDB_CODE_MND_WRONG_TOTP_CODE) {
5,913✔
1518
         // totp
1519
        char totpCode[TSDB_USER_PASSWORD_LONGLEN];
2,891✔
1520
        memset(totpCode, 0, sizeof(totpCode));
2,891✔
1521
        if (inputTotpCode(totpCode)) {
2,891✔
1522
          (void)printf("Connect with TOTP code:%s ...", totpCode);
2,677✔
1523
          taos = taos_connect_totp(host, user, pwd, totpCode, pArgs->database, port);
2,677✔
1524
          if (taos != NULL) {
2,677✔
1525
            (void)printf("... [ OK ]\n");
1,815✔
1526
            return taos;
1,815✔
1527
          }
1528
          (void)printf("... [ FAILED ]\n");
862✔
1529
          return NULL;
862✔
1530
        }
1531
      }
1532
      // token
1533
    }
1534
  }
1535

1536
  return taos;
1,228,927✔
1537
}
1538

1539
int32_t shellExecute(int argc, char *argv[]) {
1,234,775✔
1540
  int32_t code = 0;
1,234,775✔
1541
  (void)printf(shell.info.clientVersion, shell.info.cusName,
2,469,550✔
1542
         workingMode(shell.args.connMode, shell.args.dsn) == CONN_MODE_NATIVE ? STR_NATIVE : STR_WEBSOCKET,
1,234,775✔
1543
         taos_get_client_info(), shell.info.cusName);
1544
  fflush(stdout);
1,234,775✔
1545

1546
  SShellArgs *pArgs = &shell.args;
1,234,775✔
1547
  shell.conn = createConnect(pArgs);
1,234,775✔
1548

1549
  if (shell.conn == NULL) {
1,234,775✔
1550
    (void)printf("failed to connect to server, reason: %s [0x%08X]\n%s", taos_errstr(NULL), taos_errno(NULL),
6,108✔
1551
           ERROR_CODE_DETAIL);
1552
    fflush(stdout);
6,108✔
1553
    return -1;
6,108✔
1554
  }
1555

1556
  bool runOnce = pArgs->commands != NULL || pArgs->file[0] != 0;
1,228,667✔
1557
  shellSetConn(shell.conn, runOnce);
1,228,667✔
1558
  shellReadHistory();
1,228,667✔
1559

1560
  if (shell.args.is_bi_mode) {
1,228,667✔
1561
    // need set bi mode
1562
    (void)printf("Set BI mode is true.\n");
609✔
1563
    taos_set_conn_mode(shell.conn, TAOS_CONN_MODE_BI, 1);
609✔
1564
  }
1565

1566
  if (runOnce) {
1,228,667✔
1567
    if (pArgs->commands != NULL) {
1,227,652✔
1568
      (void)printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
1,062,336✔
1569
      char *cmd = taosStrdup(pArgs->commands);
1,062,336✔
1570
      shellRunCommand(cmd, true);
1,062,336✔
1571
      taosMemoryFree(cmd);
1,062,336✔
1572
    }
1573

1574
    if (pArgs->file[0] != 0) {
1,227,652✔
1575
      shellSourceFile(pArgs->file);
165,316✔
1576
    }
1577

1578
    taos_close(shell.conn);
1,227,652✔
1579

1580
    shellWriteHistory();
1,227,652✔
1581
    shellCleanupHistory();
1,227,652✔
1582
    return 0;
1,227,652✔
1583
  }
1584

1585
  if ((code = tsem_init(&shell.cancelSem, 0, 0)) != 0) {
1,015✔
1586
    (void)printf("failed to create cancel semaphore since %s\r\n", tstrerror(code));
×
1587
    return code;
×
1588
  }
1589

1590
  TdThread spid = {0};
1,015✔
1591
  taosThreadCreate(&spid, NULL, shellCancelHandler, NULL);
1,015✔
1592

1593
  taosSetSignal(SIGTERM, shellQueryInterruptHandler);
1,015✔
1594
  taosSetSignal(SIGHUP, shellQueryInterruptHandler);
1,015✔
1595
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
1,015✔
1596

1597
  char    buf[512] = {0};
1,015✔
1598
  int32_t verType = shellGetGrantInfo(buf);
1,015✔
1599
#ifndef WINDOWS
1600
  printfIntroduction(verType);
1,015✔
1601
#else
1602
  if (verType == TSDB_VERSION_OSS) {
1603
    showAD(false);
1604
  }
1605
#endif
1606
  // printf version
1607
  if (verType == TSDB_VERSION_ENTERPRISE || verType == TSDB_VERSION_CLOUD) {
1,015✔
1608
    (void)printf("%s\n", buf);
1,015✔
1609
  }
1610

1611
  while (1) {
1612
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, NULL);
1,015✔
1613
    taosThreadJoin(shell.pid, NULL);
1,015✔
1614
    taosThreadClear(&shell.pid);
1,015✔
1615
    if (shell.exit) {
1,015✔
1616
      tsem_post(&shell.cancelSem);
1,015✔
1617
      break;
1,015✔
1618
    }
1619
  }
1620

1621
  if (verType == TSDB_VERSION_OSS) {
1,015✔
1622
    showAD(true);
×
1623
  }
1624

1625
  taosThreadJoin(spid, NULL);
1,015✔
1626

1627
  shellCleanupHistory();
1,015✔
1628
  taos_kill_query(shell.conn);
1,015✔
1629
  taos_close(shell.conn);
1,015✔
1630

1631
  TAOS_RETURN(code);
1,015✔
1632
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc