parTestUtil.cpp 16.0 KB
Newer Older
X
Xiaoyu Wang 已提交
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/>.
 */

#include "parTestUtil.h"

#include <algorithm>
#include <array>
20
#include <thread>
X
Xiaoyu Wang 已提交
21

22 23
#include "catalog.h"
#include "mockCatalogService.h"
X
Xiaoyu Wang 已提交
24 25 26
#include "parInt.h"

using namespace std;
27
using namespace std::placeholders;
X
Xiaoyu Wang 已提交
28 29
using namespace testing;

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
namespace ParserTest {

#define DO_WITH_THROW(func, ...)                                                                                     \
  do {                                                                                                               \
    int32_t code__ = func(__VA_ARGS__);                                                                              \
    if (!checkResultCode(#func, code__)) {                                                                           \
      if (TSDB_CODE_SUCCESS != code__) {                                                                             \
        throw runtime_error("sql:[" + stmtEnv_.sql_ + "] " #func " code:" + to_string(code__) +                      \
                            ", strerror:" + string(tstrerror(code__)) + ", msg:" + string(stmtEnv_.msgBuf_.data())); \
      } else {                                                                                                       \
        throw runtime_error("sql:[" + stmtEnv_.sql_ + "] " #func " expect " + to_string(stmtEnv_.expect_) +          \
                            " actual " + to_string(code__));                                                         \
      }                                                                                                              \
    } else if (TSDB_CODE_SUCCESS != code__) {                                                                        \
      throw TerminateFlag();                                                                                         \
    }                                                                                                                \
X
Xiaoyu Wang 已提交
46 47
  } while (0);

48
bool    g_dump = false;
49
bool    g_testAsyncApis = true;
50 51 52 53
int32_t g_logLevel = 131;
int32_t g_skipSql = 0;

void setAsyncFlag(const char* pFlag) { g_testAsyncApis = stoi(pFlag) > 0 ? true : false; }
wafwerar's avatar
wafwerar 已提交
54
void setSkipSqlNum(const char* pNum) { g_skipSql = stoi(pNum); }
X
Xiaoyu Wang 已提交
55

56 57 58 59
struct TerminateFlag : public exception {
  const char* what() const throw() { return "success and terminate"; }
};

60 61 62 63
void setLogLevel(const char* pLogLevel) { g_logLevel = stoi(pLogLevel); }

int32_t getLogLevel() { return g_logLevel; }

X
Xiaoyu Wang 已提交
64 65
class ParserTestBaseImpl {
 public:
X
Xiaoyu Wang 已提交
66
  ParserTestBaseImpl(ParserTestBase* pBase) : pBase_(pBase), sqlNo_(0) {}
X
Xiaoyu Wang 已提交
67

68 69
  void login(const std::string& user) { caseEnv_.user_ = user; }

X
Xiaoyu Wang 已提交
70 71 72
  void useDb(const string& acctId, const string& db) {
    caseEnv_.acctId_ = acctId;
    caseEnv_.db_ = db;
73
    caseEnv_.nsql_ = g_skipSql;
X
Xiaoyu Wang 已提交
74 75
  }

76
  void run(const string& sql, int32_t expect, ParserStage checkStage) {
X
Xiaoyu Wang 已提交
77
    ++sqlNo_;
78 79 80 81 82
    if (caseEnv_.nsql_ > 0) {
      --(caseEnv_.nsql_);
      return;
    }

83 84
    runInternalFuncs(sql, expect, checkStage);
    runApis(sql, expect, checkStage);
85 86

    if (g_testAsyncApis) {
87 88
      runAsyncInternalFuncs(sql, expect, checkStage);
      runAsyncApis(sql, expect, checkStage);
89 90 91
    }
  }

X
Xiaoyu Wang 已提交
92 93
 private:
  struct caseEnv {
94
    string  acctId_;
95
    string  user_;
96 97
    string  db_;
    int32_t nsql_;
98 99

    caseEnv() : user_("wangxiaoyu"), nsql_(0) {}
X
Xiaoyu Wang 已提交
100 101 102 103 104
  };

  struct stmtEnv {
    string            sql_;
    array<char, 1024> msgBuf_;
105 106
    int32_t           expect_;
    string            checkFunc_;
X
Xiaoyu Wang 已提交
107 108 109 110 111 112 113 114
  };

  struct stmtRes {
    string parsedAst_;
    string translatedAst_;
    string calcConstAst_;
  };

115 116 117 118 119 120 121
  enum TestInterfaceType {
    TEST_INTERFACE_INTERNAL = 1,
    TEST_INTERFACE_API,
    TEST_INTERFACE_ASYNC_INTERNAL,
    TEST_INTERFACE_ASYNC_API
  };

122 123
  static void _destoryParseMetaCache(SParseMetaCache* pMetaCache, bool request) {
    destoryParseMetaCache(pMetaCache, request);
124 125 126
    delete pMetaCache;
  }

127 128 129 130 131 132 133 134
  static void _destroyQuery(SQuery** pQuery) {
    if (nullptr == pQuery) {
      return;
    }
    qDestroyQuery(*pQuery);
    taosMemoryFree(pQuery);
  }

135 136
  bool checkResultCode(const string& pFunc, int32_t resultCode) {
    return !(stmtEnv_.checkFunc_.empty())
137
               ? ((stmtEnv_.checkFunc_ == pFunc) ? stmtEnv_.expect_ == resultCode : TSDB_CODE_SUCCESS == resultCode)
138 139 140
               : true;
  }

141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
  string stageFunc(ParserStage stage, TestInterfaceType type) {
    switch (type) {
      case TEST_INTERFACE_INTERNAL:
      case TEST_INTERFACE_ASYNC_INTERNAL:
        switch (stage) {
          case PARSER_STAGE_PARSE:
            return "parse";
          case PARSER_STAGE_TRANSLATE:
            return "translate";
          case PARSER_STAGE_CALC_CONST:
            return "calculateConstant";
          default:
            break;
        }
        break;
      case TEST_INTERFACE_API:
        return "qParseSql";
      case TEST_INTERFACE_ASYNC_API:
        switch (stage) {
          case PARSER_STAGE_PARSE:
            return "qParseSqlSyntax";
          case PARSER_STAGE_TRANSLATE:
          case PARSER_STAGE_CALC_CONST:
            return "qAnalyseSqlSemantic";
          default:
            break;
        }
        break;
169 170 171 172 173 174
      default:
        break;
    }
    return "unknown";
  }

175
  void reset(int32_t expect, ParserStage checkStage, TestInterfaceType type) {
X
Xiaoyu Wang 已提交
176 177
    stmtEnv_.sql_.clear();
    stmtEnv_.msgBuf_.fill(0);
178
    stmtEnv_.expect_ = expect;
179
    stmtEnv_.checkFunc_ = stageFunc(checkStage, type);
X
Xiaoyu Wang 已提交
180 181 182 183 184 185 186

    res_.parsedAst_.clear();
    res_.translatedAst_.clear();
    res_.calcConstAst_.clear();
  }

  void dump() {
X
Xiaoyu Wang 已提交
187
    cout << "========================================== " << sqlNo_ << " sql : [" << stmtEnv_.sql_ << "]" << endl;
188 189 190 191 192 193 194 195 196 197 198 199
    if (!res_.parsedAst_.empty()) {
      cout << "raw syntax tree : " << endl;
      cout << res_.parsedAst_ << endl;
    }
    if (!res_.translatedAst_.empty()) {
      cout << "translated syntax tree : " << endl;
      cout << res_.translatedAst_ << endl;
    }
    if (!res_.calcConstAst_.empty()) {
      cout << "optimized syntax tree : " << endl;
      cout << res_.calcConstAst_ << endl;
    }
X
Xiaoyu Wang 已提交
200 201
  }

202
  void setParseContext(const string& sql, SParseContext* pCxt, bool async = false) {
X
Xiaoyu Wang 已提交
203
    stmtEnv_.sql_ = sql;
204
    strtolower((char*)stmtEnv_.sql_.c_str(), sql.c_str());
X
Xiaoyu Wang 已提交
205 206 207

    pCxt->acctId = atoi(caseEnv_.acctId_.c_str());
    pCxt->db = caseEnv_.db_.c_str();
208 209
    pCxt->pUser = caseEnv_.user_.c_str();
    pCxt->isSuperUser = caseEnv_.user_ == "root";
210
    pCxt->enableSysInfo = true;
X
Xiaoyu Wang 已提交
211 212 213 214
    pCxt->pSql = stmtEnv_.sql_.c_str();
    pCxt->sqlLen = stmtEnv_.sql_.length();
    pCxt->pMsg = stmtEnv_.msgBuf_.data();
    pCxt->msgLen = stmtEnv_.msgBuf_.max_size();
215
    pCxt->async = async;
216
    pCxt->svrVer = "3.0.0.0";
X
Xiaoyu Wang 已提交
217 218 219 220
  }

  void doParse(SParseContext* pCxt, SQuery** pQuery) {
    DO_WITH_THROW(parse, pCxt, pQuery);
X
Xiaoyu Wang 已提交
221
    ASSERT_NE(*pQuery, nullptr);
X
Xiaoyu Wang 已提交
222 223 224
    res_.parsedAst_ = toString((*pQuery)->pRoot);
  }

225 226
  void doCollectMetaKey(SParseContext* pCxt, SQuery* pQuery, SParseMetaCache* pMetaCache) {
    DO_WITH_THROW(collectMetaKey, pCxt, pQuery, pMetaCache);
227 228
  }

X
Xiaoyu Wang 已提交
229 230
  void doBuildCatalogReq(SParseContext* pCxt, const SParseMetaCache* pMetaCache, SCatalogReq* pCatalogReq) {
    DO_WITH_THROW(buildCatalogReq, pCxt, pMetaCache, pCatalogReq);
231 232 233 234 235 236
  }

  void doGetAllMeta(const SCatalogReq* pCatalogReq, SMetaData* pMetaData) {
    DO_WITH_THROW(g_mockCatalogService->catalogGetAllMeta, pCatalogReq, pMetaData);
  }

X
Xiaoyu Wang 已提交
237 238 239
  void doPutMetaDataToCache(const SCatalogReq* pCatalogReq, const SMetaData* pMetaData, SParseMetaCache* pMetaCache,
                            bool isInsertValues) {
    DO_WITH_THROW(putMetaDataToCache, pCatalogReq, pMetaData, pMetaCache, isInsertValues);
240 241
  }

242 243 244
  void doAuthenticate(SParseContext* pCxt, SQuery* pQuery, SParseMetaCache* pMetaCache) {
    DO_WITH_THROW(authenticate, pCxt, pQuery, pMetaCache);
  }
245

246 247
  void doTranslate(SParseContext* pCxt, SQuery* pQuery, SParseMetaCache* pMetaCache) {
    DO_WITH_THROW(translate, pCxt, pQuery, pMetaCache);
X
Xiaoyu Wang 已提交
248
    checkQuery(pQuery, PARSER_STAGE_TRANSLATE);
X
Xiaoyu Wang 已提交
249 250 251 252 253 254 255 256
    res_.translatedAst_ = toString(pQuery->pRoot);
  }

  void doCalculateConstant(SParseContext* pCxt, SQuery* pQuery) {
    DO_WITH_THROW(calculateConstant, pCxt, pQuery);
    res_.calcConstAst_ = toString(pQuery->pRoot);
  }

257 258 259 260 261 262 263 264 265
  void doParseSql(SParseContext* pCxt, SQuery** pQuery) {
    DO_WITH_THROW(qParseSql, pCxt, pQuery);
    ASSERT_NE(*pQuery, nullptr);
    res_.calcConstAst_ = toString((*pQuery)->pRoot);
  }

  void doParseSqlSyntax(SParseContext* pCxt, SQuery** pQuery, SCatalogReq* pCatalogReq) {
    DO_WITH_THROW(qParseSqlSyntax, pCxt, pQuery, pCatalogReq);
    ASSERT_NE(*pQuery, nullptr);
X
Xiaoyu Wang 已提交
266 267 268
    if (nullptr != (*pQuery)->pRoot) {
      res_.parsedAst_ = toString((*pQuery)->pRoot);
    }
269 270 271 272 273 274 275 276
  }

  void doAnalyseSqlSemantic(SParseContext* pCxt, const SCatalogReq* pCatalogReq, const SMetaData* pMetaData,
                            SQuery* pQuery) {
    DO_WITH_THROW(qAnalyseSqlSemantic, pCxt, pCatalogReq, pMetaData, pQuery);
    res_.calcConstAst_ = toString(pQuery->pRoot);
  }

X
Xiaoyu Wang 已提交
277 278 279 280 281 282 283 284 285 286 287
  void doParseInsertSql(SParseContext* pCxt, SQuery** pQuery, SParseMetaCache* pMetaCache) {
    DO_WITH_THROW(parseInsertSql, pCxt, pQuery, pMetaCache);
    ASSERT_NE(*pQuery, nullptr);
    res_.parsedAst_ = toString((*pQuery)->pRoot);
  }

  void doParseInsertSyntax(SParseContext* pCxt, SQuery** pQuery, SParseMetaCache* pMetaCache) {
    DO_WITH_THROW(parseInsertSyntax, pCxt, pQuery, pMetaCache);
    ASSERT_NE(*pQuery, nullptr);
  }

X
Xiaoyu Wang 已提交
288 289 290 291 292 293 294 295 296
  string toString(const SNode* pRoot) {
    char*   pStr = NULL;
    int32_t len = 0;
    DO_WITH_THROW(nodesNodeToString, pRoot, false, &pStr, &len)
    string str(pStr);
    taosMemoryFreeClear(pStr);
    return str;
  }

X
Xiaoyu Wang 已提交
297 298
  void checkQuery(const SQuery* pQuery, ParserStage stage) { pBase_->checkDdl(pQuery, stage); }

299 300 301 302 303 304
  void runInternalFuncs(const string& sql, int32_t expect, ParserStage checkStage) {
    reset(expect, checkStage, TEST_INTERFACE_INTERNAL);
    try {
      SParseContext cxt = {0};
      setParseContext(sql, &cxt);

X
Xiaoyu Wang 已提交
305 306 307 308 309 310 311
      if (qIsInsertValuesSql(cxt.pSql, cxt.sqlLen)) {
        unique_ptr<SQuery*, void (*)(SQuery**)> query((SQuery**)taosMemoryCalloc(1, sizeof(SQuery*)), _destroyQuery);
        doParseInsertSql(&cxt, query.get(), nullptr);
      } else {
        unique_ptr<SQuery*, void (*)(SQuery**)> query((SQuery**)taosMemoryCalloc(1, sizeof(SQuery*)), _destroyQuery);
        doParse(&cxt, query.get());
        SQuery* pQuery = *(query.get());
312

X
Xiaoyu Wang 已提交
313
        doAuthenticate(&cxt, pQuery, nullptr);
314

X
Xiaoyu Wang 已提交
315
        doTranslate(&cxt, pQuery, nullptr);
316

X
Xiaoyu Wang 已提交
317 318
        doCalculateConstant(&cxt, pQuery);
      }
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337

      if (g_dump) {
        dump();
      }
    } catch (const TerminateFlag& e) {
      // success and terminate
      return;
    } catch (...) {
      dump();
      throw;
    }
  }

  void runApis(const string& sql, int32_t expect, ParserStage checkStage) {
    reset(expect, checkStage, TEST_INTERFACE_API);
    try {
      SParseContext cxt = {0};
      setParseContext(sql, &cxt);

338 339 340
      unique_ptr<SQuery*, void (*)(SQuery**)> query((SQuery**)taosMemoryCalloc(1, sizeof(SQuery*)), _destroyQuery);
      doParseSql(&cxt, query.get());
      SQuery* pQuery = *(query.get());
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355

      if (g_dump) {
        dump();
      }
    } catch (const TerminateFlag& e) {
      // success and terminate
      return;
    } catch (...) {
      dump();
      throw;
    }
  }

  void runAsyncInternalFuncs(const string& sql, int32_t expect, ParserStage checkStage) {
    reset(expect, checkStage, TEST_INTERFACE_ASYNC_INTERNAL);
356 357 358 359
    try {
      SParseContext cxt = {0};
      setParseContext(sql, &cxt, true);

360
      unique_ptr<SQuery*, void (*)(SQuery**)> query((SQuery**)taosMemoryCalloc(1, sizeof(SQuery*)), _destroyQuery);
X
Xiaoyu Wang 已提交
361
      bool                                    request = true;
362 363
      unique_ptr<SParseMetaCache, function<void(SParseMetaCache*)> > metaCache(
          new SParseMetaCache(), bind(_destoryParseMetaCache, _1, cref(request)));
X
Xiaoyu Wang 已提交
364 365 366 367 368 369 370 371 372
      bool isInsertValues = qIsInsertValuesSql(cxt.pSql, cxt.sqlLen);
      if (isInsertValues) {
        doParseInsertSyntax(&cxt, query.get(), metaCache.get());
      } else {
        doParse(&cxt, query.get());
        doCollectMetaKey(&cxt, *(query.get()), metaCache.get());
      }

      SQuery* pQuery = *(query.get());
373

374 375
      unique_ptr<SCatalogReq, void (*)(SCatalogReq*)> catalogReq(new SCatalogReq(),
                                                                 MockCatalogService::destoryCatalogReq);
X
Xiaoyu Wang 已提交
376
      doBuildCatalogReq(&cxt, metaCache.get(), catalogReq.get());
377 378 379 380

      string err;
      thread t1([&]() {
        try {
381 382
          unique_ptr<SMetaData, void (*)(SMetaData*)> metaData(new SMetaData(), MockCatalogService::destoryMetaData);
          doGetAllMeta(catalogReq.get(), metaData.get());
383

384 385
          metaCache.reset(new SParseMetaCache());
          request = false;
X
Xiaoyu Wang 已提交
386
          doPutMetaDataToCache(catalogReq.get(), metaData.get(), metaCache.get(), isInsertValues);
387

X
Xiaoyu Wang 已提交
388 389 390 391
          if (isInsertValues) {
            doParseInsertSql(&cxt, query.get(), metaCache.get());
          } else {
            doAuthenticate(&cxt, pQuery, metaCache.get());
392

X
Xiaoyu Wang 已提交
393
            doTranslate(&cxt, pQuery, metaCache.get());
394

X
Xiaoyu Wang 已提交
395 396
            doCalculateConstant(&cxt, pQuery);
          }
397 398 399 400
        } catch (const TerminateFlag& e) {
          // success and terminate
        } catch (const runtime_error& e) {
          err = e.what();
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
        } catch (...) {
          err = "unknown error";
        }
      });

      t1.join();
      if (!err.empty()) {
        throw runtime_error(err);
      }

      if (g_dump) {
        dump();
      }
    } catch (const TerminateFlag& e) {
      // success and terminate
      return;
    } catch (...) {
      dump();
      throw;
    }
  }

  void runAsyncApis(const string& sql, int32_t expect, ParserStage checkStage) {
    reset(expect, checkStage, TEST_INTERFACE_ASYNC_API);
    try {
      SParseContext cxt = {0};
      setParseContext(sql, &cxt);

      unique_ptr<SCatalogReq, void (*)(SCatalogReq*)> catalogReq(new SCatalogReq(),
                                                                 MockCatalogService::destoryCatalogReq);
431 432 433
      unique_ptr<SQuery*, void (*)(SQuery**)> query((SQuery**)taosMemoryCalloc(1, sizeof(SQuery*)), _destroyQuery);
      doParseSqlSyntax(&cxt, query.get(), catalogReq.get());
      SQuery* pQuery = *(query.get());
434 435 436 437 438 439 440 441 442 443 444 445

      string err;
      thread t1([&]() {
        try {
          unique_ptr<SMetaData, void (*)(SMetaData*)> metaData(new SMetaData(), MockCatalogService::destoryMetaData);
          doGetAllMeta(catalogReq.get(), metaData.get());

          doAnalyseSqlSemantic(&cxt, catalogReq.get(), metaData.get(), pQuery);
        } catch (const TerminateFlag& e) {
          // success and terminate
        } catch (const runtime_error& e) {
          err = e.what();
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467
        } catch (...) {
          err = "unknown error";
        }
      });

      t1.join();
      if (!err.empty()) {
        throw runtime_error(err);
      }

      if (g_dump) {
        dump();
      }
    } catch (const TerminateFlag& e) {
      // success and terminate
      return;
    } catch (...) {
      dump();
      throw;
    }
  }

X
Xiaoyu Wang 已提交
468 469 470 471
  caseEnv         caseEnv_;
  stmtEnv         stmtEnv_;
  stmtRes         res_;
  ParserTestBase* pBase_;
X
Xiaoyu Wang 已提交
472
  int32_t         sqlNo_;
X
Xiaoyu Wang 已提交
473 474
};

X
Xiaoyu Wang 已提交
475
ParserTestBase::ParserTestBase() : impl_(new ParserTestBaseImpl(this)) {}
X
Xiaoyu Wang 已提交
476 477 478

ParserTestBase::~ParserTestBase() {}

479 480
void ParserTestBase::login(const std::string& user) { return impl_->login(user); }

X
Xiaoyu Wang 已提交
481 482
void ParserTestBase::useDb(const std::string& acctId, const std::string& db) { impl_->useDb(acctId, db); }

483 484 485 486
void ParserTestBase::run(const std::string& sql, int32_t expect, ParserStage checkStage) {
  return impl_->run(sql, expect, checkStage);
}

X
Xiaoyu Wang 已提交
487 488
void ParserTestBase::checkDdl(const SQuery* pQuery, ParserStage stage) { return; }

489
}  // namespace ParserTest