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

#define __USE_XOPEN

#include "shellInt.h"
#include "shellAuto.h"
A
Alex Duan 已提交
20
#include "shellTire.h"
A
Alex Duan 已提交
21 22 23 24 25 26 27 28
#include "tthread.h"

//
// ------------- define area  ---------------
//
#define UNION_ALL " union all "

// extern function
29 30 31 32
void shellClearScreen(int32_t ecmd_pos, int32_t cursor_pos);
void shellGetPrevCharSize(const char* str, int32_t pos, int32_t* size, int32_t* width);
void shellShowOnScreen(SShellCmd* cmd);
void shellInsertChar(SShellCmd* cmd, char* c, int size);
A
Alex Duan 已提交
33
void shellInsertStr(SShellCmd* cmd, char* str, int size);
34
bool appendAfterSelect(TAOS* con, SShellCmd* cmd, char* p, int32_t len);
A
Alex Duan 已提交
35 36 37

typedef struct SAutoPtr {
  STire* p;
38 39
  int    ref;
} SAutoPtr;
A
Alex Duan 已提交
40

41 42 43 44 45 46 47
typedef struct SWord {
  int           type;  // word type , see WT_ define
  char*         word;
  int32_t       len;
  struct SWord* next;
  bool          free;  // if true need free
} SWord;
A
Alex Duan 已提交
48 49

typedef struct {
50 51
  char*   source;
  int32_t source_len;  // valid data length in source
A
Alex Duan 已提交
52 53 54
  int32_t count;
  SWord*  head;
  // matched information
55 56 57
  int32_t matchIndex;  // matched word index in words
  int32_t matchLen;    // matched length at matched word
} SWords;
A
Alex Duan 已提交
58 59

SWords shellCommands[] = {
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    {"alter database <db_name> <alter_db_options> <anyword> <alter_db_options> <anyword> <alter_db_options> <anyword> "
     "<alter_db_options> <anyword> <alter_db_options> <anyword> ;",
     0, 0, NULL},
    {"alter dnode <dnode_id> balance ", 0, 0, NULL},
    {"alter dnode <dnode_id> resetlog;", 0, 0, NULL},
    {"alter dnode <dnode_id> debugFlag 141;", 0, 0, NULL},
    {"alter dnode <dnode_id> monitor 1;", 0, 0, NULL},
    {"alter all dnodes monitor ", 0, 0, NULL},
    {"alter alldnodes balance ", 0, 0, NULL},
    {"alter alldnodes resetlog;", 0, 0, NULL},
    {"alter alldnodes debugFlag 141;", 0, 0, NULL},
    {"alter alldnodes monitor 1;", 0, 0, NULL},
    {"alter table <tb_name> <tb_actions> <anyword> ;", 0, 0, NULL},
    {"alter table modify column", 0, 0, NULL},
    {"alter local resetlog;", 0, 0, NULL},
    {"alter local DebugFlag 143;", 0, 0, NULL},
    {"alter local cDebugFlag 143;", 0, 0, NULL},
    {"alter local uDebugFlag 143;", 0, 0, NULL},
    {"alter local rpcDebugFlag 143;", 0, 0, NULL},
    {"alter local tmrDebugFlag 143;", 0, 0, NULL},
    {"alter topic", 0, 0, NULL},
    {"alter user <user_name> <user_actions> <anyword> ;", 0, 0, NULL},
    // 20
    {"create table <anyword> using <stb_name> tags(", 0, 0, NULL},
    {"create database <anyword> <db_options> <anyword> <db_options> <anyword> <db_options> <anyword> <db_options> "
     "<anyword> <db_options> <anyword> <db_options> <anyword> <db_options> <anyword> <db_options> <anyword> "
     "<db_options> <anyword> <db_options> <anyword> ;",
     0, 0, NULL},
    {"create dnode ", 0, 0, NULL},
    {"create index ", 0, 0, NULL},
    {"create mnode on dnode <dnode_id> ;", 0, 0, NULL},
    {"create qnode on dnode <dnode_id> ;", 0, 0, NULL},
    {"create stream <anyword> into <anyword> as select", 0, 0, NULL},  // 26 append sub sql
    {"create topic <anyword> as select", 0, 0, NULL},                  // 27 append sub sql
    {"create function ", 0, 0, NULL},
    {"create user <anyword> pass <anyword> sysinfo 0;", 0, 0, NULL},
    {"create user <anyword> pass <anyword> sysinfo 1;", 0, 0, NULL},
    {"describe <all_table>", 0, 0, NULL},
    {"delete from <all_table> where ", 0, 0, NULL},
    {"drop database <db_name>", 0, 0, NULL},
    {"drop table <all_table>", 0, 0, NULL},
    {"drop dnode <dnode_id>", 0, 0, NULL},
    {"drop mnode on dnode <dnode_id> ;", 0, 0, NULL},
    {"drop qnode on dnode <dnode_id> ;", 0, 0, NULL},
    {"drop user <user_name> ;", 0, 0, NULL},
    // 40
    {"drop function", 0, 0, NULL},
    {"drop consumer group <anyword> on ", 0, 0, NULL},
    {"drop topic <topic_name> ;", 0, 0, NULL},
    {"drop stream <stream_name> ;", 0, 0, NULL},
    {"explain select", 0, 0, NULL},  // 44 append sub sql
    {"grant all on <anyword> to <user_name> ;", 0, 0, NULL},
    {"grant read on <anyword> to <user_name> ;", 0, 0, NULL},
    {"grant write on <anyword> to <user_name> ;", 0, 0, NULL},
    {"kill connection <anyword> ;", 0, 0, NULL},
    {"kill query ", 0, 0, NULL},
    {"kill transaction ", 0, 0, NULL},
    {"merge vgroup ", 0, 0, NULL},
    {"reset query cache;", 0, 0, NULL},
    {"revoke all on <anyword> from <user_name> ;", 0, 0, NULL},
    {"revoke read on <anyword> from <user_name> ;", 0, 0, NULL},
    {"revoke write on <anyword> from <user_name> ;", 0, 0, NULL},
    {"select * from <all_table>", 0, 0, NULL},
    {"select _block_dist() from <all_table> \\G;", 0, 0, NULL},
    {"select client_version();", 0, 0, NULL},
    // 60
    {"select current_user();", 0, 0, NULL},
    {"select database();", 0, 0, NULL},
    {"select server_version();", 0, 0, NULL},
    {"select server_status();", 0, 0, NULL},
    {"select now();", 0, 0, NULL},
    {"select today();", 0, 0, NULL},
    {"select timezone();", 0, 0, NULL},
    {"set max_binary_display_width ", 0, 0, NULL},
    {"show apps;", 0, 0, NULL},
    {"show create database <db_name> \\G;", 0, 0, NULL},
    {"show create stable <stb_name> \\G;", 0, 0, NULL},
    {"show create table <tb_name> \\G;", 0, 0, NULL},
    {"show connections;", 0, 0, NULL},
    {"show cluster;", 0, 0, NULL},
    {"show databases;", 0, 0, NULL},
    {"show dnodes;", 0, 0, NULL},
    {"show dnode <dnode_id> variables;", 0, 0, NULL},
    {"show functions;", 0, 0, NULL},
    {"show mnodes;", 0, 0, NULL},
    {"show queries;", 0, 0, NULL},
    // 80
    {"show query <anyword> ;", 0, 0, NULL},
    {"show qnodes;", 0, 0, NULL},
    {"show stables;", 0, 0, NULL},
    {"show stables like ", 0, 0, NULL},
    {"show streams;", 0, 0, NULL},
    {"show scores;", 0, 0, NULL},
A
Alex Duan 已提交
153
    {"show snodes;", 0, 0, NULL},
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
    {"show subscriptions;", 0, 0, NULL},
    {"show tables;", 0, 0, NULL},
    {"show tables like", 0, 0, NULL},
    {"show table distributed <all_table>", 0, 0, NULL},
    {"show tags from <tb_name>", 0, 0, NULL},
    {"show tags from <db_name>", 0, 0, NULL},
    {"show topics;", 0, 0, NULL},
    {"show transactions;", 0, 0, NULL},
    {"show users;", 0, 0, NULL},
    {"show variables;", 0, 0, NULL},
    {"show local variables;", 0, 0, NULL},
    {"show vnodes <dnode_id>", 0, 0, NULL},
    {"show vgroups;", 0, 0, NULL},
    {"show consumers;", 0, 0, NULL},
    {"show grants;", 0, 0, NULL},
    {"split vgroup ", 0, 0, NULL},
    {"insert into <tb_name> values(", 0, 0, NULL},
    {"insert into <tb_name> using <stb_name> tags(", 0, 0, NULL},
    {"insert into <tb_name> using <stb_name> <anyword> values(", 0, 0, NULL},
    {"insert into <tb_name> file ", 0, 0, NULL},
    {"trim database <db_name>", 0, 0, NULL},
    {"use <db_name>", 0, 0, NULL},
    {"quit", 0, 0, NULL}};

char* keywords[] = {
    "and ",         "asc ",      "desc ",     "from ",    "fill(",         "limit ",    "where ",
    "interval(",    "order by ", "order by ", "offset ",  "or ",           "group by ", "now()",
    "session(",     "sliding ",  "slimit ",   "soffset ", "state_window(", "today() ",  "union all select ",
    "partition by "};

char* functions[] = {
    "count(",         "sum(",
    "avg(",           "last(",
    "last_row(",      "top(",
    "interp(",        "max(",
    "min(",           "now()",
    "today()",        "percentile(",
    "tail(",          "pow(",
    "abs(",           "atan(",
    "acos(",          "asin(",
    "apercentile(",   "bottom(",
    "cast(",          "ceil(",
    "char_length(",   "cos(",
    "concat(",        "concat_ws(",
    "csum(",          "diff(",
    "derivative(",    "elapsed(",
    "first(",         "floor(",
    "hyperloglog(",   "histogram(",
    "irate(",         "leastsquares(",
    "length(",        "log(",
    "lower(",         "ltrim(",
    "mavg(",          "mode(",
    "tan(",           "round(",
    "rtrim(",         "sample(",
    "sin(",           "spread(",
    "substr(",        "statecount(",
    "stateduration(", "stddev(",
    "sqrt(",          "timediff(",
    "timezone(",      "timetruncate(",
    "twa(",           "to_unixtimestamp(",
    "unique(",        "upper(",
A
Alex Duan 已提交
215 216
};

217 218 219
char* tb_actions[] = {
    "add column ", "modify column ", "drop column ", "rename column ", "add tag ",
    "modify tag ", "drop tag ",      "rename tag ",  "set tag ",
A
Alex Duan 已提交
220 221
};

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
char* user_actions[] = {"pass ", "enable ", "sysinfo "};

char* tb_options[] = {"comment ", "watermark ", "max_delay ", "ttl ", "rollup(", "sma("};

char* db_options[] = {"keep ",
                      "replica ",
                      "precision ",
                      "strict ",
                      "buffer ",
                      "cachemodel ",
                      "cachesize ",
                      "comp ",
                      "duration ",
                      "wal_fsync_period",
                      "maxrows ",
                      "minrows ",
                      "pages ",
                      "pagesize ",
                      "retentions ",
                      "wal_level ",
                      "vgroups ",
                      "single_stable ",
                      "wal_retention_period ",
                      "wal_roll_period ",
                      "wal_retention_size ",
                      "wal_segment_size "};

char* alter_db_options[] = {"keep ", "cachemodel ", "cachesize ", "wal_fsync_period ", "wal_level "};

char* data_types[] = {"timestamp",    "int",
                      "int unsigned", "varchar(16)",
                      "float",        "double",
                      "binary(16)",   "nchar(16)",
                      "bigint",       "bigint unsigned",
                      "smallint",     "smallint unsigned",
                      "tinyint",      "tinyint unsigned",
                      "bool",         "json"};

char* key_tags[] = {"tags("};

char* key_select[] = {"select "};
A
Alex Duan 已提交
263 264 265 266

//
//  ------- gobal variant define ---------
//
267 268 269 270 271
int32_t firstMatchIndex = -1;  // first match shellCommands index
int32_t lastMatchIndex = -1;   // last match shellCommands index
int32_t curMatchIndex = -1;    // current match shellCommands index
int32_t lastWordBytes = -1;    // printShow last word length
bool    waitAutoFill = false;
A
Alex Duan 已提交
272 273 274 275

//
//   ----------- global var array define -----------
//
276 277 278 279 280 281 282 283 284 285 286 287
#define WT_VAR_DBNAME         0
#define WT_VAR_STABLE         1
#define WT_VAR_TABLE          2
#define WT_VAR_DNODEID        3
#define WT_VAR_USERNAME       4
#define WT_VAR_TOPIC          5
#define WT_VAR_STREAM         6
#define WT_VAR_ALLTABLE       7
#define WT_VAR_FUNC           8
#define WT_VAR_KEYWORD        9
#define WT_VAR_TBACTION       10
#define WT_VAR_DBOPTION       11
A
Alex Duan 已提交
288
#define WT_VAR_ALTER_DBOPTION 12
289 290 291 292 293 294
#define WT_VAR_DATATYPE       13
#define WT_VAR_KEYTAGS        14
#define WT_VAR_ANYWORD        15
#define WT_VAR_TBOPTION       16
#define WT_VAR_USERACTION     17
#define WT_VAR_KEYSELECT      18
A
Alex Duan 已提交
295

296
#define WT_VAR_CNT 19
A
Alex Duan 已提交
297

298 299
#define WT_FROM_DB_MAX 6  // max get content from db
#define WT_FROM_DB_CNT (WT_FROM_DB_MAX + 1)
A
Alex Duan 已提交
300

301
#define WT_TEXT 0xFF
A
Alex Duan 已提交
302

303
char dbName[256] = "";  // save use database name;
A
Alex Duan 已提交
304
// tire array
305
STire*        tires[WT_VAR_CNT];
A
Alex Duan 已提交
306
TdThreadMutex tiresMutex;
307
// save thread handle obtain var name from db server
A
Alex Duan 已提交
308 309
TdThread* threads[WT_FROM_DB_CNT];
// obtain var name  with sql from server
310 311 312 313
char varTypes[WT_VAR_CNT][64] = {"<db_name>",    "<stb_name>",    "<tb_name>",          "<dnode_id>",   "<user_name>",
                                 "<topic_name>", "<stream_name>", "<all_table>",        "<function>",   "<keyword>",
                                 "<tb_actions>", "<db_options>",  "<alter_db_options>", "<data_types>", "<key_tags>",
                                 "<anyword>",    "<tb_options>",  "<user_actions>",     "<key_select>"};
A
Alex Duan 已提交
314

315 316
char varSqls[WT_FROM_DB_CNT][64] = {"show databases;", "show stables;", "show tables;", "show dnodes;",
                                    "show users;",     "show topics;",  "show streams;"};
A
Alex Duan 已提交
317 318

// var words current cursor, if user press any one key except tab, cursorVar can be reset to -1
319 320
int  cursorVar = -1;
bool varMode = false;  // enter var names list mode
A
Alex Duan 已提交
321

322 323 324 325
TAOS*      varCon = NULL;
SShellCmd* varCmd = NULL;
SMatch*    lastMatch = NULL;  // save last match result
int        cntDel = 0;        // delete byte count after next press tab
A
Alex Duan 已提交
326 327 328

// show auto tab introduction
void printfIntroduction() {
A
Alex Duan 已提交
329 330 331 332 333 334 335 336 337 338 339 340
  printf("   ******************************  Tab Completion  **********************************\n");
  printf("   *   The TDengine CLI supports tab completion for a variety of items,             *\n");
  printf("   *   including database names, table names, function names and keywords.          *\n");
  printf("   *   The full list of shortcut keys is as follows:                                *\n");
  printf("   *    [ TAB ]        ......  complete the current word                            *\n");
  printf("   *                   ......  if used on a blank line, display all valid commands  *\n");
  printf("   *    [ Ctrl + A ]   ......  move cursor to the st[A]rt of the line               *\n");
  printf("   *    [ Ctrl + E ]   ......  move cursor to the [E]nd of the line                 *\n");
  printf("   *    [ Ctrl + W ]   ......  move cursor to the middle of the line                *\n");
  printf("   *    [ Ctrl + L ]   ......  clear the entire screen                              *\n");
  printf("   *    [ Ctrl + K ]   ......  clear the screen after the cursor                    *\n");
  printf("   *    [ Ctrl + U ]   ......  clear the screen before the cursor                   *\n");
341
  printf("   **********************************************************************************\n\n");
A
Alex Duan 已提交
342 343 344
}

void showHelp() {
A
Alex Duan 已提交
345
  printf("\nThe TDengine CLI supports the following commands:");
346 347
  printf(
      "\n\
A
Alex Duan 已提交
348 349 350 351
  ----- A ----- \n\
    alter database <db_name> <db_options> \n\
    alter dnode <dnode_id> balance \n\
    alter dnode <dnode_id> resetlog;\n\
A
Alex Duan 已提交
352 353 354 355 356 357 358 359 360 361 362
    alter all dnodes monitor \n\
    alter alldnodes balance \n\
    alter alldnodes resetlog;\n\
    alter alldnodes debugFlag \n\
    alter alldnodes monitor \n\
    alter table <tb_name> <tb_actions> ;\n\
    alter table modify column\n\
    alter local resetlog;\n\
    alter local DebugFlag 143;\n\
    alter topic\n\
    alter user <user_name> <user_actions> ...\n\
A
Alex Duan 已提交
363 364
  ----- C ----- \n\
    create table <tb_name> using <stb_name> tags ...\n\
A
Alex Duan 已提交
365 366 367 368 369 370 371 372 373
    create database <db_name> <db_options>  ...\n\
    create dnode ...\n\
    create index ...\n\
    create mnode on dnode <dnode_id> ;\n\
    create qnode on dnode <dnode_id> ;\n\
    create stream <stream_name> into <stb_name> as select ...\n\
    create topic <topic_name> as select ...\n\
    create function ...\n\
    create user <user_name> pass <password> ...\n\
A
Alex Duan 已提交
374
  ----- D ----- \n\
A
Alex Duan 已提交
375 376
    describe <all_table>\n\
    delete from <all_table> where ...\n\
A
Alex Duan 已提交
377 378 379
    drop database <db_name>;\n\
    drop table <all_table>;\n\
    drop dnode <dnode_id>;\n\
A
Alex Duan 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
    drop mnode on dnode <dnode_id> ;\n\
    drop qnode on dnode <dnode_id> ;\n\
    drop user <user_name> ;\n\
    drop function <function_name>;\n\
    drop consumer group ... \n\
    drop topic <topic_name> ;\n\
    drop stream <stream_name> ;\n\
  ----- E ----- \n\
    explain select clause ...\n\
  ----- I ----- \n\
    insert into <tb_name> values(...) ;\n\
    insert into <tb_name> using <stb_name> tags(...) values(...) ;\n\
  ----- G ----- \n\
    grant all   on <priv_level> to <user_name> ;\n\
    grant read  on <priv_level> to <user_name> ;\n\
    grant write on <priv_level> to <user_name> ;\n\
A
Alex Duan 已提交
396 397 398
  ----- K ----- \n\
    kill connection <connection_id>; \n\
    kill query <query_id>; \n\
A
Alex Duan 已提交
399 400 401 402 403 404 405 406
    kill transaction <transaction_id>;\n\
  ----- M ----- \n\
    merge vgroup ...\n\
  ----- R ----- \n\
    reset query cache;\n\
    revoke all   on <priv_level> from <user_name> ;\n\
    revoke read  on <priv_level> from <user_name> ;\n\
    revoke write on <priv_level> from <user_name> ;\n\
A
Alex Duan 已提交
407 408 409 410 411
  ----- S ----- \n\
    select * from <all_table> where ... \n\
    select _block_dist() from <all_table>;\n\
    select client_version();\n\
    select current_user();\n\
A
Alex Duan 已提交
412
    select database();\n\
A
Alex Duan 已提交
413
    select server_version();\n\
A
Alex Duan 已提交
414 415 416 417 418 419
    select server_status();\n\
    select now();\n\
    select today();\n\
    select timezone();\n\
    set max_binary_display_width ...\n\
    show apps;\n\
A
Alex Duan 已提交
420 421 422 423
    show create database <db_name>;\n\
    show create stable <stb_name>;\n\
    show create table <tb_name>;\n\
    show connections;\n\
A
Alex Duan 已提交
424
    show cluster;\n\
A
Alex Duan 已提交
425 426
    show databases;\n\
    show dnodes;\n\
A
Alex Duan 已提交
427
    show dnode <dnode_id> variables;\n\
A
Alex Duan 已提交
428 429 430
    show functions;\n\
    show mnodes;\n\
    show queries;\n\
A
Alex Duan 已提交
431 432 433
    show query <query_id> ;\n\
    show qnodes;\n\
    show snodes;\n\
A
Alex Duan 已提交
434
    show stables;\n\
A
Alex Duan 已提交
435
    show stables like \n\
A
Alex Duan 已提交
436 437
    show streams;\n\
    show scores;\n\
A
Alex Duan 已提交
438
    show subscriptions;\n\
A
Alex Duan 已提交
439
    show tables;\n\
A
Alex Duan 已提交
440 441 442 443 444 445
    show tables like\n\
    show table distributed <all_table>;\n\
    show tags from <tb_name>\n\
    show tags from <db_name>\n\
    show topics;\n\
    show transactions;\n\
A
Alex Duan 已提交
446 447
    show users;\n\
    show variables;\n\
A
Alex Duan 已提交
448 449
    show local variables;\n\
    show vnodes <dnode_id>\n\
A
Alex Duan 已提交
450
    show vgroups;\n\
A
Alex Duan 已提交
451 452 453 454 455
    show consumers;\n\
    show grants;\n\
    split vgroup ...\n\
  ----- T ----- \n\
    trim database <db_name>;\n\
A
Alex Duan 已提交
456 457 458 459
  ----- U ----- \n\
    use <db_name>;");

  printf("\n\n");
460 461 462 463

  // define in getDuration() function
  printf(
      "\
A
Alex Duan 已提交
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
  Timestamp expression Format:\n\
    b - nanosecond \n\
    u - microsecond \n\
    a - millisecond \n\
    s - second \n\
    m - minute \n\
    h - hour \n\
    d - day \n\
    w - week \n\
    now - current time \n\
  Example : \n\
    select * from t1 where ts > now - 2w + 3d and ts <= now - 1w -2h ;\n");
  printf("\n");
}

//
//  -------------------  parse words --------------------------
//

#define SHELL_COMMAND_COUNT() (sizeof(shellCommands) / sizeof(SWords))

// get at
486 487
SWord* atWord(SWords* command, int32_t index) {
  SWord* word = command->head;
A
Alex Duan 已提交
488
  for (int32_t i = 0; i < index; i++) {
489
    if (word == NULL) return NULL;
A
Alex Duan 已提交
490 491 492 493 494 495 496 497 498 499
    word = word->next;
  }

  return word;
}

#define MATCH_WORD(x) atWord(x, x->matchIndex)

int wordType(const char* p, int32_t len) {
  for (int i = 0; i < WT_VAR_CNT; i++) {
500
    if (strncmp(p, varTypes[i], len) == 0) return i;
A
Alex Duan 已提交
501 502 503 504 505
  }
  return WT_TEXT;
}

// add word
506 507
SWord* addWord(const char* p, int32_t len, bool pattern) {
  SWord* word = (SWord*)taosMemoryMalloc(sizeof(SWord));
A
Alex Duan 已提交
508
  memset(word, 0, sizeof(SWord));
509 510
  word->word = (char*)p;
  word->len = len;
A
Alex Duan 已提交
511 512 513 514 515 516 517 518 519 520 521 522

  // check format
  if (pattern) {
    word->type = wordType(p, len);
  } else {
    word->type = WT_TEXT;
  }

  return word;
}

// parse one command
523 524
void parseCommand(SWords* command, bool pattern) {
  char*   p = command->source;
A
Alex Duan 已提交
525
  int32_t start = 0;
526
  int32_t size = command->source_len > 0 ? command->source_len : strlen(p);
A
Alex Duan 已提交
527 528 529 530 531 532 533

  bool lastBlank = false;
  for (int i = 0; i <= size; i++) {
    if (p[i] == ' ' || i == size) {
      // check continue blank like '    '
      if (p[i] == ' ') {
        if (lastBlank) {
534
          start++;
A
Alex Duan 已提交
535 536
          continue;
        }
537
        if (i == 0) {  // first blank
A
Alex Duan 已提交
538
          lastBlank = true;
539
          start++;
A
Alex Duan 已提交
540 541 542
          continue;
        }
        lastBlank = true;
543
      }
A
Alex Duan 已提交
544 545 546 547 548 549

      // found split or string end , append word
      if (command->head == NULL) {
        command->head = addWord(p + start, i - start, pattern);
        command->count = 1;
      } else {
550
        SWord* word = command->head;
A
Alex Duan 已提交
551 552 553 554
        while (word->next) {
          word = word->next;
        }
        word->next = addWord(p + start, i - start, pattern);
555
        command->count++;
A
Alex Duan 已提交
556 557 558 559 560 561 562 563 564
      }
      start = i + 1;
    } else {
      lastBlank = false;
    }
  }
}

// free SShellCmd
565
void freeCommand(SWords* command) {
A
Alex Duan 已提交
566
  SWord* item = command->head;
567
  // loop
A
Alex Duan 已提交
568 569 570
  while (item) {
    SWord* tmp = item;
    item = item->next;
A
Alex Duan 已提交
571
    // if malloc need free
572
    if (tmp->free && tmp->word) taosMemoryFree(tmp->word);
A
Alex Duan 已提交
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
    taosMemoryFree(tmp);
  }
}

void GenerateVarType(int type, char** p, int count) {
  STire* tire = createTire(TIRE_LIST);
  for (int i = 0; i < count; i++) {
    insertWord(tire, p[i]);
  }

  taosThreadMutexLock(&tiresMutex);
  tires[type] = tire;
  taosThreadMutexUnlock(&tiresMutex);
}

//
//  -------------------- shell auto ----------------
//

592
// init shell auto funciton , shell start call once
A
Alex Duan 已提交
593 594 595
bool shellAutoInit() {
  // command
  int32_t count = SHELL_COMMAND_COUNT();
596
  for (int32_t i = 0; i < count; i++) {
A
Alex Duan 已提交
597 598 599 600 601 602 603 604 605 606 607
    parseCommand(shellCommands + i, true);
  }

  // tires
  memset(tires, 0, sizeof(STire*) * WT_VAR_CNT);
  taosThreadMutexInit(&tiresMutex, NULL);

  // threads
  memset(threads, 0, sizeof(TdThread*) * WT_FROM_DB_CNT);

  // generate varType
608 609 610 611 612 613 614 615 616 617
  GenerateVarType(WT_VAR_FUNC, functions, sizeof(functions) / sizeof(char*));
  GenerateVarType(WT_VAR_KEYWORD, keywords, sizeof(keywords) / sizeof(char*));
  GenerateVarType(WT_VAR_DBOPTION, db_options, sizeof(db_options) / sizeof(char*));
  GenerateVarType(WT_VAR_ALTER_DBOPTION, alter_db_options, sizeof(alter_db_options) / sizeof(char*));
  GenerateVarType(WT_VAR_TBACTION, tb_actions, sizeof(tb_actions) / sizeof(char*));
  GenerateVarType(WT_VAR_DATATYPE, data_types, sizeof(data_types) / sizeof(char*));
  GenerateVarType(WT_VAR_KEYTAGS, key_tags, sizeof(key_tags) / sizeof(char*));
  GenerateVarType(WT_VAR_TBOPTION, tb_options, sizeof(tb_options) / sizeof(char*));
  GenerateVarType(WT_VAR_USERACTION, user_actions, sizeof(user_actions) / sizeof(char*));
  GenerateVarType(WT_VAR_KEYSELECT, key_select, sizeof(key_select) / sizeof(char*));
A
Alex Duan 已提交
618 619 620 621 622

  return true;
}

// set conn
623
void shellSetConn(TAOS* conn) { varCon = conn; }
A
Alex Duan 已提交
624 625 626 627 628

// exit shell auto funciton, shell exit call once
void shellAutoExit() {
  // free command
  int32_t count = SHELL_COMMAND_COUNT();
629
  for (int32_t i = 0; i < count; i++) {
A
Alex Duan 已提交
630 631 632 633 634 635 636 637 638
    freeCommand(shellCommands + i);
  }

  // free tires
  taosThreadMutexLock(&tiresMutex);
  for (int32_t i = 0; i < WT_VAR_CNT; i++) {
    if (tires[i]) {
      freeTire(tires[i]);
      tires[i] = NULL;
639
    }
A
Alex Duan 已提交
640 641 642 643 644 645
  }
  taosThreadMutexUnlock(&tiresMutex);
  // destory
  taosThreadMutexDestroy(&tiresMutex);

  // free threads
A
Alex Duan 已提交
646
  for (int32_t i = 0; i < WT_FROM_DB_CNT; i++) {
A
Alex Duan 已提交
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
    if (threads[i]) {
      taosDestroyThread(threads[i]);
      threads[i] = NULL;
    }
  }

  // free lastMatch
  if (lastMatch) {
    freeMatch(lastMatch);
    lastMatch = NULL;
  }
}

//
//  -------------------  auto ptr for tires --------------------------
//
bool setNewAuotPtr(int type, STire* pNew) {
664
  if (pNew == NULL) return false;
A
Alex Duan 已提交
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698

  taosThreadMutexLock(&tiresMutex);
  STire* pOld = tires[type];
  if (pOld != NULL) {
    // previous have value, release self ref count
    if (--pOld->ref == 0) {
      freeTire(pOld);
    }
  }

  // set new
  tires[type] = pNew;
  tires[type]->ref = 1;
  taosThreadMutexUnlock(&tiresMutex);

  return true;
}

// get ptr
STire* getAutoPtr(int type) {
  if (tires[type] == NULL) {
    return NULL;
  }

  taosThreadMutexLock(&tiresMutex);
  tires[type]->ref++;
  taosThreadMutexUnlock(&tiresMutex);

  return tires[type];
}

// put back tire to tires[type], if tire not equal tires[type].p, need free tire
void putBackAutoPtr(int type, STire* tire) {
  if (tire == NULL) {
699
    return;
A
Alex Duan 已提交
700 701 702 703
  }

  taosThreadMutexLock(&tiresMutex);
  if (tires[type] != tire) {
704
    // update by out,  can't put back , so free
A
Alex Duan 已提交
705 706 707 708
    if (--tire->ref == 1) {
      // support multi thread getAuotPtr
      freeTire(tire);
    }
709

A
Alex Duan 已提交
710 711 712 713 714 715
  } else {
    tires[type]->ref--;
    assert(tires[type]->ref > 0);
  }
  taosThreadMutexUnlock(&tiresMutex);

716
  return;
A
Alex Duan 已提交
717 718 719 720 721 722
}

//
//  -------------------  var Word --------------------------
//

723
#define MAX_CACHED_CNT 100000  // max cached rows 10w
A
Alex Duan 已提交
724 725
// write sql result to var name, return write rows cnt
int writeVarNames(int type, TAOS_RES* tres) {
726
  // fetch row
A
Alex Duan 已提交
727 728 729 730 731
  TAOS_ROW row = taos_fetch_row(tres);
  if (row == NULL) {
    return 0;
  }

732
  TAOS_FIELD* fields = taos_fetch_fields(tres);
A
Alex Duan 已提交
733
  // create new tires
734
  char   tireType = type == WT_VAR_TABLE ? TIRE_TREE : TIRE_LIST;
A
Alex Duan 已提交
735 736 737 738
  STire* tire = createTire(tireType);

  // enum rows
  char name[1024];
739
  int  numOfRows = 0;
A
Alex Duan 已提交
740 741
  do {
    int32_t* lengths = taos_fetch_lengths(tres);
742 743 744
    int32_t  bytes = lengths[0];
    if (fields[0].type == TSDB_DATA_TYPE_INT) {
      sprintf(name, "%d", *(int16_t*)row[0]);
A
Alex Duan 已提交
745 746 747
    } else {
      memcpy(name, row[0], bytes);
    }
748 749

    name[bytes] = 0;  // set string end
A
Alex Duan 已提交
750 751 752
    // insert to tire
    insertWord(tire, name);

753
    if (++numOfRows > MAX_CACHED_CNT) {
A
Alex Duan 已提交
754 755 756 757 758 759 760 761 762 763 764 765
      break;
    }

    row = taos_fetch_row(tres);
  } while (row != NULL);

  // replace old tire
  setNewAuotPtr(type, tire);

  return numOfRows;
}

766
bool firstMatchCommand(TAOS* con, SShellCmd* cmd);
A
Alex Duan 已提交
767
//
768
//  thread obtain var thread from db server
A
Alex Duan 已提交
769 770
//
void* varObtainThread(void* param) {
771
  int type = *(int*)param;
A
Alex Duan 已提交
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
  taosMemoryFree(param);

  if (varCon == NULL || type > WT_FROM_DB_MAX) {
    return NULL;
  }

  TAOS_RES* pSql = taos_query(varCon, varSqls[type]);
  if (taos_errno(pSql)) {
    taos_free_result(pSql);
    return NULL;
  }

  // write var names from pSql
  int cnt = writeVarNames(type, pSql);

  // free sql
  taos_free_result(pSql);

790
  // check need call auto tab
A
Alex Duan 已提交
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
  if (cnt > 0 && waitAutoFill) {
    // press tab key by program
    firstMatchCommand(varCon, varCmd);
  }

  return NULL;
}

// only match next one word from all match words, return valuue must free by caller
char* matchNextPrefix(STire* tire, char* pre) {
  SMatch* match = NULL;

  // re-use last result
  if (lastMatch) {
    if (strcmp(pre, lastMatch->pre) == 0) {
      // same pre
      match = lastMatch;
    }
  }

  if (match == NULL) {
    // not same with last result
    if (pre[0] == 0) {
      // EMPTY PRE
      match = enumAll(tire);
    } else {
      // NOT EMPTY
      match = matchPrefix(tire, pre, NULL);
    }
820

A
Alex Duan 已提交
821 822
    // save to lastMatch
    if (match) {
823
      if (lastMatch) freeMatch(lastMatch);
A
Alex Duan 已提交
824 825 826 827 828 829 830 831 832 833 834 835 836
      lastMatch = match;
    }
  }

  // check valid
  if (match == NULL || match->head == NULL) {
    // no one matched
    return false;
  }

  if (cursorVar == -1) {
    // first
    cursorVar = 0;
837
    return strdup(match->head->word);
A
Alex Duan 已提交
838 839 840
  }

  // according to cursorVar , calculate next one
841
  int         i = 0;
A
Alex Duan 已提交
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
  SMatchNode* item = match->head;
  while (item) {
    if (i == cursorVar + 1) {
      // found next position ok
      if (item->next == NULL) {
        // match last item, reset cursorVar to head
        cursorVar = -1;
      } else {
        cursorVar = i;
      }

      return strdup(item->word);
    }

    // check end item
    if (item->next == NULL) {
      // if cursorVar > var list count, return last and reset cursorVar
      cursorVar = -1;

      return strdup(item->word);
    }

    // move next
    item = item->next;
    i++;
  }

  return NULL;
}

// search pre word from tire tree, return value must free by caller
char* tireSearchWord(int type, char* pre) {
  if (type == WT_TEXT) {
    return NULL;
  }

878
  if (type > WT_FROM_DB_MAX) {
A
Alex Duan 已提交
879 880
    // NOT FROM DB , tires[type] alwary not null
    STire* tire = tires[type];
881 882
    if (tire == NULL) return NULL;
    return matchNextPrefix(tire, pre);
A
Alex Duan 已提交
883 884 885 886 887 888 889 890 891 892 893
  }

  // TYPE CONTEXT GET FROM DB
  taosThreadMutexLock(&tiresMutex);

  // check need obtain from server
  if (tires[type] == NULL) {
    waitAutoFill = true;
    // need async obtain var names from db sever
    if (threads[type] != NULL) {
      if (taosThreadRunning(threads[type])) {
894
        // thread running , need not obtain again, return
A
Alex Duan 已提交
895 896 897 898 899 900 901
        taosThreadMutexUnlock(&tiresMutex);
        return NULL;
      }
      // destroy previous thread handle for new create thread handle
      taosDestroyThread(threads[type]);
      threads[type] = NULL;
    }
902

A
Alex Duan 已提交
903
    // create new
904 905
    void* param = taosMemoryMalloc(sizeof(int));
    *((int*)param) = type;
A
Alex Duan 已提交
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
    threads[type] = taosCreateThread(varObtainThread, param);
    taosThreadMutexUnlock(&tiresMutex);
    return NULL;
  }
  taosThreadMutexUnlock(&tiresMutex);

  // can obtain var names from local
  STire* tire = getAutoPtr(type);
  if (tire == NULL) {
    return NULL;
  }

  char* str = matchNextPrefix(tire, pre);
  // used finish, put back pointer to autoptr array
  putBackAutoPtr(type, tire);

  return str;
}

925
// match var word, word1 is pattern , word2 is input from shell
A
Alex Duan 已提交
926
bool matchVarWord(SWord* word1, SWord* word2) {
927
  // search input word from tire tree
A
Alex Duan 已提交
928 929 930 931 932 933 934 935 936 937
  char pre[512];
  memcpy(pre, word2->word, word2->len);
  pre[word2->len] = 0;

  char* str = NULL;
  if (word1->type == WT_VAR_ALLTABLE) {
    // ALL_TABLE
    str = tireSearchWord(WT_VAR_STABLE, pre);
    if (str == NULL) {
      str = tireSearchWord(WT_VAR_TABLE, pre);
938
      if (str == NULL) return false;
A
Alex Duan 已提交
939 940 941 942 943 944 945 946 947 948 949
    }
  } else {
    // OTHER
    str = tireSearchWord(word1->type, pre);
    if (str == NULL) {
      // not found or word1->type variable list not obtain from server, return not match
      return false;
    }
  }

  // free previous malloc
950
  if (word1->free && word1->word) {
A
Alex Duan 已提交
951 952 953 954 955
    taosMemoryFree(word1->word);
  }

  // save
  word1->word = str;
956 957 958
  word1->len = strlen(str);
  word1->free = true;  // need free

A
Alex Duan 已提交
959 960 961 962 963 964 965 966
  return true;
}

//
//  -------------------  match words --------------------------
//

// compare command cmd1 come from shellCommands , cmd2 come from user input
967 968 969
int32_t compareCommand(SWords* cmd1, SWords* cmd2) {
  SWord* word1 = cmd1->head;
  SWord* word2 = cmd2->head;
A
Alex Duan 已提交
970 971 972 973 974 975 976 977 978

  if (word1 == NULL || word2 == NULL) {
    return -1;
  }

  for (int32_t i = 0; i < cmd1->count; i++) {
    if (word1->type == WT_TEXT) {
      // WT_TEXT match
      if (word1->len == word2->len) {
979
        if (strncasecmp(word1->word, word2->word, word1->len) != 0) return -1;
A
Alex Duan 已提交
980 981 982 983 984 985 986 987 988 989 990 991 992 993
      } else if (word1->len < word2->len) {
        return -1;
      } else {
        // word1->len > word2->len
        if (strncasecmp(word1->word, word2->word, word2->len) == 0) {
          cmd1->matchIndex = i;
          cmd1->matchLen = word2->len;
          return i;
        } else {
          return -1;
        }
      }
    } else {
      // WT_VAR auto match any one word
994
      if (word2->next == NULL) {  // input words last one
A
Alex Duan 已提交
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
        if (matchVarWord(word1, word2)) {
          cmd1->matchIndex = i;
          cmd1->matchLen = word2->len;
          varMode = true;
          return i;
        }
        return -1;
      }
    }

    // move next
    word1 = word1->next;
    word2 = word2->next;
    if (word1 == NULL || word2 == NULL) {
      return -1;
    }
  }

  return -1;
}

// match command
1017
SWords* matchCommand(SWords* input, bool continueSearch) {
A
Alex Duan 已提交
1018
  int32_t count = SHELL_COMMAND_COUNT();
1019 1020
  for (int32_t i = 0; i < count; i++) {
    SWords* shellCommand = shellCommands + i;
A
Alex Duan 已提交
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    if (continueSearch && lastMatchIndex != -1 && i <= lastMatchIndex) {
      // new match must greate than lastMatchIndex
      if (varMode && i == lastMatchIndex) {
        // do nothing, var match on lastMatchIndex
      } else {
        continue;
      }
    }

    // command is large
1031
    if (input->count > shellCommand->count) {
A
Alex Duan 已提交
1032 1033 1034 1035 1036 1037
      continue;
    }

    // compare
    int32_t index = compareCommand(shellCommand, input);
    if (index != -1) {
1038
      if (firstMatchIndex == -1) firstMatchIndex = i;
A
Alex Duan 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
      curMatchIndex = i;
      return &shellCommands[i];
    }
  }

  // not match
  return NULL;
}

//
//  -------------------  print screen --------------------------
//

// delete char count
1053
void deleteCount(SShellCmd* cmd, int count) {
A
Alex Duan 已提交
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
  int size = 0;
  int width = 0;
  int prompt_size = 6;
  shellClearScreen(cmd->endOffset + prompt_size, cmd->screenOffset + prompt_size);

  // loop delete
  while (--count >= 0 && cmd->cursorOffset > 0) {
    shellGetPrevCharSize(cmd->command, cmd->cursorOffset, &size, &width);
    memmove(cmd->command + cmd->cursorOffset - size, cmd->command + cmd->cursorOffset,
            cmd->commandSize - cmd->cursorOffset);
    cmd->commandSize -= size;
    cmd->cursorOffset -= size;
    cmd->screenOffset -= width;
    cmd->endOffset -= width;
  }
}

// show screen
1072
void printScreen(TAOS* con, SShellCmd* cmd, SWords* match) {
A
Alex Duan 已提交
1073 1074 1075
  // modify SShellCmd
  if (firstMatchIndex == -1 || curMatchIndex == -1) {
    // no match
1076
    return;
A
Alex Duan 已提交
1077 1078
  }

1079 1080 1081
  // first tab press
  const char* str = NULL;
  int         strLen = 0;
A
Alex Duan 已提交
1082 1083 1084

  if (firstMatchIndex == curMatchIndex && lastWordBytes == -1) {
    // first press tab
1085
    SWord* word = MATCH_WORD(match);
A
Alex Duan 已提交
1086 1087 1088 1089 1090
    str = word->word + match->matchLen;
    strLen = word->len - match->matchLen;
    lastMatchIndex = firstMatchIndex;
    lastWordBytes = word->len;
  } else {
1091
    if (lastWordBytes == -1) return;
A
Alex Duan 已提交
1092 1093
    deleteCount(cmd, lastWordBytes);

1094
    SWord* word = MATCH_WORD(match);
A
Alex Duan 已提交
1095 1096 1097 1098 1099 1100
    str = word->word;
    strLen = word->len;
    // set current to last
    lastMatchIndex = curMatchIndex;
    lastWordBytes = word->len;
  }
1101

A
Alex Duan 已提交
1102
  // insert new
A
Alex Duan 已提交
1103
  shellInsertStr(cmd, (char*)str, strLen);
A
Alex Duan 已提交
1104 1105 1106
}

// main key press tab , matched return true else false
1107
bool firstMatchCommand(TAOS* con, SShellCmd* cmd) {
A
Alex Duan 已提交
1108
  // parse command
1109
  SWords* input = (SWords*)taosMemoryMalloc(sizeof(SWords));
A
Alex Duan 已提交
1110 1111 1112 1113 1114 1115
  memset(input, 0, sizeof(SWords));
  input->source = cmd->command;
  input->source_len = cmd->commandSize;
  parseCommand(input, false);

  // if have many , default match first, if press tab again , switch to next
1116
  curMatchIndex = -1;
A
Alex Duan 已提交
1117
  lastMatchIndex = -1;
1118
  SWords* match = matchCommand(input, true);
A
Alex Duan 已提交
1119 1120 1121 1122 1123 1124 1125 1126 1127
  if (match == NULL) {
    // not match , nothing to do
    freeCommand(input);
    taosMemoryFree(input);
    return false;
  }

  // print to screen
  printScreen(con, cmd, match);
wafwerar's avatar
wafwerar 已提交
1128 1129 1130 1131
#ifdef WINDOWS
  printf("\r");
  shellShowOnScreen(cmd);
#endif
A
Alex Duan 已提交
1132 1133 1134 1135 1136 1137
  freeCommand(input);
  taosMemoryFree(input);
  return true;
}

// create input source
1138
void createInputFromFirst(SWords* input, SWords* firstMatch) {
A
Alex Duan 已提交
1139 1140 1141 1142
  //
  // if next pressTabKey , input context come from firstMatch, set matched length with source_len
  //
  input->source = (char*)taosMemoryMalloc(1024);
1143
  memset((void*)input->source, 0, 1024);
A
Alex Duan 已提交
1144

1145
  SWord* word = firstMatch->head;
A
Alex Duan 已提交
1146

1147
  // source_len = full match word->len + half match with firstMatch->matchLen
A
Alex Duan 已提交
1148 1149 1150
  for (int i = 0; i < firstMatch->matchIndex && word; i++) {
    // combine source from each word
    strncpy(input->source + input->source_len, word->word, word->len);
1151 1152
    strcat(input->source, " ");          // append blank splite
    input->source_len += word->len + 1;  // 1 is blank length
A
Alex Duan 已提交
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
    // move next
    word = word->next;
  }
  // appand half matched word for last
  if (word) {
    strncpy(input->source + input->source_len, word->word, firstMatch->matchLen);
    input->source_len += firstMatch->matchLen;
  }
}

// user press Tabkey again is named next , matched return true else false
1164
bool nextMatchCommand(TAOS* con, SShellCmd* cmd, SWords* firstMatch) {
A
Alex Duan 已提交
1165 1166 1167
  if (firstMatch == NULL || firstMatch->head == NULL) {
    return false;
  }
1168
  SWords* input = (SWords*)taosMemoryMalloc(sizeof(SWords));
A
Alex Duan 已提交
1169 1170 1171 1172 1173 1174 1175 1176 1177
  memset(input, 0, sizeof(SWords));

  // create input from firstMatch
  createInputFromFirst(input, firstMatch);

  // parse input
  parseCommand(input, false);

  // if have many , default match first, if press tab again , switch to next
1178
  SWords* match = matchCommand(input, true);
A
Alex Duan 已提交
1179 1180 1181
  if (match == NULL) {
    // if not match , reset all index
    firstMatchIndex = -1;
1182
    curMatchIndex = -1;
A
Alex Duan 已提交
1183 1184 1185
    match = matchCommand(input, false);
    if (match == NULL) {
      freeCommand(input);
1186
      if (input->source) taosMemoryFree(input->source);
A
Alex Duan 已提交
1187 1188 1189 1190 1191 1192 1193
      taosMemoryFree(input);
      return false;
    }
  }

  // print to screen
  printScreen(con, cmd, match);
wafwerar's avatar
wafwerar 已提交
1194 1195 1196 1197
#ifdef WINDOWS
  printf("\r");
  shellShowOnScreen(cmd);
#endif
A
Alex Duan 已提交
1198 1199

  // free
A
Alex Duan 已提交
1200
  freeCommand(input);
A
Alex Duan 已提交
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
  if (input->source) {
    taosMemoryFree(input->source);
    input->source = NULL;
  }
  taosMemoryFree(input);

  return true;
}

// fill with type
1211
bool fillWithType(TAOS* con, SShellCmd* cmd, char* pre, int type) {
A
Alex Duan 已提交
1212 1213
  // get type
  STire* tire = tires[type];
1214
  char*  str = matchNextPrefix(tire, pre);
A
Alex Duan 已提交
1215 1216 1217 1218 1219
  if (str == NULL) {
    return false;
  }

  // need insert part string
1220
  char* part = str + strlen(pre);
A
Alex Duan 已提交
1221 1222 1223

  // show
  int count = strlen(part);
A
Alex Duan 已提交
1224
  shellInsertStr(cmd, part, count);
1225
  cntDel = count;  // next press tab delete current append count
A
Alex Duan 已提交
1226 1227 1228 1229 1230 1231

  taosMemoryFree(str);
  return true;
}

// fill with type
1232
bool fillTableName(TAOS* con, SShellCmd* cmd, char* pre) {
A
Alex Duan 已提交
1233
  // search stable and table
1234
  char* str = tireSearchWord(WT_VAR_STABLE, pre);
A
Alex Duan 已提交
1235 1236
  if (str == NULL) {
    str = tireSearchWord(WT_VAR_TABLE, pre);
1237
    if (str == NULL) return false;
A
Alex Duan 已提交
1238 1239 1240
  }

  // need insert part string
1241
  char* part = str + strlen(pre);
A
Alex Duan 已提交
1242 1243

  // delete autofill count last append
1244
  if (cntDel > 0) {
A
Alex Duan 已提交
1245 1246 1247 1248 1249 1250
    deleteCount(cmd, cntDel);
    cntDel = 0;
  }

  // show
  int count = strlen(part);
A
Alex Duan 已提交
1251
  shellInsertStr(cmd, part, count);
1252 1253
  cntDel = count;  // next press tab delete current append count

A
Alex Duan 已提交
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
  taosMemoryFree(str);
  return true;
}

//
// find last word from sql select clause
//  example :
//  1 select cou -> press tab  select count(
//  2 select count(*),su -> select count(*), sum(
//  3 select count(*), su -> select count(*), sum(
//
1265 1266 1267 1268
char* lastWord(char* p) {
  // get near from end revert find ' ' and ','
  char* p1 = strrchr(p, ' ');
  char* p2 = strrchr(p, ',');
A
Alex Duan 已提交
1269 1270

  if (p1 && p2) {
1271
    return p1 > p2 ? p1 + 1 : p2 + 1;
A
Alex Duan 已提交
1272 1273
  } else if (p1) {
    return p1 + 1;
1274
  } else if (p2) {
A
Alex Duan 已提交
1275 1276 1277
    return p2 + 1;
  } else {
    return p;
1278
  }
A
Alex Duan 已提交
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
}

bool fieldsInputEnd(char* sql) {
  // not in '()'
  char* p1 = strrchr(sql, '(');
  char* p2 = strrchr(sql, ')');
  if (p1 && p2 == NULL) {
    // like select count( '  '
    return false;
  } else if (p1 && p2 && p1 > p2) {
    // like select sum(age), count( ' '
    return false;
  }

  // not in ','
1294 1295 1296
  char* p3 = strrchr(sql, ',');
  char* p = p3;
  // like select ts, age,'    '
A
Alex Duan 已提交
1297 1298
  if (p) {
    ++p;
1299 1300 1301 1302
    bool  allBlank = true;  // after last ','  all char is blank
    int   cnt = 0;          // blank count , like '    ' as one blank
    char* plast = NULL;     // last blank position
    while (*p) {
A
Alex Duan 已提交
1303 1304
      if (*p == ' ') {
        plast = p;
1305
        cnt++;
A
Alex Duan 已提交
1306 1307 1308 1309 1310 1311 1312
      } else {
        allBlank = false;
      }
      ++p;
    }

    // any one word is not blank
1313
    if (allBlank) {
A
Alex Duan 已提交
1314 1315 1316 1317 1318 1319 1320 1321 1322
      return false;
    }

    // like 'select count(*),sum(age) fr' need return true
    if (plast && plast > p3 && p2 > p1 && plast > p2 && p1 > p3) {
      return true;
    }

    // if last char not ' ', then not end field, like 'select count(*), su' can fill sum(
1323
    if (sql[strlen(sql) - 1] != ' ' && cnt <= 1) {
A
Alex Duan 已提交
1324 1325 1326 1327
      return false;
    }
  }

1328 1329
  char* p4 = strrchr(sql, ' ');
  if (p4 == NULL) {
A
Alex Duan 已提交
1330 1331 1332 1333 1334 1335 1336 1337
    // only one word
    return false;
  }

  return true;
}

// need insert from
1338 1339 1340
bool needInsertFrom(char* sql, int len) {
  // last is blank
  if (sql[len - 1] != ' ') {
A
Alex Duan 已提交
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
    // insert from keyword
    return false;
  }

  //  select fields input is end
  if (!fieldsInputEnd(sql)) {
    return false;
  }

  // can insert from keyword
  return true;
}

A
Alex Duan 已提交
1354
// p is string following select keyword
1355
bool appendAfterSelect(TAOS* con, SShellCmd* cmd, char* sql, int32_t len) {
A
Alex Duan 已提交
1356
  char* p = strndup(sql, len);
A
Alex Duan 已提交
1357 1358

  // union all
1359
  char* p1;
A
Alex Duan 已提交
1360 1361
  do {
    p1 = strstr(p, UNION_ALL);
1362
    if (p1) {
A
Alex Duan 已提交
1363 1364 1365 1366
      p = p1 + strlen(UNION_ALL);
    }
  } while (p1);

1367 1368 1369 1370
  char* from = strstr(p, " from ");
  // last word , maybe empty string or some letters of a string
  char* last = lastWord(p);
  bool  ret = false;
A
Alex Duan 已提交
1371 1372
  if (from == NULL) {
    bool fieldEnd = fieldsInputEnd(p);
A
Alex Duan 已提交
1373
    // check fields input end then insert from keyword
1374
    if (fieldEnd && p[len - 1] == ' ') {
A
Alex Duan 已提交
1375
      shellInsertStr(cmd, "from", 4);
A
Alex Duan 已提交
1376
      taosMemoryFree(p);
A
Alex Duan 已提交
1377 1378 1379 1380
      return true;
    }

    // fill funciton
1381
    if (fieldEnd) {
A
Alex Duan 已提交
1382 1383 1384 1385 1386
      // fields is end , need match keyword
      ret = fillWithType(con, cmd, last, WT_VAR_KEYWORD);
    } else {
      ret = fillWithType(con, cmd, last, WT_VAR_FUNC);
    }
1387

A
Alex Duan 已提交
1388
    taosMemoryFree(p);
A
Alex Duan 已提交
1389 1390 1391 1392
    return ret;
  }

  // have from
1393
  char* blank = strstr(from + 6, " ");
A
Alex Duan 已提交
1394 1395 1396 1397 1398 1399 1400
  if (blank == NULL) {
    // no table name, need fill
    ret = fillTableName(con, cmd, last);
  } else {
    ret = fillWithType(con, cmd, last, WT_VAR_KEYWORD);
  }

A
Alex Duan 已提交
1401
  taosMemoryFree(p);
A
Alex Duan 已提交
1402 1403 1404
  return ret;
}

A
Alex Duan 已提交
1405 1406
int32_t searchAfterSelect(char* p, int32_t len) {
  // select * from st;
1407
  if (strncasecmp(p, "select ", 7) == 0) {
A
Alex Duan 已提交
1408
    // check nest query
1409 1410 1411 1412
    char* p1 = p + 7;
    while (1) {
      char* p2 = strstr(p1, "select ");
      if (p2 == NULL) break;
A
Alex Duan 已提交
1413 1414 1415 1416 1417 1418 1419
      p1 = p2 + 7;
    }

    return p1 - p;
  }

  // explain as select * from st;
1420
  if (strncasecmp(p, "explain select ", 15) == 0) {
A
Alex Duan 已提交
1421 1422 1423 1424
    return 15;
  }

  char* as_pos_end = strstr(p, " as select ");
1425
  if (as_pos_end == NULL) return -1;
A
Alex Duan 已提交
1426 1427 1428
  as_pos_end += 11;

  // create stream <stream_name> as select
1429 1430 1431
  if (strncasecmp(p, "create stream ", 14) == 0) {
    return as_pos_end - p;
    ;
A
Alex Duan 已提交
1432 1433 1434
  }

  // create topic <topic_name> as select
1435
  if (strncasecmp(p, "create topic ", 13) == 0) {
A
Alex Duan 已提交
1436 1437 1438 1439 1440 1441
    return as_pos_end - p;
  }

  return -1;
}

1442
bool matchSelectQuery(TAOS* con, SShellCmd* cmd) {
A
Alex Duan 已提交
1443 1444 1445 1446 1447 1448 1449
  // if continue press Tab , delete bytes by previous autofill
  if (cntDel > 0) {
    deleteCount(cmd, cntDel);
    cntDel = 0;
  }

  // match select ...
1450 1451
  int   len = cmd->commandSize;
  char* p = cmd->command;
A
Alex Duan 已提交
1452 1453 1454 1455 1456 1457 1458 1459

  // remove prefix blank
  while (p[0] == ' ' && len > 0) {
    p++;
    len--;
  }

  // special range
1460
  if (len < 7 || len > 512) {
A
Alex Duan 已提交
1461 1462 1463 1464
    return false;
  }

  // search
1465
  char*   sql_cp = strndup(p, len);
A
Alex Duan 已提交
1466 1467
  int32_t n = searchAfterSelect(sql_cp, len);
  taosMemoryFree(sql_cp);
1468 1469
  if (n == -1 || n > len) return false;
  p += n;
A
Alex Duan 已提交
1470 1471 1472 1473 1474 1475
  len -= n;

  // append
  return appendAfterSelect(con, cmd, p, len);
}

A
Alex Duan 已提交
1476
// if is input create fields or tags area, return true
1477 1478
bool isCreateFieldsArea(char* p) {
  char* left = strrchr(p, '(');
A
Alex Duan 已提交
1479 1480 1481 1482 1483
  if (left == NULL) {
    // like 'create table st'
    return false;
  }

1484 1485
  char* right = strrchr(p, ')');
  if (right == NULL) {
A
Alex Duan 已提交
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497
    // like 'create table st( '
    return true;
  }

  if (left > right) {
    // like 'create table st( ts timestamp, age int) tags(area '
    return true;
  }

  return false;
}

1498
bool matchCreateTable(TAOS* con, SShellCmd* cmd) {
A
Alex Duan 已提交
1499 1500 1501 1502 1503 1504 1505
  // if continue press Tab , delete bytes by previous autofill
  if (cntDel > 0) {
    deleteCount(cmd, cntDel);
    cntDel = 0;
  }

  // match select ...
1506 1507
  int   len = cmd->commandSize;
  char* p = cmd->command;
A
Alex Duan 已提交
1508 1509 1510 1511 1512 1513 1514 1515

  // remove prefix blank
  while (p[0] == ' ' && len > 0) {
    p++;
    len--;
  }

  // special range
1516
  if (len < 7 || len > 1024) {
A
Alex Duan 已提交
1517 1518 1519
    return false;
  }

1520 1521
  // select and from
  if (strncasecmp(p, "create table ", 13) != 0) {
A
Alex Duan 已提交
1522 1523 1524 1525 1526 1527 1528
    // not select query clause
    return false;
  }
  p += 13;
  len -= 13;

  char* ps = strndup(p, len);
1529 1530
  bool  ret = false;
  char* last = lastWord(ps);
A
Alex Duan 已提交
1531 1532 1533 1534 1535 1536 1537 1538 1539

  // check in create fields or tags input area
  if (isCreateFieldsArea(ps)) {
    ret = fillWithType(con, cmd, last, WT_VAR_DATATYPE);
  }

  // tags
  if (!ret) {
    // find only one ')' , can insert tags
1540
    char* p1 = strchr(ps, ')');
A
Alex Duan 已提交
1541
    if (p1) {
1542
      if (strchr(p1 + 1, ')') == NULL && strstr(p1 + 1, "tags") == NULL) {
A
Alex Duan 已提交
1543 1544 1545 1546 1547 1548
        // can insert tags keyword
        ret = fillWithType(con, cmd, last, WT_VAR_KEYTAGS);
      }
    }
  }

A
Alex Duan 已提交
1549 1550 1551
  // tb options
  if (!ret) {
    // find like create talbe st (...) tags(..)  <here is fill tb option area>
1552
    char* p1 = strchr(ps, ')');  // first ')' end
A
Alex Duan 已提交
1553
    if (p1) {
1554
      if (strchr(p1 + 1, ')')) {  // second ')' end
A
Alex Duan 已提交
1555 1556 1557 1558 1559 1560
        // here is tb options area, can insert option
        ret = fillWithType(con, cmd, last, WT_VAR_TBOPTION);
      }
    }
  }

A
Alex Duan 已提交
1561 1562 1563 1564
  taosMemoryFree(ps);
  return ret;
}

1565 1566
bool matchOther(TAOS* con, SShellCmd* cmd) {
  int   len = cmd->commandSize;
A
Alex Duan 已提交
1567 1568
  char* p = cmd->command;

A
Alex Duan 已提交
1569
  // '\\'
A
Alex Duan 已提交
1570 1571 1572
  if (p[len - 1] == '\\') {
    // append '\G'
    char a[] = "G;";
A
Alex Duan 已提交
1573
    shellInsertStr(cmd, a, 2);
A
Alex Duan 已提交
1574 1575
    return true;
  }
A
Alex Duan 已提交
1576 1577

  // too small
1578
  if (len < 8) return false;
A
Alex Duan 已提交
1579 1580 1581 1582 1583 1584 1585 1586

  // like 'from ( '
  char* sql = strndup(p, len);
  char* last = lastWord(sql);

  if (strcmp(last, "from(") == 0) {
    fillWithType(con, cmd, "", WT_VAR_KEYSELECT);
    taosMemoryFree(sql);
1587
    return true;
A
Alex Duan 已提交
1588 1589
  }
  if (strncmp(last, "(", 1) == 0) {
1590
    last += 1;
A
Alex Duan 已提交
1591 1592 1593 1594 1595 1596
  }

  char* from = strstr(sql, " from");
  // find last ' from'
  while (from) {
    char* p1 = strstr(from + 5, " from");
1597
    if (p1 == NULL) break;
A
Alex Duan 已提交
1598 1599 1600 1601 1602
    from = p1;
  }

  if (from) {
    // find next is '('
1603 1604 1605
    char* p2 = from + 5;
    bool  found = false;   // found 'from ... ( ...'  ... is any count of blank
    bool  found1 = false;  // found '('
A
Alex Duan 已提交
1606
    while (1) {
1607
      if (p2 == last || *p2 == '\0') {
A
Alex Duan 已提交
1608 1609 1610 1611 1612
        // last word or string end
        if (found1) {
          found = true;
        }
        break;
1613
      } else if (*p2 == '(') {
A
Alex Duan 已提交
1614
        found1 = true;
1615
      } else if (*p2 == ' ') {
A
Alex Duan 已提交
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
        // do nothing
      } else {
        // have any other char
        break;
      }

      // move next
      p2++;
    }

    if (found) {
      fillWithType(con, cmd, last, WT_VAR_KEYSELECT);
      taosMemoryFree(sql);
      return true;
    }
  }

1633
  // INSERT
A
Alex Duan 已提交
1634 1635

  taosMemoryFree(sql);
1636

A
Alex Duan 已提交
1637 1638 1639 1640
  return false;
}

// main key press tab
1641 1642 1643
void pressTabKey(SShellCmd* cmd) {
  // check
  if (cmd->commandSize == 0) {
A
Alex Duan 已提交
1644 1645 1646
    // empty
    showHelp();
    shellShowOnScreen(cmd);
1647 1648
    return;
  }
A
Alex Duan 已提交
1649 1650 1651 1652 1653 1654 1655

  // save connection to global
  varCmd = cmd;
  bool matched = false;

  // manual match like create table st( ...
  matched = matchCreateTable(varCon, cmd);
1656
  if (matched) return;
A
Alex Duan 已提交
1657

1658
  // shellCommands match
A
Alex Duan 已提交
1659 1660 1661 1662 1663
  if (firstMatchIndex == -1) {
    matched = firstMatchCommand(varCon, cmd);
  } else {
    matched = nextMatchCommand(varCon, cmd, &shellCommands[firstMatchIndex]);
  }
1664
  if (matched) return;
A
Alex Duan 已提交
1665 1666 1667 1668

  // NOT MATCHED ANYONE
  // match other like '\G' ...
  matched = matchOther(varCon, cmd);
1669
  if (matched) return;
A
Alex Duan 已提交
1670 1671 1672

  // manual match like select * from ...
  matched = matchSelectQuery(varCon, cmd);
1673
  if (matched) return;
A
Alex Duan 已提交
1674

1675
  return;
A
Alex Duan 已提交
1676 1677 1678 1679 1680 1681
}

// press othr key
void pressOtherKey(char c) {
  // reset global variant
  firstMatchIndex = -1;
1682 1683 1684
  lastMatchIndex = -1;
  curMatchIndex = -1;
  lastWordBytes = -1;
A
Alex Duan 已提交
1685 1686

  // var names
1687 1688
  cursorVar = -1;
  varMode = false;
A
Alex Duan 已提交
1689
  waitAutoFill = false;
1690
  cntDel = 0;
A
Alex Duan 已提交
1691 1692 1693 1694 1695 1696 1697 1698

  if (lastMatch) {
    freeMatch(lastMatch);
    lastMatch = NULL;
  }
}

// put name into name, return name length
1699 1700
int getWordName(char* p, char* name, int nameLen) {
  // remove prefix blank
A
Alex Duan 已提交
1701 1702 1703 1704 1705 1706
  while (*p == ' ') {
    p++;
  }

  // get databases name;
  int i = 0;
1707 1708
  while (p[i] != 0 && i < nameLen - 1) {
    name[i] = p[i];
A
Alex Duan 已提交
1709
    i++;
1710
    if (p[i] == ' ' || p[i] == ';' || p[i] == '(') {
A
Alex Duan 已提交
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
      // name end
      break;
    }
  }
  name[i] = 0;

  return i;
}

// deal use db, if have  'use' return true
1721 1722 1723
bool dealUseDB(char* sql) {
  // check use keyword
  if (strncasecmp(sql, "use ", 4) != 0) {
A
Alex Duan 已提交
1724 1725
    return false;
  }
1726 1727 1728

  char  db[256];
  char* p = sql + 4;
A
Alex Duan 已提交
1729
  if (getWordName(p, db, sizeof(db)) == 0) {
1730
    // no name , return
A
Alex Duan 已提交
1731 1732 1733 1734 1735
    return true;
  }

  //  dbName is previous use open db name
  if (strcasecmp(db, dbName) == 0) {
1736
    // same , no need switch
A
Alex Duan 已提交
1737 1738 1739 1740 1741 1742 1743 1744
    return true;
  }

  // switch new db
  taosThreadMutexLock(&tiresMutex);
  // STABLE set null
  STire* tire = tires[WT_VAR_STABLE];
  tires[WT_VAR_STABLE] = NULL;
1745
  if (tire) {
A
Alex Duan 已提交
1746 1747 1748 1749 1750
    freeTire(tire);
  }
  // TABLE set null
  tire = tires[WT_VAR_TABLE];
  tires[WT_VAR_TABLE] = NULL;
1751
  if (tire) {
A
Alex Duan 已提交
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761
    freeTire(tire);
  }
  // save
  strcpy(dbName, db);
  taosThreadMutexUnlock(&tiresMutex);

  return true;
}

// deal create, if have 'create' return true
1762 1763 1764
bool dealCreateCommand(char* sql) {
  // check keyword
  if (strncasecmp(sql, "create ", 7) != 0) {
A
Alex Duan 已提交
1765 1766
    return false;
  }
1767 1768 1769

  char  name[1024];
  char* p = sql + 7;
A
Alex Duan 已提交
1770
  if (getWordName(p, name, sizeof(name)) == 0) {
1771
    // no name , return
A
Alex Duan 已提交
1772 1773 1774 1775 1776 1777 1778 1779
    return true;
  }

  int type = -1;
  //  dbName is previous use open db name
  if (strcasecmp(name, "database") == 0) {
    type = WT_VAR_DBNAME;
  } else if (strcasecmp(name, "table") == 0) {
1780
    if (strstr(sql, " tags") != NULL && strstr(sql, " using ") == NULL)
A
Alex Duan 已提交
1781 1782 1783 1784 1785
      type = WT_VAR_STABLE;
    else
      type = WT_VAR_TABLE;
  } else if (strcasecmp(name, "user") == 0) {
    type = WT_VAR_USERNAME;
A
Alex Duan 已提交
1786 1787 1788 1789
  } else if (strcasecmp(name, "topic") == 0) {
    type = WT_VAR_TOPIC;
  } else if (strcasecmp(name, "stream") == 0) {
    type = WT_VAR_STREAM;
A
Alex Duan 已提交
1790
  } else {
1791
    // no match , return
A
Alex Duan 已提交
1792 1793 1794 1795 1796 1797 1798 1799
    return true;
  }

  // move next
  p += strlen(name);

  // get next word , that is table name
  if (getWordName(p, name, sizeof(name)) == 0) {
1800
    // no name , return
A
Alex Duan 已提交
1801 1802 1803 1804 1805 1806 1807
    return true;
  }

  // switch new db
  taosThreadMutexLock(&tiresMutex);
  // STABLE set null
  STire* tire = tires[type];
1808
  if (tire) {
A
Alex Duan 已提交
1809 1810 1811 1812 1813 1814 1815 1816
    insertWord(tire, name);
  }
  taosThreadMutexUnlock(&tiresMutex);

  return true;
}

// deal create, if have 'drop' return true
1817 1818 1819
bool dealDropCommand(char* sql) {
  // check keyword
  if (strncasecmp(sql, "drop ", 5) != 0) {
A
Alex Duan 已提交
1820 1821
    return false;
  }
1822 1823 1824

  char  name[1024];
  char* p = sql + 5;
A
Alex Duan 已提交
1825
  if (getWordName(p, name, sizeof(name)) == 0) {
1826
    // no name , return
A
Alex Duan 已提交
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
    return true;
  }

  int type = -1;
  //  dbName is previous use open db name
  if (strcasecmp(name, "database") == 0) {
    type = WT_VAR_DBNAME;
  } else if (strcasecmp(name, "table") == 0) {
    type = WT_VAR_ALLTABLE;
  } else if (strcasecmp(name, "dnode") == 0) {
    type = WT_VAR_DNODEID;
  } else if (strcasecmp(name, "user") == 0) {
    type = WT_VAR_USERNAME;
A
Alex Duan 已提交
1840 1841 1842 1843
  } else if (strcasecmp(name, "topic") == 0) {
    type = WT_VAR_TOPIC;
  } else if (strcasecmp(name, "stream") == 0) {
    type = WT_VAR_STREAM;
A
Alex Duan 已提交
1844
  } else {
1845
    // no match , return
A
Alex Duan 已提交
1846 1847 1848 1849 1850 1851 1852 1853
    return true;
  }

  // move next
  p += strlen(name);

  // get next word , that is table name
  if (getWordName(p, name, sizeof(name)) == 0) {
1854
    // no name , return
A
Alex Duan 已提交
1855 1856 1857 1858 1859 1860
    return true;
  }

  // switch new db
  taosThreadMutexLock(&tiresMutex);
  // STABLE set null
1861
  if (type == WT_VAR_ALLTABLE) {
A
Alex Duan 已提交
1862 1863 1864
    bool del = false;
    // del in stable
    STire* tire = tires[WT_VAR_STABLE];
1865
    if (tire) del = deleteWord(tire, name);
A
Alex Duan 已提交
1866
    // del in table
1867
    if (!del) {
A
Alex Duan 已提交
1868
      tire = tires[WT_VAR_TABLE];
1869
      if (tire) del = deleteWord(tire, name);
A
Alex Duan 已提交
1870 1871 1872 1873
    }
  } else {
    // OTHER TYPE
    STire* tire = tires[type];
1874
    if (tire) deleteWord(tire, name);
A
Alex Duan 已提交
1875 1876 1877 1878 1879 1880 1881 1882
  }
  taosThreadMutexUnlock(&tiresMutex);

  return true;
}

// callback autotab module after shell sql execute
void callbackAutoTab(char* sqlstr, TAOS* pSql, bool usedb) {
1883
  char* sql = sqlstr;
A
Alex Duan 已提交
1884 1885 1886 1887 1888
  // remove prefix blank
  while (*sql == ' ') {
    sql++;
  }

1889
  if (dealUseDB(sql)) {
A
Alex Duan 已提交
1890
    // change to new db
1891
    return;
A
Alex Duan 已提交
1892 1893 1894
  }

  // create command add name to autotab
1895 1896
  if (dealCreateCommand(sql)) {
    return;
A
Alex Duan 已提交
1897 1898 1899
  }

  // drop command remove name from autotab
1900 1901
  if (dealDropCommand(sql)) {
    return;
A
Alex Duan 已提交
1902 1903
  }

1904
  return;
A
Alex Duan 已提交
1905
}