MySQLMetaImpl.cpp 80.8 KB
Newer Older
Z
update  
zhiru 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*******************************************************************************
 * Copyright 上海赜睿信息科技有限公司(Zilliz) - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited.
 * Proprietary and confidential.
 ******************************************************************************/
#include "MySQLMetaImpl.h"
#include "IDGenerator.h"
#include "Utils.h"
#include "Log.h"
#include "MetaConsts.h"
#include "Factories.h"
#include "metrics/Metrics.h"

#include <unistd.h>
#include <sstream>
#include <iostream>
#include <boost/filesystem.hpp>
#include <chrono>
#include <fstream>
#include <regex>
#include <string>
Z
zhiru 已提交
22
#include <mutex>
Z
zhiru 已提交
23
#include <thread>
Z
update  
zhiru 已提交
24 25 26 27 28 29 30 31 32 33

#include "mysql++/mysql++.h"

namespace zilliz {
namespace milvus {
namespace engine {
namespace meta {

    using namespace mysqlpp;

Z
zhiru 已提交
34 35
//    static std::unique_ptr<Connection> connectionPtr(new Connection());
//    std::recursive_mutex mysql_mutex;
Z
zhiru 已提交
36 37 38 39 40 41
//
//    std::unique_ptr<Connection>& MySQLMetaImpl::getConnectionPtr() {
////        static std::recursive_mutex connectionMutex_;
//        std::lock_guard<std::recursive_mutex> lock(connectionMutex_);
//        return connectionPtr;
//    }
Z
update  
zhiru 已提交
42 43 44

    namespace {

Z
update  
zhiru 已提交
45 46 47
        Status HandleException(const std::string& desc, std::exception &e) {
            ENGINE_LOG_ERROR << desc << ": " << e.what();
            return Status::DBTransactionError(desc, e.what());
Z
update  
zhiru 已提交
48 49
        }

Z
update  
zhiru 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
        class MetricCollector {
        public:
            MetricCollector() {
                server::Metrics::GetInstance().MetaAccessTotalIncrement();
                start_time_ = METRICS_NOW_TIME;
            }

            ~MetricCollector() {
                auto end_time = METRICS_NOW_TIME;
                auto total_time = METRICS_MICROSECONDS(start_time_, end_time);
                server::Metrics::GetInstance().MetaAccessDurationSecondsHistogramObserve(total_time);
            }

        private:
            using TIME_POINT = std::chrono::system_clock::time_point;
            TIME_POINT start_time_;
        };

Z
update  
zhiru 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
    }

    Status MySQLMetaImpl::NextTableId(std::string &table_id) {
        std::stringstream ss;
        SimpleIDGenerator g;
        ss << g.GetNextIDNumber();
        table_id = ss.str();
        return Status::OK();
    }

    Status MySQLMetaImpl::NextFileId(std::string &file_id) {
        std::stringstream ss;
        SimpleIDGenerator g;
        ss << g.GetNextIDNumber();
        file_id = ss.str();
        return Status::OK();
    }

Z
update  
zhiru 已提交
86
    MySQLMetaImpl::MySQLMetaImpl(const DBMetaOptions &options_, const int& mode)
Z
update  
zhiru 已提交
87 88
            : options_(options_),
              mode_(mode) {
89
        Initialize();
Z
update  
zhiru 已提交
90 91 92
    }

    Status MySQLMetaImpl::Initialize() {
93

Z
zhiru 已提交
94
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
95

Z
update  
zhiru 已提交
96 97
        if (!boost::filesystem::is_directory(options_.path)) {
            auto ret = boost::filesystem::create_directory(options_.path);
98
            if (!ret) {
Z
update  
zhiru 已提交
99 100
                ENGINE_LOG_ERROR << "Failed to create db directory " << options_.path;
                return Status::DBTransactionError("Failed to create db directory", options_.path);
101 102
            }
        }
Z
update  
zhiru 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126

        std::string uri = options_.backend_uri;

        std::string dialectRegex = "(.*)";
        std::string usernameRegex = "(.*)";
        std::string passwordRegex = "(.*)";
        std::string hostRegex = "(.*)";
        std::string portRegex = "(.*)";
        std::string dbNameRegex = "(.*)";
        std::string uriRegexStr = dialectRegex + "\\:\\/\\/" +
                                  usernameRegex + "\\:" +
                                  passwordRegex + "\\@" +
                                  hostRegex + "\\:" +
                                  portRegex + "\\/" +
                                  dbNameRegex;
        std::regex uriRegex(uriRegexStr);
        std::smatch pieces_match;

        if (std::regex_match(uri, pieces_match, uriRegex)) {
            std::string dialect = pieces_match[1].str();
            std::transform(dialect.begin(), dialect.end(), dialect.begin(), ::tolower);
            if (dialect.find("mysql") == std::string::npos) {
                return Status::Error("URI's dialect is not MySQL");
            }
Z
zhiru 已提交
127 128 129
            std::string username = pieces_match[2].str();
            std::string password = pieces_match[3].str();
            std::string serverAddress = pieces_match[4].str();
Z
update  
zhiru 已提交
130 131 132 133
            unsigned int port = 0;
            if (!pieces_match[5].str().empty()) {
                port = std::stoi(pieces_match[5].str());
            }
Z
zhiru 已提交
134 135
            std::string dbName = pieces_match[6].str();
//            std::cout << dbName << " " << serverAddress << " " << username << " " << password << " " << port << std::endl;
136
//            connectionPtr->set_option(new MultiStatementsOption(true));
Z
zhiru 已提交
137
//            connectionPtr->set_option(new mysqlpp::ReconnectOption(true));
Z
zhiru 已提交
138 139
            int threadHint = std::thread::hardware_concurrency();
            int maxPoolSize = threadHint == 0 ? 8 : threadHint;
Z
update  
zhiru 已提交
140
            mysql_connection_pool_ = std::make_shared<MySQLConnectionPool>(dbName, username, password, serverAddress, port, maxPoolSize);
Z
zhiru 已提交
141
//            std::cout << "MySQL++ thread aware:" << std::to_string(connectionPtr->thread_aware()) << std::endl;
Z
update  
zhiru 已提交
142
            ENGINE_LOG_DEBUG << "MySQL connection pool: maximum pool size = " << std::to_string(maxPoolSize);
Z
update  
zhiru 已提交
143
            try {
144

Z
zhiru 已提交
145 146 147
                if (mode_ != Options::MODE::READ_ONLY) {
                    CleanUp();
                }
148 149

                {
Z
update  
zhiru 已提交
150
                    ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
update  
zhiru 已提交
151

Z
update  
zhiru 已提交
152 153 154 155
                    if (connectionPtr == nullptr) {
                        return Status::Error("Failed to connect to database server");
                    }

Z
update  
zhiru 已提交
156
//                    ENGINE_LOG_DEBUG << "MySQLMetaImpl::Initialize: connections in use = " << mysql_connection_pool_->getConnectionsInUse();
Z
zhiru 已提交
157 158 159
//                if (!connectionPtr->connect(dbName, serverAddress, username, password, port)) {
//                    return Status::Error("DB connection failed: ", connectionPtr->error());
//                }
160 161 162 163 164
                    if (!connectionPtr->thread_aware()) {
                        ENGINE_LOG_ERROR << "MySQL++ wasn't built with thread awareness! Can't run without it.";
                        return Status::Error("MySQL++ wasn't built with thread awareness! Can't run without it.");
                    }
                    Query InitializeQuery = connectionPtr->query();
Z
update  
zhiru 已提交
165

Z
zhiru 已提交
166 167 168 169 170
//                InitializeQuery << "SET max_allowed_packet=67108864;";
//                if (!InitializeQuery.exec()) {
//                    return Status::DBTransactionError("Initialization Error", InitializeQuery.error());
//                }

171 172
//                InitializeQuery << "DROP TABLE IF EXISTS Tables, TableFiles;";
                    InitializeQuery << "CREATE TABLE IF NOT EXISTS Tables (" <<
173 174
                                    "id BIGINT PRIMARY KEY AUTO_INCREMENT, " <<
                                    "table_id VARCHAR(255) UNIQUE NOT NULL, " <<
Z
update  
zhiru 已提交
175
                                    "state INT NOT NULL, " <<
176 177 178 179 180
                                    "dimension SMALLINT NOT NULL, " <<
                                    "created_on BIGINT NOT NULL, " <<
                                    "files_cnt BIGINT DEFAULT 0 NOT NULL, " <<
                                    "engine_type INT DEFAULT 1 NOT NULL, " <<
                                    "store_raw_data BOOL DEFAULT false NOT NULL);";
Z
update  
zhiru 已提交
181

Z
update  
zhiru 已提交
182
                    ENGINE_LOG_DEBUG << "MySQLMetaImpl::Initialize: " << InitializeQuery.str();
Z
update  
zhiru 已提交
183

184 185 186
                    if (!InitializeQuery.exec()) {
                        return Status::DBTransactionError("Initialization Error", InitializeQuery.error());
                    }
187

188 189 190 191 192 193 194 195 196 197
                    InitializeQuery << "CREATE TABLE IF NOT EXISTS TableFiles (" <<
                                    "id BIGINT PRIMARY KEY AUTO_INCREMENT, " <<
                                    "table_id VARCHAR(255) NOT NULL, " <<
                                    "engine_type INT DEFAULT 1 NOT NULL, " <<
                                    "file_id VARCHAR(255) NOT NULL, " <<
                                    "file_type INT DEFAULT 0 NOT NULL, " <<
                                    "size BIGINT DEFAULT 0 NOT NULL, " <<
                                    "updated_time BIGINT NOT NULL, " <<
                                    "created_on BIGINT NOT NULL, " <<
                                    "date INT DEFAULT -1 NOT NULL);";
Z
update  
zhiru 已提交
198

Z
update  
zhiru 已提交
199
                    ENGINE_LOG_DEBUG << "MySQLMetaImpl::Initialize: " << InitializeQuery.str();
Z
update  
zhiru 已提交
200

201 202 203 204
                    if (!InitializeQuery.exec()) {
                        return Status::DBTransactionError("Initialization Error", InitializeQuery.error());
                    }
                } //Scoped Connection
205

Z
zhiru 已提交
206 207 208 209
//                //Consume all results to avoid "Commands out of sync" error
//                while (InitializeQuery.more_results()) {
//                    InitializeQuery.store_next();
//                }
210 211 212 213 214 215 216 217 218 219 220
                return Status::OK();

//                if (InitializeQuery.exec()) {
//                    std::cout << "XXXXXXXXXXXXXXXXXXXXXXXXX" << std::endl;
//                    while (InitializeQuery.more_results()) {
//                        InitializeQuery.store_next();
//                    }
//                    return Status::OK();
//                } else {
//                    return Status::DBTransactionError("Initialization Error", InitializeQuery.error());
//                }
Z
update  
zhiru 已提交
221 222
            } catch (const BadQuery& er) {
                // Handle any query errors
Z
update  
zhiru 已提交
223
                ENGINE_LOG_ERROR << "QUERY ERROR DURING INITIALIZATION" << ": " << er.what();
224
                return Status::DBTransactionError("QUERY ERROR DURING INITIALIZATION", er.what());
Z
update  
zhiru 已提交
225 226
            } catch (const Exception& er) {
                // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
227
                ENGINE_LOG_ERROR << "GENERAL ERROR DURING INITIALIZATION" << ": " << er.what();
228
                return Status::DBTransactionError("GENERAL ERROR DURING INITIALIZATION", er.what());
Z
zhiru 已提交
229 230
            } catch (std::exception &e) {
                return HandleException("Encounter exception during initialization", e);
Z
update  
zhiru 已提交
231 232 233
            }
        }
        else {
Z
zhiru 已提交
234
            ENGINE_LOG_ERROR << "Wrong URI format. URI = " << uri;
Z
update  
zhiru 已提交
235 236 237 238 239 240 241
            return Status::Error("Wrong URI format");
        }
    }

// PXU TODO: Temp solution. Will fix later
    Status MySQLMetaImpl::DropPartitionsByDates(const std::string &table_id,
                                             const DatesT &dates) {
Z
zhiru 已提交
242

Z
zhiru 已提交
243
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
244

245
        if (dates.empty()) {
246 247 248 249 250 251 252 253 254 255
            return Status::OK();
        }

        TableSchema table_schema;
        table_schema.table_id_ = table_id;
        auto status = DescribeTable(table_schema);
        if (!status.ok()) {
            return status;
        }

Z
update  
zhiru 已提交
256
        try {
257

Z
update  
zhiru 已提交
258
            auto yesterday = GetDateWithDelta(-1);
259

Z
update  
zhiru 已提交
260 261 262 263 264
            for (auto &date : dates) {
                if (date >= yesterday) {
                    return Status::Error("Could not delete partitions within 2 days");
                }
            }
265 266 267

            std::stringstream dateListSS;
            for (auto &date : dates) {
268
                dateListSS << std::to_string(date) << ", ";
269 270 271 272
            }
            std::string dateListStr = dateListSS.str();
            dateListStr = dateListStr.substr(0, dateListStr.size() - 2); //remove the last ", "

273
            {
Z
update  
zhiru 已提交
274
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
275

Z
update  
zhiru 已提交
276 277 278 279
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
280 281
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DropPartitionsByDates connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
282 283
//                }

284 285 286 287 288 289 290
                Query dropPartitionsByDatesQuery = connectionPtr->query();

                dropPartitionsByDatesQuery << "UPDATE TableFiles " <<
                                            "SET file_type = " << std::to_string(TableFileSchema::TO_DELETE) << " " <<
                                            "WHERE table_id = " << quote << table_id << " AND " <<
                                            "date in (" << dateListStr << ");";

Z
update  
zhiru 已提交
291
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::DropPartitionsByDates: " << dropPartitionsByDatesQuery.str();
Z
update  
zhiru 已提交
292

293 294 295 296 297 298
                if (!dropPartitionsByDatesQuery.exec()) {
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN DROPPING PARTITIONS BY DATES";
                    return Status::DBTransactionError("QUERY ERROR WHEN DROPPING PARTITIONS BY DATES",
                                                      dropPartitionsByDatesQuery.error());
                }
            } //Scoped Connection
299 300
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
301
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DROPPING PARTITIONS BY DATES" << ": " << er.what();
302 303 304
            return Status::DBTransactionError("QUERY ERROR WHEN DROPPING PARTITIONS BY DATES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
305
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DROPPING PARTITIONS BY DATES" << ": " << er.what();
306 307
            return Status::DBTransactionError("GENERAL ERROR WHEN DROPPING PARTITIONS BY DATES", er.what());
        }
Z
update  
zhiru 已提交
308 309 310 311
        return Status::OK();
    }

    Status MySQLMetaImpl::CreateTable(TableSchema &table_schema) {
Z
zhiru 已提交
312

Z
zhiru 已提交
313
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
314

Z
update  
zhiru 已提交
315 316 317 318 319
//        server::Metrics::GetInstance().MetaAccessTotalIncrement();
        try {

            MetricCollector metric;

320
            {
Z
update  
zhiru 已提交
321
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
update  
zhiru 已提交
322

Z
update  
zhiru 已提交
323 324 325 326
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
327 328
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::CreateTable connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
329 330
//                }

331
                Query createTableQuery = connectionPtr->query();
Z
update  
zhiru 已提交
332
//                ENGINE_LOG_DEBUG << "Create Table in";
333 334 335 336 337
                if (table_schema.table_id_.empty()) {
                    NextTableId(table_schema.table_id_);
                } else {
                    createTableQuery << "SELECT state FROM Tables " <<
                                        "WHERE table_id = " << quote << table_schema.table_id_ << ";";
Z
zhiru 已提交
338
//                    ENGINE_LOG_DEBUG << "Create Table : " << createTableQuery.str();
Z
update  
zhiru 已提交
339

Z
update  
zhiru 已提交
340
                    ENGINE_LOG_DEBUG << "MySQLMetaImpl::CreateTable: " << createTableQuery.str();
Z
update  
zhiru 已提交
341

342
                    StoreQueryResult res = createTableQuery.store();
Z
update  
zhiru 已提交
343

344 345
                    if (res.num_rows() == 1) {
                        int state = res[0]["state"];
Z
update  
zhiru 已提交
346 347 348 349 350 351
                        if (TableSchema::TO_DELETE == state) {
                            return Status::Error("Table already exists and it is in delete state, please wait a second");
                        }
                        else {
                            return Status::OK();//table already exists, no error
                        }
352
                    }
353
                }
Z
zhiru 已提交
354
//                ENGINE_LOG_DEBUG << "Create Table start";
355

356 357 358
                table_schema.files_cnt_ = 0;
                table_schema.id_ = -1;
                table_schema.created_on_ = utils::GetMicroSecTimeStamp();
Z
update  
zhiru 已提交
359 360 361

//            auto start_time = METRICS_NOW_TIME;

362 363 364 365 366 367 368 369 370 371 372 373
                std::string id = "NULL"; //auto-increment
                std::string table_id = table_schema.table_id_;
                std::string state = std::to_string(table_schema.state_);
                std::string dimension = std::to_string(table_schema.dimension_);
                std::string created_on = std::to_string(table_schema.created_on_);
                std::string files_cnt = "0";
                std::string engine_type = std::to_string(table_schema.engine_type_);
                std::string store_raw_data = table_schema.store_raw_data_ ? "true" : "false";

                createTableQuery << "INSERT INTO Tables VALUES" <<
                                 "(" << id << ", " << quote << table_id << ", " << state << ", " << dimension << ", " <<
                                 created_on << ", " << files_cnt << ", " << engine_type << ", " << store_raw_data << ");";
Z
zhiru 已提交
374
//                ENGINE_LOG_DEBUG << "Create Table : " << createTableQuery.str();
Z
update  
zhiru 已提交
375

Z
update  
zhiru 已提交
376
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::CreateTable: " << createTableQuery.str();
Z
update  
zhiru 已提交
377

378 379
                if (SimpleResult res = createTableQuery.execute()) {
                    table_schema.id_ = res.insert_id(); //Might need to use SELECT LAST_INSERT_ID()?
Z
update  
zhiru 已提交
380
//                    std::cout << table_schema.id_ << std::endl;
381
                    //Consume all results to avoid "Commands out of sync" error
Z
update  
zhiru 已提交
382 383 384
//                while (createTableQuery.more_results()) {
//                    createTableQuery.store_next();
//                }
385 386 387 388 389
                } else {
                    ENGINE_LOG_ERROR << "Add Table Error";
                    return Status::DBTransactionError("Add Table Error", createTableQuery.error());
                }
            } //Scoped Connection
Z
update  
zhiru 已提交
390 391 392 393 394

//        auto end_time = METRICS_NOW_TIME;
//        auto total_time = METRICS_MICROSECONDS(start_time, end_time);
//        server::Metrics::GetInstance().MetaAccessDurationSecondsHistogramObserve(total_time);

S
starlord 已提交
395 396
            return utils::CreateTablePath(options_, table_schema.table_id_);

Z
update  
zhiru 已提交
397 398
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
399
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN ADDING TABLE" << ": " << er.what();
Z
update  
zhiru 已提交
400 401 402
            return Status::DBTransactionError("QUERY ERROR WHEN ADDING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
403
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN ADDING TABLE" << ": " << er.what();
Z
update  
zhiru 已提交
404
            return Status::DBTransactionError("GENERAL ERROR WHEN ADDING TABLE", er.what());
Z
zhiru 已提交
405 406
        } catch (std::exception &e) {
            return HandleException("Encounter exception when create table", e);
407
        }
Z
update  
zhiru 已提交
408 409 410 411

        return Status::OK();
    }

P
peng.xu 已提交
412 413 414 415 416
    Status MySQLMetaImpl::HasNonIndexFiles(const std::string& table_id, bool& has) {
        // TODO
        return Status::OK();
    }

Z
update  
zhiru 已提交
417
    Status MySQLMetaImpl::DeleteTable(const std::string& table_id) {
Z
zhiru 已提交
418

Z
zhiru 已提交
419
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
420

421
        try {
Z
update  
zhiru 已提交
422 423 424

            MetricCollector metric;

425
            {
Z
update  
zhiru 已提交
426
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
zhiru 已提交
427

Z
update  
zhiru 已提交
428 429 430 431
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
432 433
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DeleteTable connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
434 435
//                }

436 437
                //soft delete table
                Query deleteTableQuery = connectionPtr->query();
Z
update  
zhiru 已提交
438
//
439 440 441
                deleteTableQuery << "UPDATE Tables " <<
                                    "SET state = " << std::to_string(TableSchema::TO_DELETE) << " " <<
                                    "WHERE table_id = " << quote << table_id << ";";
Z
update  
zhiru 已提交
442

Z
update  
zhiru 已提交
443
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::DeleteTable: " << deleteTableQuery.str();
Z
update  
zhiru 已提交
444

445 446 447 448 449 450
                if (!deleteTableQuery.exec()) {
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN DELETING TABLE";
                    return Status::DBTransactionError("QUERY ERROR WHEN DELETING TABLE", deleteTableQuery.error());
                }

            } //Scoped Connection
Z
update  
zhiru 已提交
451

Z
update  
zhiru 已提交
452

Z
zhiru 已提交
453
            if (mode_ == Options::MODE::CLUSTER) {
Z
update  
zhiru 已提交
454 455
                DeleteTableFiles(table_id);
            }
Z
update  
zhiru 已提交
456

457 458
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
459
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DELETING TABLE" << ": " << er.what();
460 461 462
            return Status::DBTransactionError("QUERY ERROR WHEN DELETING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
463
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DELETING TABLE" << ": " << er.what();
464 465
            return Status::DBTransactionError("GENERAL ERROR WHEN DELETING TABLE", er.what());
        }
Z
update  
zhiru 已提交
466 467 468 469 470 471 472 473

        return Status::OK();
    }

    Status MySQLMetaImpl::DeleteTableFiles(const std::string& table_id) {
        try {
            MetricCollector metric;

474
            {
Z
update  
zhiru 已提交
475
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
update  
zhiru 已提交
476

Z
update  
zhiru 已提交
477 478 479 480
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
481 482
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DeleteTableFiles connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
483 484
//                }

485 486 487 488
                //soft delete table files
                Query deleteTableFilesQuery = connectionPtr->query();
                //
                deleteTableFilesQuery << "UPDATE TableFiles " <<
Z
update  
zhiru 已提交
489
                                      "SET file_type = " << std::to_string(TableFileSchema::TO_DELETE) << ", " <<
490
                                      "updated_time = " << std::to_string(utils::GetMicroSecTimeStamp()) << " " <<
Z
update  
zhiru 已提交
491
                                      "WHERE table_id = " << quote << table_id << " AND " <<
Z
update  
zhiru 已提交
492
                                      "file_type <> " << std::to_string(TableFileSchema::TO_DELETE) << ";";
493

Z
update  
zhiru 已提交
494
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::DeleteTableFiles: " << deleteTableFilesQuery.str();
Z
update  
zhiru 已提交
495

496 497 498 499 500
                if (!deleteTableFilesQuery.exec()) {
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN DELETING TABLE FILES";
                    return Status::DBTransactionError("QUERY ERROR WHEN DELETING TABLE", deleteTableFilesQuery.error());
                }
            } //Scoped Connection
Z
update  
zhiru 已提交
501 502
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
503
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DELETING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
504 505 506
            return Status::DBTransactionError("QUERY ERROR WHEN DELETING TABLE FILES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
507
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DELETING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
508 509 510 511
            return Status::DBTransactionError("GENERAL ERROR WHEN DELETING TABLE FILES", er.what());
        }

        return Status::OK();
Z
update  
zhiru 已提交
512 513 514
    }

    Status MySQLMetaImpl::DescribeTable(TableSchema &table_schema) {
Z
zhiru 已提交
515

Z
zhiru 已提交
516
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
517

518
        try {
Z
update  
zhiru 已提交
519 520

            MetricCollector metric;
521

522 523 524
            StoreQueryResult res;

            {
Z
update  
zhiru 已提交
525
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
zhiru 已提交
526

Z
update  
zhiru 已提交
527 528 529 530
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
531 532
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DescribeTable connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
533 534
//                }

535 536 537 538 539
                Query describeTableQuery = connectionPtr->query();
                describeTableQuery << "SELECT id, dimension, files_cnt, engine_type, store_raw_data " <<
                                      "FROM Tables " <<
                                      "WHERE table_id = " << quote << table_schema.table_id_ << " " <<
                                      "AND state <> " << std::to_string(TableSchema::TO_DELETE) << ";";
Z
update  
zhiru 已提交
540

Z
update  
zhiru 已提交
541
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::DescribeTable: " << describeTableQuery.str();
Z
update  
zhiru 已提交
542

543 544
                res = describeTableQuery.store();
            } //Scoped Connection
545 546 547 548 549 550 551 552 553 554 555 556

            if (res.num_rows() == 1) {
                const Row& resRow = res[0];

                table_schema.id_ = resRow["id"]; //implicit conversion

                table_schema.dimension_ = resRow["dimension"];

                table_schema.files_cnt_ = resRow["files_cnt"];

                table_schema.engine_type_ = resRow["engine_type"];

Z
update  
zhiru 已提交
557 558
                int store_raw_data = resRow["store_raw_data"];
                table_schema.store_raw_data_ = (store_raw_data == 1);
559 560 561 562 563 564 565
            }
            else {
                return Status::NotFound("Table " + table_schema.table_id_ + " not found");
            }

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
566
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DESCRIBING TABLE" << ": " << er.what();
567 568 569
            return Status::DBTransactionError("QUERY ERROR WHEN DESCRIBING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
570
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DESCRIBING TABLE" << ": " << er.what();
571 572
            return Status::DBTransactionError("GENERAL ERROR WHEN DESCRIBING TABLE", er.what());
        }
Z
update  
zhiru 已提交
573 574 575 576 577

        return Status::OK();
    }

    Status MySQLMetaImpl::HasTable(const std::string &table_id, bool &has_or_not) {
Z
zhiru 已提交
578

Z
zhiru 已提交
579
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
580

581
        try {
Z
update  
zhiru 已提交
582 583 584

            MetricCollector metric;

585 586 587
            StoreQueryResult res;

            {
Z
update  
zhiru 已提交
588
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
589

Z
update  
zhiru 已提交
590 591 592 593
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
594 595
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::HasTable connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
596 597
//                }

598 599 600 601 602 603 604
                Query hasTableQuery = connectionPtr->query();
                //since table_id is a unique column we just need to check whether it exists or not
                hasTableQuery << "SELECT EXISTS " <<
                              "(SELECT 1 FROM Tables " <<
                              "WHERE table_id = " << quote << table_id << " " <<
                              "AND state <> " << std::to_string(TableSchema::TO_DELETE) << ") " <<
                              "AS " << quote << "check" << ";";
Z
update  
zhiru 已提交
605

Z
update  
zhiru 已提交
606
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::HasTable: " << hasTableQuery.str();
Z
update  
zhiru 已提交
607

608 609
                res = hasTableQuery.store();
            } //Scoped Connection
610 611 612 613 614 615

            int check = res[0]["check"];
            has_or_not = (check == 1);

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
616
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN CHECKING IF TABLE EXISTS" << ": " << er.what();
617 618 619
            return Status::DBTransactionError("QUERY ERROR WHEN CHECKING IF TABLE EXISTS", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
620
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN CHECKING IF TABLE EXISTS" << ": " << er.what();
621 622 623
            return Status::DBTransactionError("GENERAL ERROR WHEN CHECKING IF TABLE EXISTS", er.what());
        }

Z
update  
zhiru 已提交
624 625 626 627
        return Status::OK();
    }

    Status MySQLMetaImpl::AllTables(std::vector<TableSchema>& table_schema_array) {
Z
zhiru 已提交
628

Z
zhiru 已提交
629
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
630

631
        try {
Z
update  
zhiru 已提交
632 633

            MetricCollector metric;
634

635 636 637
            StoreQueryResult res;

            {
Z
update  
zhiru 已提交
638
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
zhiru 已提交
639

Z
update  
zhiru 已提交
640 641 642 643
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
644 645
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::AllTables connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
646 647
//                }

648 649 650 651
                Query allTablesQuery = connectionPtr->query();
                allTablesQuery << "SELECT id, table_id, dimension, files_cnt, engine_type, store_raw_data " <<
                               "FROM Tables " <<
                               "WHERE state <> " << std::to_string(TableSchema::TO_DELETE) << ";";
Z
update  
zhiru 已提交
652

Z
update  
zhiru 已提交
653
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::AllTables: " << allTablesQuery.str();
Z
update  
zhiru 已提交
654

655 656
                res = allTablesQuery.store();
            } //Scoped Connection
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672

            for (auto& resRow : res) {
                TableSchema table_schema;

                table_schema.id_ = resRow["id"]; //implicit conversion

                std::string table_id;
                resRow["table_id"].to_string(table_id);
                table_schema.table_id_ = table_id;

                table_schema.dimension_ = resRow["dimension"];

                table_schema.files_cnt_ = resRow["files_cnt"];

                table_schema.engine_type_ = resRow["engine_type"];

Z
update  
zhiru 已提交
673 674
                int store_raw_data = resRow["store_raw_data"];
                table_schema.store_raw_data_ = (store_raw_data == 1);
675 676 677 678 679

                table_schema_array.emplace_back(table_schema);
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
680
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DESCRIBING ALL TABLES" << ": " << er.what();
681 682 683
            return Status::DBTransactionError("QUERY ERROR WHEN DESCRIBING ALL TABLES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
684
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DESCRIBING ALL TABLES" << ": " << er.what();
685 686
            return Status::DBTransactionError("GENERAL ERROR WHEN DESCRIBING ALL TABLES", er.what());
        }
Z
update  
zhiru 已提交
687 688 689 690 691

        return Status::OK();
    }

    Status MySQLMetaImpl::CreateTableFile(TableFileSchema &file_schema) {
Z
zhiru 已提交
692

Z
zhiru 已提交
693
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
694

695 696 697 698 699 700 701 702 703 704
        if (file_schema.date_ == EmptyDate) {
            file_schema.date_ = Meta::GetDate();
        }
        TableSchema table_schema;
        table_schema.table_id_ = file_schema.table_id_;
        auto status = DescribeTable(table_schema);
        if (!status.ok()) {
            return status;
        }

Z
update  
zhiru 已提交
705
        try {
706

Z
update  
zhiru 已提交
707
            MetricCollector metric;
708

Z
update  
zhiru 已提交
709 710 711 712 713 714 715
            NextFileId(file_schema.file_id_);
            file_schema.file_type_ = TableFileSchema::NEW;
            file_schema.dimension_ = table_schema.dimension_;
            file_schema.size_ = 0;
            file_schema.created_on_ = utils::GetMicroSecTimeStamp();
            file_schema.updated_time_ = file_schema.created_on_;
            file_schema.engine_type_ = table_schema.engine_type_;
S
starlord 已提交
716
            utils::GetTableFilePath(options_, file_schema);
717

Z
update  
zhiru 已提交
718 719 720 721 722 723 724 725 726
            std::string id = "NULL"; //auto-increment
            std::string table_id = file_schema.table_id_;
            std::string engine_type = std::to_string(file_schema.engine_type_);
            std::string file_id = file_schema.file_id_;
            std::string file_type = std::to_string(file_schema.file_type_);
            std::string size = std::to_string(file_schema.size_);
            std::string updated_time = std::to_string(file_schema.updated_time_);
            std::string created_on = std::to_string(file_schema.created_on_);
            std::string date = std::to_string(file_schema.date_);
727

728
            {
Z
update  
zhiru 已提交
729
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
zhiru 已提交
730

Z
update  
zhiru 已提交
731 732 733 734
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
735 736
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::CreateTableFile connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
737 738
//                }

739
                Query createTableFileQuery = connectionPtr->query();
740

741 742 743 744 745
                createTableFileQuery << "INSERT INTO TableFiles VALUES" <<
                                     "(" << id << ", " << quote << table_id << ", " << engine_type << ", " <<
                                     quote << file_id << ", " << file_type << ", " << size << ", " <<
                                     updated_time << ", " << created_on << ", " << date << ");";

Z
update  
zhiru 已提交
746
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::CreateTableFile: " << createTableFileQuery.str();
Z
update  
zhiru 已提交
747

748 749 750 751
                if (SimpleResult res = createTableFileQuery.execute()) {
                    file_schema.id_ = res.insert_id(); //Might need to use SELECT LAST_INSERT_ID()?

                    //Consume all results to avoid "Commands out of sync" error
Z
update  
zhiru 已提交
752 753 754
//                while (createTableFileQuery.more_results()) {
//                    createTableFileQuery.store_next();
//                }
755 756 757 758 759
                } else {
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN ADDING TABLE FILE";
                    return Status::DBTransactionError("Add file Error", createTableFileQuery.error());
                }
            } // Scoped Connection
760

S
starlord 已提交
761
            return utils::CreateTableFilePath(options_, file_schema);
Z
update  
zhiru 已提交
762 763 764

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
765
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN ADDING TABLE FILE" << ": " << er.what();
Z
update  
zhiru 已提交
766 767 768
            return Status::DBTransactionError("QUERY ERROR WHEN ADDING TABLE FILE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
769
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN ADDING TABLE FILE" << ": " << er.what();
Z
update  
zhiru 已提交
770
            return Status::DBTransactionError("GENERAL ERROR WHEN ADDING TABLE FILE", er.what());
Z
zhiru 已提交
771 772
        } catch (std::exception& ex) {
            return HandleException("Encounter exception when create table file", ex);
773
        }
Z
update  
zhiru 已提交
774 775 776 777 778

        return Status::OK();
    }

    Status MySQLMetaImpl::FilesToIndex(TableFilesSchema &files) {
Z
zhiru 已提交
779

Z
zhiru 已提交
780
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
781

782 783 784
        files.clear();

        try {
Z
update  
zhiru 已提交
785 786

            MetricCollector metric;
787

788 789 790
            StoreQueryResult res;

            {
Z
update  
zhiru 已提交
791
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
zhiru 已提交
792

Z
update  
zhiru 已提交
793 794 795 796
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
797 798
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::FilesToIndex connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
799 800
//                }

801 802 803 804
                Query filesToIndexQuery = connectionPtr->query();
                filesToIndexQuery << "SELECT id, table_id, engine_type, file_id, file_type, size, date " <<
                                     "FROM TableFiles " <<
                                     "WHERE file_type = " << std::to_string(TableFileSchema::TO_INDEX) << ";";
Z
update  
zhiru 已提交
805

Z
update  
zhiru 已提交
806
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::FilesToIndex: " << filesToIndexQuery.str();
Z
update  
zhiru 已提交
807

808 809
                res = filesToIndexQuery.store();
            } //Scoped Connection
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845

            std::map<std::string, TableSchema> groups;
            TableFileSchema table_file;
            for (auto& resRow : res) {

                table_file.id_ = resRow["id"]; //implicit conversion

                std::string table_id;
                resRow["table_id"].to_string(table_id);
                table_file.table_id_ = table_id;

                table_file.engine_type_ = resRow["engine_type"];

                std::string file_id;
                resRow["file_id"].to_string(file_id);
                table_file.file_id_ = file_id;

                table_file.file_type_ = resRow["file_type"];

                table_file.size_ = resRow["size"];

                table_file.date_ = resRow["date"];

                auto groupItr = groups.find(table_file.table_id_);
                if (groupItr == groups.end()) {
                    TableSchema table_schema;
                    table_schema.table_id_ = table_file.table_id_;
                    auto status = DescribeTable(table_schema);
                    if (!status.ok()) {
                        return status;
                    }
                    groups[table_file.table_id_] = table_schema;
//                    std::cout << table_schema.dimension_ << std::endl;
                }
                table_file.dimension_ = groups[table_file.table_id_].dimension_;

S
starlord 已提交
846
                utils::GetTableFilePath(options_, table_file);
847 848 849 850 851

                files.push_back(table_file);
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
852
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN FINDING TABLE FILES TO INDEX" << ": " << er.what();
853 854 855
            return Status::DBTransactionError("QUERY ERROR WHEN FINDING TABLE FILES TO INDEX", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
856
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN FINDING TABLE FILES TO INDEX" << ": " << er.what();
857 858
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO INDEX", er.what());
        }
Z
update  
zhiru 已提交
859 860 861 862 863 864 865

        return Status::OK();
    }

    Status MySQLMetaImpl::FilesToSearch(const std::string &table_id,
                                     const DatesT &partition,
                                     DatePartionedTableFilesSchema &files) {
Z
zhiru 已提交
866

Z
zhiru 已提交
867
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
868

869 870 871
        files.clear();

        try {
Z
update  
zhiru 已提交
872 873

            MetricCollector metric;
874 875 876

            StoreQueryResult res;

877
            {
Z
update  
zhiru 已提交
878
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
879

Z
update  
zhiru 已提交
880 881 882
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }
Z
update  
zhiru 已提交
883 884
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::FilesToSearch connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
885 886
//                }

887
                if (partition.empty()) {
888

889 890 891 892 893 894 895
                    Query filesToSearchQuery = connectionPtr->query();
                    filesToSearchQuery << "SELECT id, table_id, engine_type, file_id, file_type, size, date " <<
                                       "FROM TableFiles " <<
                                       "WHERE table_id = " << quote << table_id << " AND " <<
                                       "(file_type = " << std::to_string(TableFileSchema::RAW) << " OR " <<
                                       "file_type = " << std::to_string(TableFileSchema::TO_INDEX) << " OR " <<
                                       "file_type = " << std::to_string(TableFileSchema::INDEX) << ");";
Z
update  
zhiru 已提交
896

Z
update  
zhiru 已提交
897
                    ENGINE_LOG_DEBUG << "MySQLMetaImpl::FilesToSearch: " << filesToSearchQuery.str();
Z
update  
zhiru 已提交
898

899
                    res = filesToSearchQuery.store();
900

901
                } else {
902

903
                    Query filesToSearchQuery = connectionPtr->query();
904

905 906 907 908 909 910 911 912 913
                    std::stringstream partitionListSS;
                    for (auto &date : partition) {
                        partitionListSS << std::to_string(date) << ", ";
                    }
                    std::string partitionListStr = partitionListSS.str();
                    partitionListStr = partitionListStr.substr(0, partitionListStr.size() - 2); //remove the last ", "

                    filesToSearchQuery << "SELECT id, table_id, engine_type, file_id, file_type, size, date " <<
                                       "FROM TableFiles " <<
Z
update  
zhiru 已提交
914 915 916 917 918
                                       "WHERE table_id = " << quote << table_id << " AND " <<
                                       "date IN (" << partitionListStr << ") AND " <<
                                       "(file_type = " << std::to_string(TableFileSchema::RAW) << " OR " <<
                                       "file_type = " << std::to_string(TableFileSchema::TO_INDEX) << " OR " <<
                                       "file_type = " << std::to_string(TableFileSchema::INDEX) << ");";
Z
update  
zhiru 已提交
919

Z
update  
zhiru 已提交
920
                    ENGINE_LOG_DEBUG << "MySQLMetaImpl::FilesToSearch: " << filesToSearchQuery.str();
Z
update  
zhiru 已提交
921

922
                    res = filesToSearchQuery.store();
923

924 925
                }
            } //Scoped Connection
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956

            TableSchema table_schema;
            table_schema.table_id_ = table_id;
            auto status = DescribeTable(table_schema);
            if (!status.ok()) {
                return status;
            }

            TableFileSchema table_file;
            for (auto& resRow : res) {

                table_file.id_ = resRow["id"]; //implicit conversion

                std::string table_id_str;
                resRow["table_id"].to_string(table_id_str);
                table_file.table_id_ = table_id_str;

                table_file.engine_type_ = resRow["engine_type"];

                std::string file_id;
                resRow["file_id"].to_string(file_id);
                table_file.file_id_ = file_id;

                table_file.file_type_ = resRow["file_type"];

                table_file.size_ = resRow["size"];

                table_file.date_ = resRow["date"];

                table_file.dimension_ = table_schema.dimension_;

S
starlord 已提交
957
                utils::GetTableFilePath(options_, table_file);
958 959 960 961 962 963 964 965 966 967

                auto dateItr = files.find(table_file.date_);
                if (dateItr == files.end()) {
                    files[table_file.date_] = TableFilesSchema();
                }

                files[table_file.date_].push_back(table_file);
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
968
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN FINDING TABLE FILES TO SEARCH" << ": " << er.what();
969 970 971
            return Status::DBTransactionError("QUERY ERROR WHEN FINDING TABLE FILES TO SEARCH", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
972
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN FINDING TABLE FILES TO SEARCH" << ": " << er.what();
973 974
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO SEARCH", er.what());
        }
Z
update  
zhiru 已提交
975 976 977 978 979 980

        return Status::OK();
    }

    Status MySQLMetaImpl::FilesToMerge(const std::string &table_id,
                                    DatePartionedTableFilesSchema &files) {
Z
zhiru 已提交
981

Z
zhiru 已提交
982
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
983

984 985 986
        files.clear();

        try {
Z
update  
zhiru 已提交
987
            MetricCollector metric;
988

989
            StoreQueryResult res;
Z
zhiru 已提交
990

991
            {
Z
update  
zhiru 已提交
992
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
993

Z
update  
zhiru 已提交
994 995 996 997
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
998 999
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::FilesToMerge connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
1000 1001
//                }

1002 1003 1004 1005 1006 1007
                Query filesToMergeQuery = connectionPtr->query();
                filesToMergeQuery << "SELECT id, table_id, file_id, file_type, size, date " <<
                                  "FROM TableFiles " <<
                                  "WHERE table_id = " << quote << table_id << " AND " <<
                                  "file_type = " << std::to_string(TableFileSchema::RAW) << " " <<
                                  "ORDER BY size DESC" << ";";
Z
update  
zhiru 已提交
1008

Z
update  
zhiru 已提交
1009
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::FilesToMerge: " << filesToMergeQuery.str();
Z
update  
zhiru 已提交
1010

1011 1012
                res = filesToMergeQuery.store();
            } //Scoped Connection
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042

            TableSchema table_schema;
            table_schema.table_id_ = table_id;
            auto status = DescribeTable(table_schema);

            if (!status.ok()) {
                return status;
            }

            TableFileSchema table_file;
            for (auto& resRow : res) {

                table_file.id_ = resRow["id"]; //implicit conversion

                std::string table_id_str;
                resRow["table_id"].to_string(table_id_str);
                table_file.table_id_ = table_id_str;

                std::string file_id;
                resRow["file_id"].to_string(file_id);
                table_file.file_id_ = file_id;

                table_file.file_type_ = resRow["file_type"];

                table_file.size_ = resRow["size"];

                table_file.date_ = resRow["date"];

                table_file.dimension_ = table_schema.dimension_;

S
starlord 已提交
1043
                utils::GetTableFilePath(options_, table_file);
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054

                auto dateItr = files.find(table_file.date_);
                if (dateItr == files.end()) {
                    files[table_file.date_] = TableFilesSchema();
                }

                files[table_file.date_].push_back(table_file);
            }

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1055
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN FINDING TABLE FILES TO MERGE" << ": " << er.what();
1056 1057 1058
            return Status::DBTransactionError("QUERY ERROR WHEN FINDING TABLE FILES TO MERGE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1059
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN FINDING TABLE FILES TO MERGE" << ": " << er.what();
1060 1061
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO MERGE", er.what());
        }
Z
update  
zhiru 已提交
1062 1063 1064 1065

        return Status::OK();
    }

Z
update  
zhiru 已提交
1066 1067 1068
    Status MySQLMetaImpl::GetTableFiles(const std::string& table_id,
                                        const std::vector<size_t>& ids,
                                        TableFilesSchema& table_files) {
Z
update  
zhiru 已提交
1069

Z
zhiru 已提交
1070
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
1071

Z
fix  
zhiru 已提交
1072 1073 1074 1075
        if (ids.empty()) {
            return Status::OK();
        }

Z
update  
zhiru 已提交
1076 1077 1078 1079 1080 1081 1082
        std::stringstream idSS;
        for (auto& id : ids) {
            idSS << "id = " << std::to_string(id) << " OR ";
        }
        std::string idStr = idSS.str();
        idStr = idStr.substr(0, idStr.size() - 4); //remove the last " OR "

1083 1084
        try {

1085 1086 1087
            StoreQueryResult res;

            {
Z
update  
zhiru 已提交
1088
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
zhiru 已提交
1089

Z
update  
zhiru 已提交
1090 1091 1092 1093
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1094 1095
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::GetTableFiles connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
1096 1097
//                }

1098
                Query getTableFileQuery = connectionPtr->query();
Z
update  
zhiru 已提交
1099 1100 1101 1102
                getTableFileQuery << "SELECT id, engine_type, file_id, file_type, size, date " <<
                                      "FROM TableFiles " <<
                                      "WHERE table_id = " << quote << table_id << " AND " <<
                                      "(" << idStr << ");";
Z
update  
zhiru 已提交
1103

Z
update  
zhiru 已提交
1104
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::GetTableFiles: " << getTableFileQuery.str();
Z
update  
zhiru 已提交
1105

1106 1107
                res = getTableFileQuery.store();
            } //Scoped Connection
1108

Z
update  
zhiru 已提交
1109 1110 1111 1112 1113 1114
            TableSchema table_schema;
            table_schema.table_id_ = table_id;
            auto status = DescribeTable(table_schema);
            if (!status.ok()) {
                return status;
            }
1115

Z
update  
zhiru 已提交
1116 1117 1118
            for (auto& resRow : res) {

                TableFileSchema file_schema;
1119

Z
update  
zhiru 已提交
1120 1121
                file_schema.id_ = resRow["id"];

1122 1123
                file_schema.table_id_ = table_id;

Z
update  
zhiru 已提交
1124 1125
                file_schema.engine_type_ = resRow["engine_type"];

1126 1127 1128 1129 1130 1131 1132 1133 1134
                std::string file_id;
                resRow["file_id"].to_string(file_id);
                file_schema.file_id_ = file_id;

                file_schema.file_type_ = resRow["file_type"];

                file_schema.size_ = resRow["size"];

                file_schema.date_ = resRow["date"];
Z
update  
zhiru 已提交
1135 1136 1137

                file_schema.dimension_ = table_schema.dimension_;

S
starlord 已提交
1138
                utils::GetTableFilePath(options_, file_schema);
Z
update  
zhiru 已提交
1139 1140

                table_files.emplace_back(file_schema);
1141 1142 1143
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1144
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN RETRIEVING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
1145
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING TABLE FILES", er.what());
1146 1147
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1148
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN RETRIEVING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
1149
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING TABLE FILES", er.what());
1150
        }
Z
update  
zhiru 已提交
1151 1152 1153 1154 1155 1156

        return Status::OK();
    }

// PXU TODO: Support Swap
    Status MySQLMetaImpl::Archive() {
Z
zhiru 已提交
1157

Z
zhiru 已提交
1158
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
1159

1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
        auto &criterias = options_.archive_conf.GetCriterias();
        if (criterias.empty()) {
            return Status::OK();
        }

        for (auto& kv : criterias) {
            auto &criteria = kv.first;
            auto &limit = kv.second;
            if (criteria == "days") {
                size_t usecs = limit * D_SEC * US_PS;
                long now = utils::GetMicroSecTimeStamp();
Z
zhiru 已提交
1171

1172 1173
                try {

Z
update  
zhiru 已提交
1174
                    ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
zhiru 已提交
1175

Z
update  
zhiru 已提交
1176 1177 1178 1179
                    if (connectionPtr == nullptr) {
                        return Status::Error("Failed to connect to database server");
                    }

Z
update  
zhiru 已提交
1180 1181
//                    if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                        ENGINE_LOG_WARNING << "MySQLMetaImpl::Archive connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
1182 1183
//                    }

1184
                    Query archiveQuery = connectionPtr->query();
1185
                    archiveQuery << "UPDATE TableFiles " <<
1186 1187 1188
                                    "SET file_type = " << std::to_string(TableFileSchema::TO_DELETE) << " " <<
                                    "WHERE created_on < " << std::to_string(now - usecs) << " AND " <<
                                    "file_type <> " << std::to_string(TableFileSchema::TO_DELETE) << ";";
Z
update  
zhiru 已提交
1189

Z
update  
zhiru 已提交
1190
                    ENGINE_LOG_DEBUG << "MySQLMetaImpl::Archive: " << archiveQuery.str();
Z
update  
zhiru 已提交
1191

1192 1193 1194 1195 1196 1197
                    if (!archiveQuery.exec()) {
                        return Status::DBTransactionError("QUERY ERROR DURING ARCHIVE", archiveQuery.error());
                    }

                } catch (const BadQuery& er) {
                    // Handle any query errors
Z
update  
zhiru 已提交
1198
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN DURING ARCHIVE" << ": " << er.what();
1199 1200 1201
                    return Status::DBTransactionError("QUERY ERROR WHEN DURING ARCHIVE", er.what());
                } catch (const Exception& er) {
                    // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1202
                    ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DURING ARCHIVE" << ": " << er.what();
1203 1204 1205 1206 1207 1208 1209
                    return Status::DBTransactionError("GENERAL ERROR WHEN DURING ARCHIVE", er.what());
                }
            }
            if (criteria == "disk") {
                uint64_t sum = 0;
                Size(sum);

Z
update  
zhiru 已提交
1210
                auto to_delete = (sum - limit * G);
1211 1212 1213
                DiscardFiles(to_delete);
            }
        }
Z
update  
zhiru 已提交
1214 1215 1216 1217 1218

        return Status::OK();
    }

    Status MySQLMetaImpl::Size(uint64_t &result) {
Z
zhiru 已提交
1219

Z
zhiru 已提交
1220
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
1221

1222 1223 1224
        result = 0;
        try {

1225 1226 1227
            StoreQueryResult res;

            {
Z
update  
zhiru 已提交
1228
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
zhiru 已提交
1229

Z
update  
zhiru 已提交
1230 1231 1232 1233
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1234 1235
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::Size connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
1236 1237
//                }

1238
                Query getSizeQuery = connectionPtr->query();
Z
update  
zhiru 已提交
1239
                getSizeQuery << "SELECT IFNULL(SUM(size),0) AS sum " <<
1240 1241
                             "FROM TableFiles " <<
                             "WHERE file_type <> " << std::to_string(TableFileSchema::TO_DELETE) << ";";
Z
update  
zhiru 已提交
1242

Z
update  
zhiru 已提交
1243
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::Size: " << getSizeQuery.str();
Z
update  
zhiru 已提交
1244

1245 1246
                res = getSizeQuery.store();
            } //Scoped Connection
1247

Z
zhiru 已提交
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259
//            if (!res) {
////                std::cout << "result is NULL" << std::endl;
//                return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING SIZE", getSizeQuery.error());
//            }
            if (res.empty()) {
                result = 0;
//                std::cout << "result = 0" << std::endl;
            }
            else {
                result = res[0]["sum"];
//                std::cout << "result = " << std::to_string(result) << std::endl;
            }
1260 1261 1262

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1263
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN RETRIEVING SIZE" << ": " << er.what();
1264 1265 1266
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING SIZE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1267
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN RETRIEVING SIZE" << ": " << er.what();
1268 1269
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING SIZE", er.what());
        }
Z
update  
zhiru 已提交
1270 1271 1272 1273

        return Status::OK();
    }

Z
zhiru 已提交
1274 1275
    Status MySQLMetaImpl::DiscardFiles(long long to_discard_size) {

Z
zhiru 已提交
1276
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
1277

1278 1279 1280 1281
        if (to_discard_size <= 0) {
//            std::cout << "in" << std::endl;
            return Status::OK();
        }
Z
update  
zhiru 已提交
1282 1283
        ENGINE_LOG_DEBUG << "About to discard size=" << to_discard_size;

1284 1285
        try {

Z
update  
zhiru 已提交
1286 1287
            MetricCollector metric;

1288 1289 1290
            bool status;

            {
Z
update  
zhiru 已提交
1291
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
zhiru 已提交
1292

Z
update  
zhiru 已提交
1293 1294 1295 1296
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1297 1298
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DiscardFiles connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
1299 1300
//                }

1301 1302 1303 1304 1305 1306
                Query discardFilesQuery = connectionPtr->query();
                discardFilesQuery << "SELECT id, size " <<
                                  "FROM TableFiles " <<
                                  "WHERE file_type <> " << std::to_string(TableFileSchema::TO_DELETE) << " " <<
                                  "ORDER BY id ASC " <<
                                  "LIMIT 10;";
Z
update  
zhiru 已提交
1307

Z
update  
zhiru 已提交
1308
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::DiscardFiles: " << discardFilesQuery.str();
Z
update  
zhiru 已提交
1309 1310

                //            std::cout << discardFilesQuery.str() << std::endl;
1311
                StoreQueryResult res = discardFilesQuery.store();
1312

1313 1314 1315
                if (res.num_rows() == 0) {
                    return Status::OK();
                }
1316

1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
                TableFileSchema table_file;
                std::stringstream idsToDiscardSS;
                for (auto &resRow : res) {
                    if (to_discard_size <= 0) {
                        break;
                    }
                    table_file.id_ = resRow["id"];
                    table_file.size_ = resRow["size"];
                    idsToDiscardSS << "id = " << std::to_string(table_file.id_) << " OR ";
                    ENGINE_LOG_DEBUG << "Discard table_file.id=" << table_file.file_id_
                                     << " table_file.size=" << table_file.size_;
                    to_discard_size -= table_file.size_;
1329 1330
                }

1331 1332
                std::string idsToDiscardStr = idsToDiscardSS.str();
                idsToDiscardStr = idsToDiscardStr.substr(0, idsToDiscardStr.size() - 4); //remove the last " OR "
1333

1334 1335 1336 1337
                discardFilesQuery << "UPDATE TableFiles " <<
                                  "SET file_type = " << std::to_string(TableFileSchema::TO_DELETE) << ", " <<
                                  "updated_time = " << std::to_string(utils::GetMicroSecTimeStamp()) << " " <<
                                  "WHERE " << idsToDiscardStr << ";";
1338

Z
update  
zhiru 已提交
1339
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::DiscardFiles: " << discardFilesQuery.str();
Z
update  
zhiru 已提交
1340

1341 1342 1343 1344 1345 1346 1347 1348
                status = discardFilesQuery.exec();
                if (!status) {
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN DISCARDING FILES";
                    return Status::DBTransactionError("QUERY ERROR WHEN DISCARDING FILES", discardFilesQuery.error());
                }
            } //Scoped Connection

            return DiscardFiles(to_discard_size);
1349 1350 1351

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1352
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DISCARDING FILES" << ": " << er.what();
1353 1354 1355
            return Status::DBTransactionError("QUERY ERROR WHEN DISCARDING FILES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1356
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DISCARDING FILES" << ": " << er.what();
1357 1358
            return Status::DBTransactionError("GENERAL ERROR WHEN DISCARDING FILES", er.what());
        }
Z
update  
zhiru 已提交
1359 1360
    }

1361
    //ZR: this function assumes all fields in file_schema have value
Z
update  
zhiru 已提交
1362
    Status MySQLMetaImpl::UpdateTableFile(TableFileSchema &file_schema) {
Z
zhiru 已提交
1363

Z
zhiru 已提交
1364
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
1365

1366 1367
        file_schema.updated_time_ = utils::GetMicroSecTimeStamp();
        try {
Z
update  
zhiru 已提交
1368 1369

            MetricCollector metric;
1370

1371
            {
Z
update  
zhiru 已提交
1372
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
zhiru 已提交
1373

Z
update  
zhiru 已提交
1374 1375 1376 1377
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1378 1379
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::UpdateTableFile connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
1380 1381
//                }

1382
                Query updateTableFileQuery = connectionPtr->query();
1383

1384 1385 1386 1387
                //if the table has been deleted, just mark the table file as TO_DELETE
                //clean thread will delete the file later
                updateTableFileQuery << "SELECT state FROM Tables " <<
                                     "WHERE table_id = " << quote << file_schema.table_id_ << ";";
Z
update  
zhiru 已提交
1388

Z
update  
zhiru 已提交
1389
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::UpdateTableFile: " << updateTableFileQuery.str();
Z
update  
zhiru 已提交
1390

1391 1392 1393 1394 1395 1396 1397 1398
                StoreQueryResult res = updateTableFileQuery.store();

                if (res.num_rows() == 1) {
                    int state = res[0]["state"];
                    if (state == TableSchema::TO_DELETE) {
                        file_schema.file_type_ = TableFileSchema::TO_DELETE;
                    }
                } else {
Z
update  
zhiru 已提交
1399 1400 1401
                    file_schema.file_type_ = TableFileSchema::TO_DELETE;
                }

1402 1403 1404 1405 1406 1407 1408 1409 1410
                std::string id = std::to_string(file_schema.id_);
                std::string table_id = file_schema.table_id_;
                std::string engine_type = std::to_string(file_schema.engine_type_);
                std::string file_id = file_schema.file_id_;
                std::string file_type = std::to_string(file_schema.file_type_);
                std::string size = std::to_string(file_schema.size_);
                std::string updated_time = std::to_string(file_schema.updated_time_);
                std::string created_on = std::to_string(file_schema.created_on_);
                std::string date = std::to_string(file_schema.date_);
1411

1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
                updateTableFileQuery << "UPDATE TableFiles " <<
                                     "SET table_id = " << quote << table_id << ", " <<
                                     "engine_type = " << engine_type << ", " <<
                                     "file_id = " << quote << file_id << ", " <<
                                     "file_type = " << file_type << ", " <<
                                     "size = " << size << ", " <<
                                     "updated_time = " << updated_time << ", " <<
                                     "created_on = " << created_on << ", " <<
                                     "date = " << date << " " <<
                                     "WHERE id = " << id << ";";
1422

Z
update  
zhiru 已提交
1423
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::UpdateTableFile: " << updateTableFileQuery.str();
Z
update  
zhiru 已提交
1424 1425

                //            std::cout << updateTableFileQuery.str() << std::endl;
1426

1427 1428 1429 1430 1431 1432 1433
                if (!updateTableFileQuery.exec()) {
                    ENGINE_LOG_DEBUG << "table_id= " << file_schema.table_id_ << " file_id=" << file_schema.file_id_;
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN UPDATING TABLE FILE";
                    return Status::DBTransactionError("QUERY ERROR WHEN UPDATING TABLE FILE",
                                                      updateTableFileQuery.error());
                }
            } //Scoped Connection
1434 1435 1436 1437

        } catch (const BadQuery& er) {
            // Handle any query errors
            ENGINE_LOG_DEBUG << "table_id= " << file_schema.table_id_ << " file_id=" << file_schema.file_id_;
Z
update  
zhiru 已提交
1438
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN UPDATING TABLE FILE" << ": " << er.what();
1439 1440 1441 1442
            return Status::DBTransactionError("QUERY ERROR WHEN UPDATING TABLE FILE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            ENGINE_LOG_DEBUG << "table_id= " << file_schema.table_id_ << " file_id=" << file_schema.file_id_;
Z
update  
zhiru 已提交
1443
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN UPDATING TABLE FILE" << ": " << er.what();
1444 1445
            return Status::DBTransactionError("GENERAL ERROR WHEN UPDATING TABLE FILE", er.what());
        }
Z
update  
zhiru 已提交
1446 1447 1448
        return Status::OK();
    }

P
peng.xu 已提交
1449 1450 1451 1452 1453
    Status MySQLMetaImpl::UpdateTableFilesToIndex(const std::string& table_id) {
        // TODO
        return Status::OK();
    }

Z
update  
zhiru 已提交
1454
    Status MySQLMetaImpl::UpdateTableFiles(TableFilesSchema &files) {
Z
zhiru 已提交
1455

Z
zhiru 已提交
1456
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
1457

1458
        try {
Z
update  
zhiru 已提交
1459
            MetricCollector metric;
1460

1461
            {
Z
update  
zhiru 已提交
1462
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
update  
zhiru 已提交
1463

Z
update  
zhiru 已提交
1464 1465 1466 1467
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1468 1469
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::UpdateTableFiles connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
1470 1471
//                }

1472
                Query updateTableFilesQuery = connectionPtr->query();
Z
update  
zhiru 已提交
1473

1474 1475
                std::map<std::string, bool> has_tables;
                for (auto &file_schema : files) {
Z
update  
zhiru 已提交
1476

1477 1478 1479
                    if (has_tables.find(file_schema.table_id_) != has_tables.end()) {
                        continue;
                    }
Z
update  
zhiru 已提交
1480

1481 1482 1483 1484 1485
                    updateTableFilesQuery << "SELECT EXISTS " <<
                                          "(SELECT 1 FROM Tables " <<
                                          "WHERE table_id = " << quote << file_schema.table_id_ << " " <<
                                          "AND state <> " << std::to_string(TableSchema::TO_DELETE) << ") " <<
                                          "AS " << quote << "check" << ";";
Z
update  
zhiru 已提交
1486

Z
update  
zhiru 已提交
1487
                    ENGINE_LOG_DEBUG << "MySQLMetaImpl::UpdateTableFiles: " << updateTableFilesQuery.str();
Z
update  
zhiru 已提交
1488

1489
                    StoreQueryResult res = updateTableFilesQuery.store();
1490

1491 1492
                    int check = res[0]["check"];
                    has_tables[file_schema.table_id_] = (check == 1);
Z
update  
zhiru 已提交
1493 1494
                }

1495
                for (auto &file_schema : files) {
1496

1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522
                    if (!has_tables[file_schema.table_id_]) {
                        file_schema.file_type_ = TableFileSchema::TO_DELETE;
                    }
                    file_schema.updated_time_ = utils::GetMicroSecTimeStamp();

                    std::string id = std::to_string(file_schema.id_);
                    std::string table_id = file_schema.table_id_;
                    std::string engine_type = std::to_string(file_schema.engine_type_);
                    std::string file_id = file_schema.file_id_;
                    std::string file_type = std::to_string(file_schema.file_type_);
                    std::string size = std::to_string(file_schema.size_);
                    std::string updated_time = std::to_string(file_schema.updated_time_);
                    std::string created_on = std::to_string(file_schema.created_on_);
                    std::string date = std::to_string(file_schema.date_);

                    updateTableFilesQuery << "UPDATE TableFiles " <<
                                          "SET table_id = " << quote << table_id << ", " <<
                                          "engine_type = " << engine_type << ", " <<
                                          "file_id = " << quote << file_id << ", " <<
                                          "file_type = " << file_type << ", " <<
                                          "size = " << size << ", " <<
                                          "updated_time = " << updated_time << ", " <<
                                          "created_on = " << created_on << ", " <<
                                          "date = " << date << " " <<
                                          "WHERE id = " << id << ";";

Z
update  
zhiru 已提交
1523
                    ENGINE_LOG_DEBUG << "MySQLMetaImpl::UpdateTableFiles: " << updateTableFilesQuery.str();
Z
update  
zhiru 已提交
1524

1525 1526 1527 1528 1529 1530 1531
                    if (!updateTableFilesQuery.exec()) {
                        ENGINE_LOG_ERROR << "QUERY ERROR WHEN UPDATING TABLE FILES";
                        return Status::DBTransactionError("QUERY ERROR WHEN UPDATING TABLE FILES",
                                                          updateTableFilesQuery.error());
                    }
                }
            } //Scoped Connection
1532 1533 1534

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1535
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN UPDATING TABLE FILES" << ": " << er.what();
1536 1537 1538
            return Status::DBTransactionError("QUERY ERROR WHEN UPDATING TABLE FILES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1539
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN UPDATING TABLE FILES" << ": " << er.what();
1540 1541
            return Status::DBTransactionError("GENERAL ERROR WHEN UPDATING TABLE FILES", er.what());
        }
Z
update  
zhiru 已提交
1542 1543 1544 1545
        return Status::OK();
    }

    Status MySQLMetaImpl::CleanUpFilesWithTTL(uint16_t seconds) {
Z
zhiru 已提交
1546 1547 1548 1549
//        static int b_count = 0;
//        b_count++;
//        std::cout << "CleanUpFilesWithTTL: " << b_count << std::endl;
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
1550

1551 1552
        auto now = utils::GetMicroSecTimeStamp();
        try {
Z
update  
zhiru 已提交
1553
            MetricCollector metric;
1554

1555
            {
Z
update  
zhiru 已提交
1556 1557

//                ENGINE_LOG_WARNING << "MySQLMetaImpl::CleanUpFilesWithTTL: clean table files: connection in use before creating ScopedConnection = "
Z
update  
zhiru 已提交
1558
//                << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
1559

Z
update  
zhiru 已提交
1560
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
zhiru 已提交
1561

Z
update  
zhiru 已提交
1562 1563 1564 1565
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1566
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
Z
update  
zhiru 已提交
1567
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::CleanUpFilesWithTTL: clean table files: connection in use after creating ScopedConnection = "
Z
update  
zhiru 已提交
1568
//                    << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
1569 1570
//                }

1571 1572 1573 1574 1575
                Query cleanUpFilesWithTTLQuery = connectionPtr->query();
                cleanUpFilesWithTTLQuery << "SELECT id, table_id, file_id, date " <<
                                         "FROM TableFiles " <<
                                         "WHERE file_type = " << std::to_string(TableFileSchema::TO_DELETE) << " AND " <<
                                         "updated_time < " << std::to_string(now - seconds * US_PS) << ";";
Z
update  
zhiru 已提交
1576

Z
update  
zhiru 已提交
1577
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::CleanUpFilesWithTTL: " << cleanUpFilesWithTTLQuery.str();
Z
update  
zhiru 已提交
1578

1579
                StoreQueryResult res = cleanUpFilesWithTTLQuery.store();
1580

1581 1582
                TableFileSchema table_file;
                std::vector<std::string> idsToDelete;
1583

1584
                for (auto &resRow : res) {
1585

1586
                    table_file.id_ = resRow["id"]; //implicit conversion
1587

1588 1589 1590
                    std::string table_id;
                    resRow["table_id"].to_string(table_id);
                    table_file.table_id_ = table_id;
1591

1592 1593 1594
                    std::string file_id;
                    resRow["file_id"].to_string(file_id);
                    table_file.file_id_ = file_id;
1595

1596
                    table_file.date_ = resRow["date"];
1597

S
starlord 已提交
1598
                    utils::DeleteTableFilePath(options_, table_file);
1599

1600 1601
                    ENGINE_LOG_DEBUG << "Removing deleted id =" << table_file.id_ << " location = "
                                     << table_file.location_ << std::endl;
1602

1603 1604
                    idsToDelete.emplace_back(std::to_string(table_file.id_));
                }
1605

Z
fix  
zhiru 已提交
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
                if (!idsToDelete.empty()) {

                    std::stringstream idsToDeleteSS;
                    for (auto &id : idsToDelete) {
                        idsToDeleteSS << "id = " << id << " OR ";
                    }

                    std::string idsToDeleteStr = idsToDeleteSS.str();
                    idsToDeleteStr = idsToDeleteStr.substr(0, idsToDeleteStr.size() - 4); //remove the last " OR "
                    cleanUpFilesWithTTLQuery << "DELETE FROM TableFiles WHERE " <<
                                             idsToDeleteStr << ";";
Z
update  
zhiru 已提交
1617

Z
update  
zhiru 已提交
1618
                    ENGINE_LOG_DEBUG << "MySQLMetaImpl::CleanUpFilesWithTTL: " << cleanUpFilesWithTTLQuery.str();
Z
update  
zhiru 已提交
1619

Z
fix  
zhiru 已提交
1620 1621 1622 1623 1624
                    if (!cleanUpFilesWithTTLQuery.exec()) {
                        ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES WITH TTL";
                        return Status::DBTransactionError("CleanUpFilesWithTTL Error",
                                                          cleanUpFilesWithTTLQuery.error());
                    }
1625 1626
                }
            } //Scoped Connection
1627 1628 1629

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1630
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES WITH TTL" << ": " << er.what();
1631 1632 1633
            return Status::DBTransactionError("QUERY ERROR WHEN CLEANING UP FILES WITH TTL", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1634
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN CLEANING UP FILES WITH TTL" << ": " << er.what();
1635 1636
            return Status::DBTransactionError("GENERAL ERROR WHEN CLEANING UP FILES WITH TTL", er.what());
        }
Z
update  
zhiru 已提交
1637

1638
        try {
Z
update  
zhiru 已提交
1639
            MetricCollector metric;
1640

1641
            {
Z
update  
zhiru 已提交
1642
//                ENGINE_LOG_WARNING << "MySQLMetaImpl::CleanUpFilesWithTTL: clean tables: connection in use before creating ScopedConnection = "
Z
update  
zhiru 已提交
1643
//                                   << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
1644

Z
update  
zhiru 已提交
1645
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
zhiru 已提交
1646

Z
update  
zhiru 已提交
1647 1648 1649 1650
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1651
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
Z
update  
zhiru 已提交
1652
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::CleanUpFilesWithTTL: clean tables: connection in use after creating ScopedConnection = "
Z
update  
zhiru 已提交
1653
//                    << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
1654 1655
//                }

1656 1657 1658 1659
                Query cleanUpFilesWithTTLQuery = connectionPtr->query();
                cleanUpFilesWithTTLQuery << "SELECT id, table_id " <<
                                         "FROM Tables " <<
                                         "WHERE state = " << std::to_string(TableSchema::TO_DELETE) << ";";
Z
update  
zhiru 已提交
1660

Z
update  
zhiru 已提交
1661
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::CleanUpFilesWithTTL: " << cleanUpFilesWithTTLQuery.str();
Z
update  
zhiru 已提交
1662

1663
                StoreQueryResult res = cleanUpFilesWithTTLQuery.store();
Z
zhiru 已提交
1664
//            std::cout << res.num_rows() << std::endl;
1665

Z
fix  
zhiru 已提交
1666
                if (!res.empty()) {
1667

Z
fix  
zhiru 已提交
1668 1669 1670 1671 1672
                    std::stringstream idsToDeleteSS;
                    for (auto &resRow : res) {
                        size_t id = resRow["id"];
                        std::string table_id;
                        resRow["table_id"].to_string(table_id);
1673

S
starlord 已提交
1674
                        utils::DeleteTablePath(options_, table_id);
Z
fix  
zhiru 已提交
1675 1676 1677 1678 1679 1680 1681

                        idsToDeleteSS << "id = " << std::to_string(id) << " OR ";
                    }
                    std::string idsToDeleteStr = idsToDeleteSS.str();
                    idsToDeleteStr = idsToDeleteStr.substr(0, idsToDeleteStr.size() - 4); //remove the last " OR "
                    cleanUpFilesWithTTLQuery << "DELETE FROM Tables WHERE " <<
                                             idsToDeleteStr << ";";
Z
update  
zhiru 已提交
1682

Z
update  
zhiru 已提交
1683
                    ENGINE_LOG_DEBUG << "MySQLMetaImpl::CleanUpFilesWithTTL: " << cleanUpFilesWithTTLQuery.str();
Z
update  
zhiru 已提交
1684

Z
fix  
zhiru 已提交
1685 1686 1687 1688 1689
                    if (!cleanUpFilesWithTTLQuery.exec()) {
                        ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES WITH TTL";
                        return Status::DBTransactionError("QUERY ERROR WHEN CLEANING UP FILES WITH TTL",
                                                          cleanUpFilesWithTTLQuery.error());
                    }
1690
                }
Z
fix  
zhiru 已提交
1691
           } //Scoped Connection
1692

Z
update  
zhiru 已提交
1693 1694
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1695
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES WITH TTL" << ": " << er.what();
Z
update  
zhiru 已提交
1696 1697 1698
            return Status::DBTransactionError("QUERY ERROR WHEN CLEANING UP FILES WITH TTL", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1699
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN CLEANING UP FILES WITH TTL" << ": " << er.what();
Z
update  
zhiru 已提交
1700 1701
            return Status::DBTransactionError("GENERAL ERROR WHEN CLEANING UP FILES WITH TTL", er.what());
        }
1702

Z
update  
zhiru 已提交
1703 1704
        return Status::OK();
    }
1705

Z
update  
zhiru 已提交
1706 1707
    Status MySQLMetaImpl::CleanUp() {

Z
zhiru 已提交
1708
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
update  
zhiru 已提交
1709 1710

        try {
Z
update  
zhiru 已提交
1711
            ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
zhiru 已提交
1712

Z
update  
zhiru 已提交
1713 1714 1715 1716
            if (connectionPtr == nullptr) {
                return Status::Error("Failed to connect to database server");
            }

Z
update  
zhiru 已提交
1717 1718
//            if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                ENGINE_LOG_WARNING << "MySQLMetaImpl::CleanUp: connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
1719 1720
//            }

Z
update  
zhiru 已提交
1721
            Query cleanUpQuery = connectionPtr->query();
Z
update  
zhiru 已提交
1722 1723
            cleanUpQuery << "SELECT table_name " <<
                         "FROM information_schema.tables " <<
Z
zhiru 已提交
1724 1725
                         "WHERE table_schema = " << quote << mysql_connection_pool_->getDB() << " " <<
                         "AND table_name = " << quote << "TableFiles" << ";";
1726

Z
update  
zhiru 已提交
1727
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::CleanUp: " << cleanUpQuery.str();
Z
update  
zhiru 已提交
1728

Z
update  
zhiru 已提交
1729
            StoreQueryResult res = cleanUpQuery.store();
Z
update  
zhiru 已提交
1730

Z
update  
zhiru 已提交
1731 1732 1733 1734
            if (!res.empty()) {
                ENGINE_LOG_DEBUG << "Remove table file type as NEW";
                cleanUpQuery << "DELETE FROM TableFiles WHERE file_type = " << std::to_string(TableFileSchema::NEW) << ";";

Z
update  
zhiru 已提交
1735
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::CleanUp: " << cleanUpQuery.str();
Z
update  
zhiru 已提交
1736 1737 1738 1739 1740

                if (!cleanUpQuery.exec()) {
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES";
                    return Status::DBTransactionError("Clean up Error", cleanUpQuery.error());
                }
1741 1742 1743 1744
            }

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1745
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES" << ": " << er.what();
1746 1747 1748
            return Status::DBTransactionError("QUERY ERROR WHEN CLEANING UP FILES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1749
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN CLEANING UP FILES" << ": " << er.what();
1750 1751
            return Status::DBTransactionError("GENERAL ERROR WHEN CLEANING UP FILES", er.what());
        }
Z
update  
zhiru 已提交
1752 1753 1754 1755 1756 1757

        return Status::OK();
    }

    Status MySQLMetaImpl::Count(const std::string &table_id, uint64_t &result) {

Z
zhiru 已提交
1758
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
1759

1760
        try {
Z
update  
zhiru 已提交
1761
            MetricCollector metric;
1762 1763 1764 1765 1766 1767 1768 1769 1770

            TableSchema table_schema;
            table_schema.table_id_ = table_id;
            auto status = DescribeTable(table_schema);

            if (!status.ok()) {
                return status;
            }

1771 1772 1773
            StoreQueryResult res;

            {
Z
update  
zhiru 已提交
1774
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
1775

Z
update  
zhiru 已提交
1776 1777 1778 1779
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1780 1781
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::Count: connection in use = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
1782 1783
//                }

1784 1785 1786 1787 1788 1789 1790
                Query countQuery = connectionPtr->query();
                countQuery << "SELECT size " <<
                           "FROM TableFiles " <<
                           "WHERE table_id = " << quote << table_id << " AND " <<
                           "(file_type = " << std::to_string(TableFileSchema::RAW) << " OR " <<
                           "file_type = " << std::to_string(TableFileSchema::TO_INDEX) << " OR " <<
                           "file_type = " << std::to_string(TableFileSchema::INDEX) << ");";
Z
update  
zhiru 已提交
1791

Z
update  
zhiru 已提交
1792
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::Count: " << countQuery.str();
Z
update  
zhiru 已提交
1793

1794 1795 1796
                res = countQuery.store();
            } //Scoped Connection

1797 1798 1799 1800 1801 1802
            result = 0;
            for (auto &resRow : res) {
                size_t size = resRow["size"];
                result += size;
            }

Z
update  
zhiru 已提交
1803 1804 1805 1806 1807 1808
            if (table_schema.dimension_ <= 0) {
                std::stringstream errorMsg;
                errorMsg << "MySQLMetaImpl::Count: " << "table dimension = " << std::to_string(table_schema.dimension_) << ", table_id = " << table_id;
                ENGINE_LOG_ERROR << errorMsg.str();
                return Status::Error(errorMsg.str());
            }
1809 1810 1811 1812 1813
            result /= table_schema.dimension_;
            result /= sizeof(float);

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1814
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN RETRIEVING COUNT" << ": " << er.what();
1815 1816 1817
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING COUNT", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1818
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN RETRIEVING COUNT" << ": " << er.what();
1819 1820
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING COUNT", er.what());
        }
Z
update  
zhiru 已提交
1821 1822 1823 1824
        return Status::OK();
    }

    Status MySQLMetaImpl::DropAll() {
Z
zhiru 已提交
1825

Z
zhiru 已提交
1826
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
1827

1828 1829 1830 1831
        if (boost::filesystem::is_directory(options_.path)) {
            boost::filesystem::remove_all(options_.path);
        }
        try {
Z
zhiru 已提交
1832

Z
update  
zhiru 已提交
1833
            ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);
Z
zhiru 已提交
1834

Z
update  
zhiru 已提交
1835 1836 1837 1838
            if (connectionPtr == nullptr) {
                return Status::Error("Failed to connect to database server");
            }

Z
update  
zhiru 已提交
1839 1840
//            if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                ENGINE_LOG_WARNING << "MySQLMetaImpl::DropAll: connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
Z
update  
zhiru 已提交
1841 1842
//            }

1843
            Query dropTableQuery = connectionPtr->query();
1844
            dropTableQuery << "DROP TABLE IF EXISTS Tables, TableFiles;";
Z
update  
zhiru 已提交
1845

Z
update  
zhiru 已提交
1846
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::DropAll: " << dropTableQuery.str();
Z
update  
zhiru 已提交
1847

1848 1849 1850 1851
            if (dropTableQuery.exec()) {
                return Status::OK();
            }
            else {
Z
update  
zhiru 已提交
1852
                ENGINE_LOG_ERROR << "QUERY ERROR WHEN DROPPING TABLE";
1853 1854 1855 1856
                return Status::DBTransactionError("DROP TABLE ERROR", dropTableQuery.error());
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1857
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DROPPING TABLE" << ": " << er.what();
1858 1859 1860
            return Status::DBTransactionError("QUERY ERROR WHEN DROPPING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1861
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DROPPING TABLE" << ": " << er.what();
1862 1863
            return Status::DBTransactionError("GENERAL ERROR WHEN DROPPING TABLE", er.what());
        }
Z
zhiru 已提交
1864
        return Status::OK();
Z
update  
zhiru 已提交
1865 1866 1867
    }

    MySQLMetaImpl::~MySQLMetaImpl() {
Z
zhiru 已提交
1868
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
1869 1870 1871
        if (mode_ != Options::MODE::READ_ONLY) {
            CleanUp();
        }
Z
update  
zhiru 已提交
1872 1873 1874 1875 1876 1877
    }

} // namespace meta
} // namespace engine
} // namespace milvus
} // namespace zilliz