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

taosdata / TDengine / #3535

23 Nov 2024 02:07AM UTC coverage: 60.85% (+0.03%) from 60.825%
#3535

push

travis-ci

web-flow
Merge pull request #28893 from taosdata/doc/internal

refact: rename taos lib name

120252 of 252737 branches covered (47.58%)

Branch coverage included in aggregate %.

201187 of 275508 relevant lines covered (73.02%)

15886166.19 hits per line

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

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

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

25
SShellObj shell = {0};
26

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

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

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

41
  uint64_t resShowMaxNum;
42
} tsDumpInfo;
43

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

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

67
static bool shellCmdkilled = false;
68

69
bool shellIsEmptyCommand(const char *cmd) {
800,951✔
70
  for (char c = *cmd++; c != 0; c = *cmd++) {
982,951✔
71
    if (c != ' ' && c != '\t' && c != ';') {
601,762!
72
      return false;
419,762✔
73
    }
74
  }
75
  return true;
381,189✔
76
}
77

78
int32_t shellRunSingleCommand(char *command) {
591,678✔
79
  shellCmdkilled = false;
591,678✔
80

81
  if (shellIsEmptyCommand(command)) {
591,678✔
82
    return 0;
381,189✔
83
  }
84

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

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

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

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

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

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

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

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

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

176
  if (recordHistory) shellRecordCommandToHistory(command);
209,273✔
177

178
  char quote = 0, *cmd = command;
209,273✔
179
  for (char c = *command++; c != 0; c = *command++) {
155,595,067✔
180
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
155,385,794!
181
      command++;
2✔
182
      continue;
2✔
183
    }
184

185
    if (quote == c) {
155,385,792✔
186
      quote = 0;
2,188,462✔
187
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
153,197,330✔
188
      quote = c;
2,188,462✔
189
    } else if (c == ';' && quote == 0) {
151,008,868✔
190
      c = *command;
382,405✔
191
      *command = 0;
382,405✔
192
      if (shellRunSingleCommand(cmd) < 0) {
382,405!
193
        return -1;
×
194
      }
195
      *command = c;
382,405✔
196
      cmd = command;
382,405✔
197
    }
198
  }
199
  return shellRunSingleCommand(cmd);
209,273✔
200
}
201

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

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

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

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

222
  return NULL;
210,429✔
223
}
224

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

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

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

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

248
  st = taosGetTimestampUs();
210,488✔
249

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

256
  if (shellRegexMatch(command, "^\\s*use\\s+[a-zA-Z0-9_]+\\s*;\\s*$", REG_EXTENDED | REG_ICASE)) {
207,641✔
257
    fprintf(stdout, "Database changed.\r\n\r\n");
170✔
258
    fflush(stdout);
170✔
259

260
    // call back auto tab module
261
    callbackAutoTab(command, pSql, true);
170✔
262

263
    taos_free_result(pSql);
170✔
264

265
    return;
170✔
266
  }
267

268
  // pre string
269
  char *pre = "Query OK";
207,471✔
270
  if (shellRegexMatch(command, "^\\s*delete\\s*from\\s*.*", REG_EXTENDED | REG_ICASE)) {
207,471✔
271
    pre = "Delete OK";
25✔
272
  } else if (shellRegexMatch(command, "^\\s*insert\\s*into\\s*.*", REG_EXTENDED | REG_ICASE)) {
207,446✔
273
    pre = "Insert OK";
117,975✔
274
  } else if (shellRegexMatch(command, "^\\s*create\\s*.*", REG_EXTENDED | REG_ICASE)) {
89,471✔
275
    pre = "Create OK";
4,131✔
276
  } else if (shellRegexMatch(command, "^\\s*drop\\s*.*", REG_EXTENDED | REG_ICASE)) {
85,340✔
277
    pre = "Drop OK";
152✔
278
  }
279

280
  TAOS_FIELD *pFields = taos_fetch_fields(pSql);
207,471✔
281
  if (pFields != NULL) {  // select and show kinds of commands
207,471✔
282
    int32_t error_no = 0;
79,204✔
283

284
    int64_t numOfRows = shellDumpResult(pSql, fname, &error_no, printMode, command);
79,204✔
285
    if (numOfRows < 0) return;
79,204!
286

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

302
    // call auto tab
303
    callbackAutoTab(command, NULL, false);
128,267✔
304
  }
305

306
  printf("\r\n");
207,471✔
307
}
308

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

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

328
  if (tt <= 0 && ms < 0) {
4,055,000✔
329
    tt--;
5,147✔
330
    if (precision == TSDB_TIME_PRECISION_NANO) {
5,147!
331
      ms += 1000000000;
×
332
    } else if (precision == TSDB_TIME_PRECISION_MICRO) {
5,147!
333
      ms += 1000000;
×
334
    } else {
335
      ms += 1000;
5,147✔
336
    }
337
  }
338

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

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

353
  return buf;
4,055,000✔
354
}
355

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

362
  return buf;
×
363
}
364

365
void shellDumpFieldToFile(TdFilePtr pFile, const char *val, TAOS_FIELD *field, int32_t length, int32_t precision) {
2,185,983✔
366
  if (val == NULL) {
2,185,983✔
367
    taosFprintfFile(pFile, "NULL");
12,766✔
368
    return;
12,766✔
369
  }
370

371
  char    quotationStr[2] = {'"', 0};
2,173,217✔
372
  int32_t width;
373

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

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

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

484
  TAOS_ROW row = taos_fetch_row(tres);
43✔
485
  if (row == NULL) {
43!
486
    return 0;
×
487
  }
488

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

495
  TAOS_FIELD *fields = taos_fetch_fields(tres);
43✔
496
  int32_t     num_fields = taos_num_fields(tres);
43✔
497
  int32_t     precision = taos_result_precision(tres);
43✔
498

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

507
  int64_t numOfRows = 0;
43✔
508
  do {
509
    int32_t *length = taos_fetch_lengths(tres);
323,439✔
510
    for (int32_t i = 0; i < num_fields; i++) {
2,509,422✔
511
      if (i > 0) {
2,185,983✔
512
        taosFprintfFile(pFile, ",");
1,862,544✔
513
      }
514
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision);
2,185,983✔
515
    }
516
    taosFprintfFile(pFile, "\r\n");
323,439✔
517

518
    numOfRows++;
323,439✔
519
    row = taos_fetch_row(tres);
323,439✔
520
  } while (row != NULL);
323,439✔
521

522
  taosCloseFile(&pFile);
43✔
523

524
  return numOfRows;
43✔
525
}
526

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

531
  while (pos < length) {
42,689,473✔
532
    TdWchar wc;
533
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
41,648,673✔
534
    if (bytes <= 0) {
41,648,673✔
535
      break;
695,217✔
536
    }
537

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

549
    if (w <= 0) {
41,648,664!
550
      continue;
84,719✔
551
    }
552

553
    if (width <= 0) {
41,648,664✔
554
      printf("%lc", wc);
84,719✔
555
      continue;
84,719✔
556
    }
557

558
    totalCols += w;
41,563,945✔
559
    if (totalCols > width) {
41,563,945✔
560
      break;
695,208✔
561
    }
562
    if (totalCols <= (width - 3)) {
40,868,737✔
563
      printf("%lc", wc);
38,373,134✔
564
      cols += w;
38,373,134✔
565
    } else {
566
      tail[tailLen] = wc;
2,495,603✔
567
      tailLen++;
2,495,603✔
568
    }
569
  }
570

571
  if (totalCols > width) {
1,736,017✔
572
    // width could be 1 or 2, so printf("...") cannot be used
573
    for (int32_t i = 0; i < 3; i++) {
2,780,832✔
574
      if (cols >= width) {
2,085,624!
575
        break;
×
576
      }
577
      putchar('.');
2,085,624✔
578
      ++cols;
2,085,624✔
579
    }
580
  } else {
581
    for (int32_t i = 0; i < tailLen; i++) {
1,450,797✔
582
      printf("%lc", tail[i]);
409,988✔
583
    }
584
    cols = totalCols;
1,040,809✔
585
  }
586

587
  for (; cols < width; cols++) {
12,622,972✔
588
    putchar(' ');
10,886,955✔
589
  }
590
}
1,736,017✔
591

592
void shellPrintString(const char *str, int32_t width) {
1,722,403✔
593
  int32_t len = strlen(str);
1,722,403✔
594

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

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

614
  int32_t code = TSDB_CODE_FAILED;
×
615

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

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

629
  shellPrintString(outputWKT, width);
×
630

631
  geosFreeBuffer(outputWKT);
×
632
}
633

634
void shellPrintField(const char *val, TAOS_FIELD *field, int32_t width, int32_t length, int32_t precision) {
8,863,957✔
635
  if (val == NULL) {
8,863,957✔
636
    shellPrintString(TSDB_DATA_NULL_STR, width);
1,642,299✔
637
    return;
1,642,299✔
638
  }
639

640
  int n = 0;
7,221,658✔
641
#define LENGTH 64
642
  char buf[LENGTH] = {0};
7,221,658✔
643
  switch (field->type) {
7,221,658!
644
    case TSDB_DATA_TYPE_BOOL:
80,104✔
645
      shellPrintString(((((int32_t)(*((char *)val))) == TSDB_FALSE) ? "false" : "true"), width);
80,104✔
646
      break;
80,104✔
647
    case TSDB_DATA_TYPE_TINYINT:
83,288✔
648
      printf("%*d", width, *((int8_t *)val));
83,288✔
649
      break;
83,288✔
650
    case TSDB_DATA_TYPE_UTINYINT:
109✔
651
      printf("%*u", width, *((uint8_t *)val));
109✔
652
      break;
109✔
653
    case TSDB_DATA_TYPE_SMALLINT:
118,309✔
654
      printf("%*d", width, *((int16_t *)val));
118,309✔
655
      break;
118,309✔
656
    case TSDB_DATA_TYPE_USMALLINT:
×
657
      printf("%*u", width, *((uint16_t *)val));
×
658
      break;
×
659
    case TSDB_DATA_TYPE_INT:
113,468✔
660
      printf("%*d", width, *((int32_t *)val));
113,468✔
661
      break;
113,468✔
662
    case TSDB_DATA_TYPE_UINT:
×
663
      printf("%*u", width, *((uint32_t *)val));
×
664
      break;
×
665
    case TSDB_DATA_TYPE_BIGINT:
925,559✔
666
      printf("%*" PRId64, width, *((int64_t *)val));
925,559✔
667
      break;
925,559✔
668
    case TSDB_DATA_TYPE_UBIGINT:
×
669
      printf("%*" PRIu64, width, *((uint64_t *)val));
×
670
      break;
×
671
    case TSDB_DATA_TYPE_FLOAT:
95,227✔
672
      if (tsEnableScience) {
95,227!
673
        printf("%*.7e", width, GET_FLOAT_VAL(val));
×
674
      } else {
675
        n = tsnprintf(buf, LENGTH, "%*.7f", width, GET_FLOAT_VAL(val));
95,227✔
676
        if (n > SHELL_FLOAT_WIDTH) {
95,227✔
677
          printf("%*.7e", width, GET_FLOAT_VAL(val));
12,145✔
678
        } else {
679
          printf("%s", buf);
83,082✔
680
        }
681
      }
682
      break;
95,227✔
683
    case TSDB_DATA_TYPE_DOUBLE:
468,012✔
684
      if (tsEnableScience) {
468,012!
685
        snprintf(buf, LENGTH, "%*.15e", width, GET_DOUBLE_VAL(val));
×
686
        printf("%s", buf);
×
687
      } else {
688
        n = tsnprintf(buf, LENGTH, "%*.15f", width, GET_DOUBLE_VAL(val));
468,012✔
689
        if (n > SHELL_DOUBLE_WIDTH) {
468,012✔
690
          printf("%*.15e", width, GET_DOUBLE_VAL(val));
61,107✔
691
        } else {
692
          printf("%*s", width, buf);
406,905✔
693
        }
694
      }
695
      break;
468,012✔
696
    case TSDB_DATA_TYPE_VARBINARY: {
×
697
      void    *data = NULL;
×
698
      uint32_t size = 0;
×
699
      if (taosAscii2Hex(val, length, &data, &size) < 0) {
×
700
        break;
×
701
      }
702
      shellPrintNChar(data, size, width);
×
703
      taosMemoryFree(data);
×
704
      break;
×
705
    }
706
    case TSDB_DATA_TYPE_BINARY:
1,736,017✔
707
    case TSDB_DATA_TYPE_NCHAR:
708
    case TSDB_DATA_TYPE_JSON:
709
      shellPrintNChar(val, length, width);
1,736,017✔
710
      break;
1,736,017✔
711
    case TSDB_DATA_TYPE_GEOMETRY:
×
712
      shellPrintGeometry(val, length, width);
×
713
      break;
×
714
    case TSDB_DATA_TYPE_TIMESTAMP:
3,601,565✔
715
      shellFormatTimestamp(buf, sizeof(buf), *(int64_t *)val, precision);
3,601,565✔
716
      printf("%s", buf);
3,601,565✔
717
      break;
3,601,565✔
718
    default:
×
719
      break;
×
720
  }
721
}
722

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

742
  return false;
×
743
}
744

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

751
  return false;
×
752
}
753

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

760
  dump_info->numFields = taos_num_fields(tres);
79,161✔
761
  dump_info->fields = taos_fetch_fields(tres);
79,161✔
762
  dump_info->precision = taos_result_precision(tres);
79,161✔
763

764
  dump_info->resShowMaxNum = UINT64_MAX;
79,161✔
765

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

770
  if (vertical) {
79,161✔
771
    dump_info->maxColNameLen = 0;
59✔
772
    for (int32_t col = 0; col < dump_info->numFields; col++) {
120✔
773
      int32_t len = (int32_t)strlen(dump_info->fields[col].name);
61✔
774
      if (len > dump_info->maxColNameLen) {
61!
775
        dump_info->maxColNameLen = len;
61✔
776
      }
777
    }
778
  } else {
779
    for (int32_t col = 0; col < dump_info->numFields; col++) {
225,302✔
780
      dump_info->width[col] = shellCalcColWidth(dump_info->fields + col, dump_info->precision);
146,200✔
781
    }
782
  }
783
}
79,161✔
784

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

792
  int64_t numOfPintRows = dump_info->numOfAllRows;
59✔
793
  int     numOfPrintRowsThisOne = 0;
59✔
794

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

798
    int32_t *length = taos_fetch_lengths(tres);
1,473✔
799

800
    for (int32_t i = 0; i < dump_info->numFields; i++) {
2,950✔
801
      TAOS_FIELD *field = dump_info->fields + i;
1,477✔
802

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

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

811
    numOfPintRows++;
1,473✔
812
    numOfPrintRowsThisOne++;
1,473✔
813

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

825
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
1,473✔
826
      return;
59✔
827
    }
828

829
    row = taos_fetch_row(tres);
1,414✔
830
  }
831
  return;
×
832
}
833

834
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
146,200✔
835
  int32_t width = (int32_t)strlen(field->name);
146,200✔
836

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

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

847
    case TSDB_DATA_TYPE_SMALLINT:
3,624✔
848
    case TSDB_DATA_TYPE_USMALLINT:
849
      return TMAX(6, width);  // '-32767'
3,624✔
850

851
    case TSDB_DATA_TYPE_INT:
2,855✔
852
    case TSDB_DATA_TYPE_UINT:
853
      return TMAX(11, width);  // '-2147483648'
2,855✔
854

855
    case TSDB_DATA_TYPE_BIGINT:
29,641✔
856
    case TSDB_DATA_TYPE_UBIGINT:
857
      return TMAX(21, width);  // '-9223372036854775807'
29,641✔
858

859
    case TSDB_DATA_TYPE_FLOAT:
1,231✔
860
      return TMAX(SHELL_FLOAT_WIDTH, width);
1,231✔
861

862
    case TSDB_DATA_TYPE_DOUBLE:
19,552✔
863
      return TMAX(SHELL_DOUBLE_WIDTH, width);
19,552✔
864

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

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

902
    default:
×
903
      ASSERT(false);
×
904
  }
905

906
  return 0;
×
907
}
908

909
void shellPrintHeader(TAOS_FIELD *fields, int32_t *width, int32_t num_fields) {
74,121✔
910
  int32_t rowWidth = 0;
74,121✔
911
  for (int32_t col = 0; col < num_fields; col++) {
204,822✔
912
    TAOS_FIELD *field = fields + col;
130,701✔
913
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
130,701✔
914
    int32_t     left = padding / 2;
130,701✔
915
    printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
130,701✔
916
    rowWidth += width[col] + 3;
130,701✔
917
  }
918

919
  putchar('\r');
74,121✔
920
  putchar('\n');
74,121✔
921
  for (int32_t i = 0; i < rowWidth; i++) {
3,841,294✔
922
    putchar('=');
3,767,173✔
923
  }
924
  putchar('\r');
74,121✔
925
  putchar('\n');
74,121✔
926
}
74,121✔
927

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

935
  int64_t numOfPintRows = dump_info->numOfAllRows;
76,333✔
936
  int     numOfPrintRowsThisOne = 0;
76,333✔
937
  if (numOfPintRows == 0) {
76,333✔
938
    shellPrintHeader(dump_info->fields, dump_info->width, dump_info->numFields);
74,121✔
939
  }
940

941
  while (row != NULL) {
2,826,342!
942
    int32_t *length = taos_fetch_lengths(tres);
2,826,342✔
943
    for (int32_t i = 0; i < dump_info->numFields; i++) {
11,688,822✔
944
      putchar(' ');
8,862,480✔
945
      shellPrintField((const char *)row[i], dump_info->fields + i, dump_info->width[i], length[i],
8,862,480✔
946
                      dump_info->precision);
947
      putchar(' ');
8,862,480✔
948
      putchar('|');
8,862,480✔
949
    }
950
    putchar('\r');
2,826,342✔
951
    putchar('\n');
2,826,342✔
952

953
    numOfPintRows++;
2,826,342✔
954
    numOfPrintRowsThisOne++;
2,826,342✔
955

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

971
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
2,826,342✔
972
      return;
76,333✔
973
    }
974

975
    row = taos_fetch_row(tres);
2,750,009✔
976
  }
977
  return;
×
978
}
979

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

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

1019
  *error_no = shellCmdkilled ? TSDB_CODE_TSC_QUERY_KILLED : taos_errno(tres);
79,204!
1020
  return num_of_rows;
79,204✔
1021
}
1022

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

1028
  char   *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
2,226✔
1029
  int32_t read_size = 0;
2,226✔
1030
  while ((read_size = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) > 0) {
5,599,252✔
1031
    line[read_size - 1] = '\0';
5,597,026✔
1032
    taosMemoryFree(pHistory->hist[pHistory->hend]);
5,597,026✔
1033
    pHistory->hist[pHistory->hend] = taosStrdup(line);
5,597,026✔
1034

1035
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
5,597,026✔
1036

1037
    if (pHistory->hend == pHistory->hstart) {
5,597,026✔
1038
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
3,373,252✔
1039
    }
1040
  }
1041

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

1058
    /* coverity[+retval] */
1059
    taosFsyncFile(pFile);
×
1060
    taosCloseFile(&pFile);
×
1061
  }
1062
  pHistory->hstart = pHistory->hend;
2,226✔
1063
}
1064

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

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

1082
void shellCleanupHistory() {
2,226✔
1083
  SShellHistory *pHistory = &shell.history;
2,226✔
1084
  for (int32_t i = 0; i < SHELL_MAX_HISTORY_SIZE; ++i) {
2,228,226✔
1085
    if (pHistory->hist[i] != NULL) {
2,226,000✔
1086
      taosMemoryFree(pHistory->hist[i]);
2,223,773✔
1087
      pHistory->hist[i] = NULL;
2,223,773✔
1088
    }
1089
  }
1090
}
2,226✔
1091

1092
void shellPrintError(TAOS_RES *tres, int64_t st) {
2,847✔
1093
  int64_t et = taosGetTimestampUs();
2,847✔
1094
  fprintf(stderr, "\r\nDB error: %s (%.6fs)\r\n", taos_errstr(tres), (et - st) / 1E6);
2,847✔
1095
  taos_free_result(tres);
2,847✔
1096
}
2,847✔
1097

1098
bool shellIsCommentLine(char *line) {
207,877✔
1099
  if (line == NULL) return true;
207,877!
1100
  return shellRegexMatch(line, "^\\s*#.*", REG_EXTENDED);
207,877✔
1101
}
1102

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

1110
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
831!
1111
    tstrncpy(fullname, file, PATH_MAX);
×
1112
  }
1113

1114
  sprintf(sourceFileCommand, "source %s;", fullname);
831✔
1115
  shellRecordCommandToHistory(sourceFileCommand);
831✔
1116

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

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

1135
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
207,962!
1136
      continue;
85✔
1137
    }
1138

1139
    if (line[read_len - 1] == '\\') {
207,877!
1140
      line[read_len - 1] = ' ';
×
1141
      memcpy(cmd + cmd_len, line, read_len);
×
1142
      cmd_len += read_len;
×
1143
      continue;
×
1144
    }
1145

1146
    if (line[read_len - 1] == '\r') {
207,877!
1147
      line[read_len - 1] = ' ';
×
1148
    }
1149

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

1157
  taosMemoryFree(cmd);
807✔
1158
  taosMemoryFreeClear(line);
807!
1159
  taosCloseFile(&pFile);
807✔
1160
}
1161

1162
bool shellGetGrantInfo(char *buf) {
5✔
1163
  bool community = true;
5✔
1164
  char sinfo[256] = {0};
5✔
1165
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
5✔
1166
  strtok(sinfo, "\r\n");
5✔
1167

1168
  char sql[] = "show grants";
5✔
1169

1170
  TAOS_RES *tres = taos_query(shell.conn, sql);
5✔
1171

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

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

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

1202
    tstrncpy(serverVersion, row[0], 64);
5✔
1203
    memcpy(expiretime, row[1], fields[1].bytes);
5✔
1204
    memcpy(expired, row[2], fields[2].bytes);
5✔
1205

1206
    if (strcmp(serverVersion, "community") == 0) {
5!
1207
      community = true;
×
1208
    } else if (strcmp(expiretime, "unlimited") == 0) {
5!
1209
      community = false;
×
1210
      sprintf(buf, "Server is %s, %s and will never expire.\r\n", serverVersion, sinfo);
×
1211
    } else {
1212
      community = false;
5✔
1213
      sprintf(buf, "Server is %s, %s and will expire at %s.\r\n", serverVersion, sinfo, expiretime);
5✔
1214
    }
1215

1216
    taos_free_result(tres);
5✔
1217
  }
1218

1219
  fprintf(stdout, "\r\n");
5✔
1220
  return community;
5✔
1221
}
1222

1223
#ifdef WINDOWS
1224
BOOL shellQueryInterruptHandler(DWORD fdwCtrlType) {
1225
  tsem_post(&shell.cancelSem);
1226
  return TRUE;
1227
}
1228
#else
1229
void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) { tsem_post(&shell.cancelSem); }
5✔
1230
#endif
1231

1232
void shellCleanup(void *arg) { taosResetTerminalMode(); }
5✔
1233

1234
void *shellCancelHandler(void *arg) {
5✔
1235
  setThreadName("shellCancelHandler");
5✔
1236
  while (1) {
1237
    if (shell.exit == true) {
15✔
1238
      break;
5✔
1239
    }
1240

1241
    if (tsem_wait(&shell.cancelSem) != 0) {
10!
1242
      taosMsleep(10);
×
1243
      continue;
×
1244
    }
1245

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

1263
  return NULL;
5✔
1264
}
1265

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

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

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

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

1286
      taosResetTerminalMode();
5✔
1287
    } while (shellRunCommand(command, true) == 0);
5!
1288

1289
    taosMemoryFreeClear(command);
5!
1290
    shellWriteHistory();
5✔
1291
    shellExit();
5✔
1292
  } while (0);
1293

1294
  taosThreadCleanupPop(1);
5✔
1295
  return NULL;
5✔
1296
}
1297

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

1302
  SShellArgs *pArgs = &shell.args;
2,238✔
1303
#ifdef WEBSOCKET
1304
  if (shell.args.restful || shell.args.cloud) {
1305
    if (shell_conn_ws_server(1)) {
1306
      return -1;
1307
    }
1308
  } else {
1309
#endif
1310
    if (shell.args.auth == NULL) {
2,238✔
1311
      shell.conn = taos_connect(pArgs->host, pArgs->user, pArgs->password, pArgs->database, pArgs->port);
2,236✔
1312
    } else {
1313
      shell.conn = taos_connect_auth(pArgs->host, pArgs->user, pArgs->auth, pArgs->database, pArgs->port);
2✔
1314
    }
1315

1316
    if (shell.conn == NULL) {
2,238✔
1317
      printf("failed to connect to server, reason: %s\n", taos_errstr(NULL));
12✔
1318
      fflush(stdout);
12✔
1319
      return -1;
12✔
1320
    }
1321
#ifdef WEBSOCKET
1322
  }
1323
#endif
1324

1325
  bool runOnce = pArgs->commands != NULL || pArgs->file[0] != 0;
2,226✔
1326
  shellSetConn(shell.conn, runOnce);
2,226✔
1327
  shellReadHistory();
2,226✔
1328

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

1337
  if (runOnce) {
2,226✔
1338
    if (pArgs->commands != NULL) {
2,221✔
1339
      printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
1,391✔
1340
      char *cmd = taosStrdup(pArgs->commands);
1,391✔
1341
      shellRunCommand(cmd, true);
1,391✔
1342
      taosMemoryFree(cmd);
1,391✔
1343
    }
1344

1345
    if (pArgs->file[0] != 0) {
2,221✔
1346
      shellSourceFile(pArgs->file);
830✔
1347
    }
1348
#ifdef WEBSOCKET
1349
    if (shell.args.restful || shell.args.cloud) {
1350
      ws_close(shell.ws_conn);
1351
    } else {
1352
#endif
1353
      taos_close(shell.conn);
2,221✔
1354
#ifdef WEBSOCKET
1355
    }
1356
#endif
1357

1358
    shellWriteHistory();
2,221✔
1359
    shellCleanupHistory();
2,221✔
1360
    return 0;
2,221✔
1361
  }
1362

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

1368
  TdThread spid = {0};
5✔
1369
  taosThreadCreate(&spid, NULL, shellCancelHandler, NULL);
5✔
1370

1371
  taosSetSignal(SIGTERM, shellQueryInterruptHandler);
5✔
1372
  taosSetSignal(SIGHUP, shellQueryInterruptHandler);
5✔
1373
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
5✔
1374

1375
#ifdef WEBSOCKET
1376
  if (!shell.args.restful && !shell.args.cloud) {
1377
#endif
1378
    char *buf = taosMemoryMalloc(512);
5✔
1379
    bool  community = shellGetGrantInfo(buf);
5✔
1380
#ifndef WINDOWS
1381
    printfIntroduction(community);
5✔
1382
#else
1383
#ifndef WEBSOCKET
1384
  if (community) {
1385
    showAD(false);
1386
  }
1387
#endif
1388
#endif
1389
    // printf version
1390
    if (!community) {
5!
1391
      printf("%s\n", buf);
5✔
1392
    }
1393
    taosMemoryFree(buf);
5✔
1394

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

1414
  taosThreadJoin(spid, NULL);
5✔
1415

1416
  shellCleanupHistory();
5✔
1417
  taos_kill_query(shell.conn);
5✔
1418
  taos_close(shell.conn);
5✔
1419

1420
  return 0;
5✔
1421
}
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