MySQLMetaImpl.cpp 82.3 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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
    }

    std::string MySQLMetaImpl::GetTablePath(const std::string &table_id) {
        return options_.path + "/tables/" + table_id;
    }

    std::string MySQLMetaImpl::GetTableDatePartitionPath(const std::string &table_id, DateT &date) {
        std::stringstream ss;
        ss << GetTablePath(table_id) << "/" << date;
        return ss.str();
    }

    void MySQLMetaImpl::GetTableFilePath(TableFileSchema &group_file) {
        if (group_file.date_ == EmptyDate) {
            group_file.date_ = Meta::GetDate();
        }
        std::stringstream ss;
        ss << GetTableDatePartitionPath(group_file.table_id_, group_file.date_)
           << "/" << group_file.file_id_;
        group_file.location_ = ss.str();
    }

    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 已提交
106
    MySQLMetaImpl::MySQLMetaImpl(const DBMetaOptions &options_, const int& mode)
Z
update  
zhiru 已提交
107 108
            : options_(options_),
              mode_(mode) {
109
        Initialize();
Z
update  
zhiru 已提交
110 111 112
    }

    Status MySQLMetaImpl::Initialize() {
113

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

Z
update  
zhiru 已提交
116 117
        if (!boost::filesystem::is_directory(options_.path)) {
            auto ret = boost::filesystem::create_directory(options_.path);
118
            if (!ret) {
Z
update  
zhiru 已提交
119 120
                ENGINE_LOG_ERROR << "Failed to create db directory " << options_.path;
                return Status::DBTransactionError("Failed to create db directory", options_.path);
121 122
            }
        }
Z
update  
zhiru 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146

        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 已提交
147 148 149
            std::string username = pieces_match[2].str();
            std::string password = pieces_match[3].str();
            std::string serverAddress = pieces_match[4].str();
Z
update  
zhiru 已提交
150 151 152 153
            unsigned int port = 0;
            if (!pieces_match[5].str().empty()) {
                port = std::stoi(pieces_match[5].str());
            }
Z
zhiru 已提交
154 155
            std::string dbName = pieces_match[6].str();
//            std::cout << dbName << " " << serverAddress << " " << username << " " << password << " " << port << std::endl;
156
//            connectionPtr->set_option(new MultiStatementsOption(true));
Z
zhiru 已提交
157
//            connectionPtr->set_option(new mysqlpp::ReconnectOption(true));
Z
zhiru 已提交
158 159
            int threadHint = std::thread::hardware_concurrency();
            int maxPoolSize = threadHint == 0 ? 8 : threadHint;
Z
update  
zhiru 已提交
160
            mysql_connection_pool_ = std::make_shared<MySQLConnectionPool>(dbName, username, password, serverAddress, port, maxPoolSize);
Z
zhiru 已提交
161
//            std::cout << "MySQL++ thread aware:" << std::to_string(connectionPtr->thread_aware()) << std::endl;
Z
update  
zhiru 已提交
162 163

            try {
164

Z
zhiru 已提交
165 166 167
                if (mode_ != Options::MODE::READ_ONLY) {
                    CleanUp();
                }
168 169

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

Z
update  
zhiru 已提交
172 173 174 175
                    if (connectionPtr == nullptr) {
                        return Status::Error("Failed to connect to database server");
                    }

Z
update  
zhiru 已提交
176
//                    ENGINE_LOG_DEBUG << "MySQLMetaImpl::Initialize: connections in use = " << mysql_connection_pool_->getConnectionsInUse();
Z
zhiru 已提交
177 178 179
//                if (!connectionPtr->connect(dbName, serverAddress, username, password, port)) {
//                    return Status::Error("DB connection failed: ", connectionPtr->error());
//                }
180 181 182 183 184
                    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 已提交
185

Z
zhiru 已提交
186 187 188 189 190
//                InitializeQuery << "SET max_allowed_packet=67108864;";
//                if (!InitializeQuery.exec()) {
//                    return Status::DBTransactionError("Initialization Error", InitializeQuery.error());
//                }

191 192
//                InitializeQuery << "DROP TABLE IF EXISTS Tables, TableFiles;";
                    InitializeQuery << "CREATE TABLE IF NOT EXISTS Tables (" <<
193 194
                                    "id BIGINT PRIMARY KEY AUTO_INCREMENT, " <<
                                    "table_id VARCHAR(255) UNIQUE NOT NULL, " <<
Z
update  
zhiru 已提交
195
                                    "state INT NOT NULL, " <<
196 197 198 199 200
                                    "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 已提交
201

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

204 205 206
                    if (!InitializeQuery.exec()) {
                        return Status::DBTransactionError("Initialization Error", InitializeQuery.error());
                    }
207

208 209 210 211 212 213 214 215 216 217
                    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 已提交
218

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

221 222 223 224
                    if (!InitializeQuery.exec()) {
                        return Status::DBTransactionError("Initialization Error", InitializeQuery.error());
                    }
                } //Scoped Connection
225

Z
zhiru 已提交
226 227 228 229
//                //Consume all results to avoid "Commands out of sync" error
//                while (InitializeQuery.more_results()) {
//                    InitializeQuery.store_next();
//                }
230 231 232 233 234 235 236 237 238 239 240
                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 已提交
241 242
            } catch (const BadQuery& er) {
                // Handle any query errors
Z
update  
zhiru 已提交
243
                ENGINE_LOG_ERROR << "QUERY ERROR DURING INITIALIZATION" << ": " << er.what();
244
                return Status::DBTransactionError("QUERY ERROR DURING INITIALIZATION", er.what());
Z
update  
zhiru 已提交
245 246
            } catch (const Exception& er) {
                // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
247
                ENGINE_LOG_ERROR << "GENERAL ERROR DURING INITIALIZATION" << ": " << er.what();
248
                return Status::DBTransactionError("GENERAL ERROR DURING INITIALIZATION", er.what());
Z
zhiru 已提交
249 250
            } catch (std::exception &e) {
                return HandleException("Encounter exception during initialization", e);
Z
update  
zhiru 已提交
251 252 253
            }
        }
        else {
Z
zhiru 已提交
254
            ENGINE_LOG_ERROR << "Wrong URI format. URI = " << uri;
Z
update  
zhiru 已提交
255 256 257 258 259 260 261
            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 已提交
262

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

265
        if (dates.empty()) {
266 267 268 269 270 271 272 273 274 275
            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 已提交
276
        try {
277

Z
update  
zhiru 已提交
278
            auto yesterday = GetDateWithDelta(-1);
279

Z
update  
zhiru 已提交
280 281 282 283 284
            for (auto &date : dates) {
                if (date >= yesterday) {
                    return Status::Error("Could not delete partitions within 2 days");
                }
            }
285 286 287

            std::stringstream dateListSS;
            for (auto &date : dates) {
288
                dateListSS << std::to_string(date) << ", ";
289 290 291 292
            }
            std::string dateListStr = dateListSS.str();
            dateListStr = dateListStr.substr(0, dateListStr.size() - 2); //remove the last ", "

293
            {
Z
update  
zhiru 已提交
294 295
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);

Z
update  
zhiru 已提交
296 297 298 299
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
300 301 302
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DropPartitionsByDates connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
303

304 305 306 307 308 309 310
                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 已提交
311
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::DropPartitionsByDates: " << dropPartitionsByDatesQuery.str();
Z
update  
zhiru 已提交
312

313 314 315 316 317 318
                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
319 320 321

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
322
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DROPPING PARTITIONS BY DATES" << ": " << er.what();
323 324 325
            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 已提交
326
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DROPPING PARTITIONS BY DATES" << ": " << er.what();
327 328
            return Status::DBTransactionError("GENERAL ERROR WHEN DROPPING PARTITIONS BY DATES", er.what());
        }
Z
update  
zhiru 已提交
329 330 331 332
        return Status::OK();
    }

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

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

Z
update  
zhiru 已提交
336 337 338 339 340
//        server::Metrics::GetInstance().MetaAccessTotalIncrement();
        try {

            MetricCollector metric;

341
            {
Z
update  
zhiru 已提交
342 343
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);

Z
update  
zhiru 已提交
344 345 346 347
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
348 349 350
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::CreateTable connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
Z
update  
zhiru 已提交
351

352 353 354 355 356 357 358
                Query createTableQuery = connectionPtr->query();
                ENGINE_LOG_DEBUG << "Create Table in";
                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 已提交
359
//                    ENGINE_LOG_DEBUG << "Create Table : " << createTableQuery.str();
Z
update  
zhiru 已提交
360

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

363
                    StoreQueryResult res = createTableQuery.store();
Z
update  
zhiru 已提交
364

365 366 367 368 369 370 371 372
                    if (res.num_rows() == 1) {
                        int state = res[0]["state"];
                        std::string msg = (TableSchema::TO_DELETE == state) ?
                                          "Table already exists and it is in delete state, please wait a second"
                                                                            : "Table already exists";
                        ENGINE_LOG_WARNING << "MySQLMetaImpl::CreateTable: " << msg;
                        return Status::Error(msg);
                    }
373
                }
Z
zhiru 已提交
374
//                ENGINE_LOG_DEBUG << "Create Table start";
375

376 377 378
                table_schema.files_cnt_ = 0;
                table_schema.id_ = -1;
                table_schema.created_on_ = utils::GetMicroSecTimeStamp();
Z
update  
zhiru 已提交
379 380 381

//            auto start_time = METRICS_NOW_TIME;

382 383 384 385 386 387 388 389 390 391 392 393
                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 已提交
394
//                ENGINE_LOG_DEBUG << "Create Table : " << createTableQuery.str();
Z
update  
zhiru 已提交
395

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

398 399
                if (SimpleResult res = createTableQuery.execute()) {
                    table_schema.id_ = res.insert_id(); //Might need to use SELECT LAST_INSERT_ID()?
Z
update  
zhiru 已提交
400
//                    std::cout << table_schema.id_ << std::endl;
401
                    //Consume all results to avoid "Commands out of sync" error
Z
update  
zhiru 已提交
402 403 404
//                while (createTableQuery.more_results()) {
//                    createTableQuery.store_next();
//                }
405 406 407 408 409
                } else {
                    ENGINE_LOG_ERROR << "Add Table Error";
                    return Status::DBTransactionError("Add Table Error", createTableQuery.error());
                }
            } //Scoped Connection
Z
update  
zhiru 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422

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

            auto table_path = GetTablePath(table_schema.table_id_);
            table_schema.location_ = table_path;
            if (!boost::filesystem::is_directory(table_path)) {
                auto ret = boost::filesystem::create_directories(table_path);
                if (!ret) {
                    ENGINE_LOG_ERROR << "Create directory " << table_path << " Error";
                    return Status::Error("Failed to create table path");
                }
423
            }
Z
update  
zhiru 已提交
424 425
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
426
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN ADDING TABLE" << ": " << er.what();
Z
update  
zhiru 已提交
427 428 429
            return Status::DBTransactionError("QUERY ERROR WHEN ADDING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
430
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN ADDING TABLE" << ": " << er.what();
Z
update  
zhiru 已提交
431
            return Status::DBTransactionError("GENERAL ERROR WHEN ADDING TABLE", er.what());
Z
zhiru 已提交
432 433
        } catch (std::exception &e) {
            return HandleException("Encounter exception when create table", e);
434
        }
Z
update  
zhiru 已提交
435 436 437 438 439

        return Status::OK();
    }

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

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

443
        try {
Z
update  
zhiru 已提交
444 445 446

            MetricCollector metric;

447
            {
Z
update  
zhiru 已提交
448 449
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);

Z
update  
zhiru 已提交
450 451 452 453
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
454 455 456
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DeleteTable connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
Z
zhiru 已提交
457

458 459
                //soft delete table
                Query deleteTableQuery = connectionPtr->query();
Z
update  
zhiru 已提交
460
//
461 462 463
                deleteTableQuery << "UPDATE Tables " <<
                                    "SET state = " << std::to_string(TableSchema::TO_DELETE) << " " <<
                                    "WHERE table_id = " << quote << table_id << ";";
Z
update  
zhiru 已提交
464

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

467 468 469 470 471 472
                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 已提交
473 474


Z
zhiru 已提交
475
            if (mode_ == Options::MODE::CLUSTER) {
Z
update  
zhiru 已提交
476 477 478
                DeleteTableFiles(table_id);
            }

479 480
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
481
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DELETING TABLE" << ": " << er.what();
482 483 484
            return Status::DBTransactionError("QUERY ERROR WHEN DELETING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
485
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DELETING TABLE" << ": " << er.what();
486 487
            return Status::DBTransactionError("GENERAL ERROR WHEN DELETING TABLE", er.what());
        }
Z
update  
zhiru 已提交
488 489 490 491 492 493 494 495

        return Status::OK();
    }

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

496
            {
Z
update  
zhiru 已提交
497 498
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);

Z
update  
zhiru 已提交
499 500 501 502
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
503 504 505
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DeleteTableFiles connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
Z
update  
zhiru 已提交
506

507 508 509 510
                //soft delete table files
                Query deleteTableFilesQuery = connectionPtr->query();
                //
                deleteTableFilesQuery << "UPDATE TableFiles " <<
Z
update  
zhiru 已提交
511
                                      "SET file_type = " << std::to_string(TableFileSchema::TO_DELETE) << ", " <<
512
                                      "updated_time = " << std::to_string(utils::GetMicroSecTimeStamp()) << " " <<
Z
update  
zhiru 已提交
513
                                      "WHERE table_id = " << quote << table_id << " AND " <<
Z
update  
zhiru 已提交
514
                                      "file_type <> " << std::to_string(TableFileSchema::TO_DELETE) << ";";
515

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

518 519 520 521 522
                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 已提交
523 524
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
525
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DELETING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
526 527 528
            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 已提交
529
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DELETING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
530 531 532 533
            return Status::DBTransactionError("GENERAL ERROR WHEN DELETING TABLE FILES", er.what());
        }

        return Status::OK();
Z
update  
zhiru 已提交
534 535 536
    }

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

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

540
        try {
Z
update  
zhiru 已提交
541 542

            MetricCollector metric;
543

544 545 546
            StoreQueryResult res;

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

Z
update  
zhiru 已提交
549 550 551 552
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
553 554 555
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DescribeTable connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
Z
zhiru 已提交
556

557 558 559 560 561
                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 已提交
562

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

565 566
                res = describeTableQuery.store();
            } //Scoped Connection
567 568 569 570 571 572 573 574 575 576 577 578

            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 已提交
579 580
                int store_raw_data = resRow["store_raw_data"];
                table_schema.store_raw_data_ = (store_raw_data == 1);
581 582 583 584 585 586 587 588 589 590
            }
            else {
                return Status::NotFound("Table " + table_schema.table_id_ + " not found");
            }

            auto table_path = GetTablePath(table_schema.table_id_);
            table_schema.location_ = table_path;

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
591
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DESCRIBING TABLE" << ": " << er.what();
592 593 594
            return Status::DBTransactionError("QUERY ERROR WHEN DESCRIBING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
595
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DESCRIBING TABLE" << ": " << er.what();
596 597
            return Status::DBTransactionError("GENERAL ERROR WHEN DESCRIBING TABLE", er.what());
        }
Z
update  
zhiru 已提交
598 599 600 601 602

        return Status::OK();
    }

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

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

606
        try {
Z
update  
zhiru 已提交
607 608 609

            MetricCollector metric;

610 611 612
            StoreQueryResult res;

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

Z
update  
zhiru 已提交
615 616 617 618
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
619 620 621
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::HasTable connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
622

623 624 625 626 627 628 629
                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 已提交
630

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

633 634
                res = hasTableQuery.store();
            } //Scoped Connection
635 636 637 638 639 640

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

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
641
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN CHECKING IF TABLE EXISTS" << ": " << er.what();
642 643 644
            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 已提交
645
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN CHECKING IF TABLE EXISTS" << ": " << er.what();
646 647 648
            return Status::DBTransactionError("GENERAL ERROR WHEN CHECKING IF TABLE EXISTS", er.what());
        }

Z
update  
zhiru 已提交
649 650 651 652
        return Status::OK();
    }

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

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

656
        try {
Z
update  
zhiru 已提交
657 658

            MetricCollector metric;
659

660 661 662
            StoreQueryResult res;

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

Z
update  
zhiru 已提交
665 666 667 668
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
669 670 671
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::AllTables connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
Z
zhiru 已提交
672

673 674 675 676
                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 已提交
677

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

680 681
                res = allTablesQuery.store();
            } //Scoped Connection
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697

            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 已提交
698 699
                int store_raw_data = resRow["store_raw_data"];
                table_schema.store_raw_data_ = (store_raw_data == 1);
700 701 702 703 704

                table_schema_array.emplace_back(table_schema);
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
705
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DESCRIBING ALL TABLES" << ": " << er.what();
706 707 708
            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 已提交
709
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DESCRIBING ALL TABLES" << ": " << er.what();
710 711
            return Status::DBTransactionError("GENERAL ERROR WHEN DESCRIBING ALL TABLES", er.what());
        }
Z
update  
zhiru 已提交
712 713 714 715 716

        return Status::OK();
    }

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

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

720 721 722 723 724 725 726 727 728 729
        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 已提交
730
        try {
731

Z
update  
zhiru 已提交
732
            MetricCollector metric;
733

Z
update  
zhiru 已提交
734 735 736 737 738 739 740 741
            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_;
            GetTableFilePath(file_schema);
742

Z
update  
zhiru 已提交
743 744 745 746 747 748 749 750 751
            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_);
752

753
            {
Z
update  
zhiru 已提交
754 755
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);

Z
update  
zhiru 已提交
756 757 758 759
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
760 761 762
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::CreateTableFile connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
Z
zhiru 已提交
763

764
                Query createTableFileQuery = connectionPtr->query();
765

766 767 768 769 770
                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 已提交
771
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::CreateTableFile: " << createTableFileQuery.str();
Z
update  
zhiru 已提交
772

773 774 775 776
                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 已提交
777 778 779
//                while (createTableFileQuery.more_results()) {
//                    createTableFileQuery.store_next();
//                }
780 781 782 783 784
                } else {
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN ADDING TABLE FILE";
                    return Status::DBTransactionError("Add file Error", createTableFileQuery.error());
                }
            } // Scoped Connection
785

Z
update  
zhiru 已提交
786
            auto partition_path = GetTableDatePartitionPath(file_schema.table_id_, file_schema.date_);
787

Z
update  
zhiru 已提交
788 789 790 791 792 793
            if (!boost::filesystem::is_directory(partition_path)) {
                auto ret = boost::filesystem::create_directory(partition_path);
                if (!ret) {
                    ENGINE_LOG_ERROR << "Create directory " << partition_path << " Error";
                    return Status::DBTransactionError("Failed to create partition directory");
                }
794
            }
Z
update  
zhiru 已提交
795 796 797

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
798
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN ADDING TABLE FILE" << ": " << er.what();
Z
update  
zhiru 已提交
799 800 801
            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 已提交
802
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN ADDING TABLE FILE" << ": " << er.what();
Z
update  
zhiru 已提交
803
            return Status::DBTransactionError("GENERAL ERROR WHEN ADDING TABLE FILE", er.what());
Z
zhiru 已提交
804 805
        } catch (std::exception& ex) {
            return HandleException("Encounter exception when create table file", ex);
806
        }
Z
update  
zhiru 已提交
807 808 809 810 811

        return Status::OK();
    }

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

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

815 816 817
        files.clear();

        try {
Z
update  
zhiru 已提交
818 819

            MetricCollector metric;
820

821 822 823
            StoreQueryResult res;

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

Z
update  
zhiru 已提交
826 827 828 829
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
830 831 832
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::FilesToIndex connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
Z
zhiru 已提交
833

834 835 836 837
                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 已提交
838

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

841 842
                res = filesToIndexQuery.store();
            } //Scoped Connection
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884

            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_;

                GetTableFilePath(table_file);

                files.push_back(table_file);
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
885
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN FINDING TABLE FILES TO INDEX" << ": " << er.what();
886 887 888
            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 已提交
889
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN FINDING TABLE FILES TO INDEX" << ": " << er.what();
890 891
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO INDEX", er.what());
        }
Z
update  
zhiru 已提交
892 893 894 895 896 897 898

        return Status::OK();
    }

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

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

902 903 904
        files.clear();

        try {
Z
update  
zhiru 已提交
905 906

            MetricCollector metric;
907 908 909

            StoreQueryResult res;

910
            {
Z
update  
zhiru 已提交
911 912
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);

Z
update  
zhiru 已提交
913 914 915
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }
Z
update  
zhiru 已提交
916 917 918
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::FilesToSearch connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
919

920
                if (partition.empty()) {
921

922 923 924 925 926 927 928
                    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 已提交
929

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

932
                    res = filesToSearchQuery.store();
933

934
                } else {
935

936
                    Query filesToSearchQuery = connectionPtr->query();
937

938 939 940 941 942 943 944 945 946
                    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 已提交
947 948 949 950 951
                                       "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 已提交
952

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

955
                    res = filesToSearchQuery.store();
956

957 958
                }
            } //Scoped Connection
959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000

            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_;

                GetTableFilePath(table_file);

                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 已提交
1001
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN FINDING TABLE FILES TO SEARCH" << ": " << er.what();
1002 1003 1004
            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 已提交
1005
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN FINDING TABLE FILES TO SEARCH" << ": " << er.what();
1006 1007
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO SEARCH", er.what());
        }
Z
update  
zhiru 已提交
1008 1009 1010 1011 1012 1013

        return Status::OK();
    }

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

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

1017 1018 1019
        files.clear();

        try {
Z
update  
zhiru 已提交
1020
            MetricCollector metric;
1021

1022
            StoreQueryResult res;
Z
zhiru 已提交
1023

1024
            {
Z
update  
zhiru 已提交
1025 1026
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);

Z
update  
zhiru 已提交
1027 1028 1029 1030
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1031 1032 1033
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::FilesToMerge connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
1034 1035 1036 1037 1038 1039 1040

                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 已提交
1041

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

1044 1045
                res = filesToMergeQuery.store();
            } //Scoped Connection
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087

            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_;

                GetTableFilePath(table_file);

                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 已提交
1088
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN FINDING TABLE FILES TO MERGE" << ": " << er.what();
1089 1090 1091
            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 已提交
1092
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN FINDING TABLE FILES TO MERGE" << ": " << er.what();
1093 1094
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO MERGE", er.what());
        }
Z
update  
zhiru 已提交
1095 1096 1097 1098

        return Status::OK();
    }

Z
update  
zhiru 已提交
1099 1100 1101
    Status MySQLMetaImpl::GetTableFiles(const std::string& table_id,
                                        const std::vector<size_t>& ids,
                                        TableFilesSchema& table_files) {
Z
update  
zhiru 已提交
1102

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

Z
fix  
zhiru 已提交
1105 1106 1107 1108
        if (ids.empty()) {
            return Status::OK();
        }

Z
update  
zhiru 已提交
1109 1110 1111 1112 1113 1114 1115
        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 "

1116 1117
        try {

1118 1119 1120
            StoreQueryResult res;

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

Z
update  
zhiru 已提交
1123 1124 1125 1126
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1127 1128 1129
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::GetTableFiles connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
Z
zhiru 已提交
1130

1131
                Query getTableFileQuery = connectionPtr->query();
Z
update  
zhiru 已提交
1132 1133 1134 1135
                getTableFileQuery << "SELECT id, engine_type, file_id, file_type, size, date " <<
                                      "FROM TableFiles " <<
                                      "WHERE table_id = " << quote << table_id << " AND " <<
                                      "(" << idStr << ");";
Z
update  
zhiru 已提交
1136

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

1139 1140
                res = getTableFileQuery.store();
            } //Scoped Connection
1141

Z
update  
zhiru 已提交
1142 1143 1144 1145 1146 1147
            TableSchema table_schema;
            table_schema.table_id_ = table_id;
            auto status = DescribeTable(table_schema);
            if (!status.ok()) {
                return status;
            }
1148

Z
update  
zhiru 已提交
1149 1150 1151
            for (auto& resRow : res) {

                TableFileSchema file_schema;
1152

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

1155 1156
                file_schema.table_id_ = table_id;

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

1159 1160 1161 1162 1163 1164 1165 1166 1167
                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 已提交
1168 1169 1170 1171 1172 1173

                file_schema.dimension_ = table_schema.dimension_;

                GetTableFilePath(file_schema);

                table_files.emplace_back(file_schema);
1174 1175 1176
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1177
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN RETRIEVING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
1178
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING TABLE FILES", er.what());
1179 1180
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1181
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN RETRIEVING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
1182
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING TABLE FILES", er.what());
1183
        }
Z
update  
zhiru 已提交
1184 1185 1186 1187 1188 1189

        return Status::OK();
    }

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

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

1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
        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 已提交
1204

1205 1206
                try {

Z
update  
zhiru 已提交
1207 1208
                    ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);

Z
update  
zhiru 已提交
1209 1210 1211 1212
                    if (connectionPtr == nullptr) {
                        return Status::Error("Failed to connect to database server");
                    }

Z
update  
zhiru 已提交
1213 1214 1215
//                    if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                        ENGINE_LOG_WARNING << "MySQLMetaImpl::Archive connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                    }
Z
zhiru 已提交
1216

1217
                    Query archiveQuery = connectionPtr->query();
1218
                    archiveQuery << "UPDATE TableFiles " <<
1219 1220 1221
                                    "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 已提交
1222

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

1225 1226 1227 1228 1229 1230
                    if (!archiveQuery.exec()) {
                        return Status::DBTransactionError("QUERY ERROR DURING ARCHIVE", archiveQuery.error());
                    }

                } catch (const BadQuery& er) {
                    // Handle any query errors
Z
update  
zhiru 已提交
1231
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN DURING ARCHIVE" << ": " << er.what();
1232 1233 1234
                    return Status::DBTransactionError("QUERY ERROR WHEN DURING ARCHIVE", er.what());
                } catch (const Exception& er) {
                    // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1235
                    ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DURING ARCHIVE" << ": " << er.what();
1236 1237 1238 1239 1240 1241 1242
                    return Status::DBTransactionError("GENERAL ERROR WHEN DURING ARCHIVE", er.what());
                }
            }
            if (criteria == "disk") {
                uint64_t sum = 0;
                Size(sum);

Z
update  
zhiru 已提交
1243
                auto to_delete = (sum - limit * G);
1244 1245 1246
                DiscardFiles(to_delete);
            }
        }
Z
update  
zhiru 已提交
1247 1248 1249 1250 1251

        return Status::OK();
    }

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

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

1255 1256 1257
        result = 0;
        try {

1258 1259 1260
            StoreQueryResult res;

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

Z
update  
zhiru 已提交
1263 1264 1265 1266
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1267 1268 1269
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::Size connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
Z
zhiru 已提交
1270

1271
                Query getSizeQuery = connectionPtr->query();
Z
update  
zhiru 已提交
1272
                getSizeQuery << "SELECT IFNULL(SUM(size),0) AS sum " <<
1273 1274
                             "FROM TableFiles " <<
                             "WHERE file_type <> " << std::to_string(TableFileSchema::TO_DELETE) << ";";
Z
update  
zhiru 已提交
1275

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

1278 1279
                res = getSizeQuery.store();
            } //Scoped Connection
1280

Z
zhiru 已提交
1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
//            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;
            }
1293 1294 1295

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1296
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN RETRIEVING SIZE" << ": " << er.what();
1297 1298 1299
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING SIZE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1300
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN RETRIEVING SIZE" << ": " << er.what();
1301 1302
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING SIZE", er.what());
        }
Z
update  
zhiru 已提交
1303 1304 1305 1306

        return Status::OK();
    }

Z
zhiru 已提交
1307 1308
    Status MySQLMetaImpl::DiscardFiles(long long to_discard_size) {

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

1311 1312 1313 1314
        if (to_discard_size <= 0) {
//            std::cout << "in" << std::endl;
            return Status::OK();
        }
Z
update  
zhiru 已提交
1315 1316
        ENGINE_LOG_DEBUG << "About to discard size=" << to_discard_size;

1317 1318
        try {

Z
update  
zhiru 已提交
1319 1320
            MetricCollector metric;

1321 1322 1323
            bool status;

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

Z
update  
zhiru 已提交
1326 1327 1328 1329
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1330 1331 1332
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DiscardFiles connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
Z
zhiru 已提交
1333

1334 1335 1336 1337 1338 1339
                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 已提交
1340

Z
update  
zhiru 已提交
1341
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::DiscardFiles: " << discardFilesQuery.str();
Z
update  
zhiru 已提交
1342 1343

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

1346 1347 1348
                if (res.num_rows() == 0) {
                    return Status::OK();
                }
1349

1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
                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_;
1362 1363
                }

1364 1365
                std::string idsToDiscardStr = idsToDiscardSS.str();
                idsToDiscardStr = idsToDiscardStr.substr(0, idsToDiscardStr.size() - 4); //remove the last " OR "
1366

1367 1368 1369 1370
                discardFilesQuery << "UPDATE TableFiles " <<
                                  "SET file_type = " << std::to_string(TableFileSchema::TO_DELETE) << ", " <<
                                  "updated_time = " << std::to_string(utils::GetMicroSecTimeStamp()) << " " <<
                                  "WHERE " << idsToDiscardStr << ";";
1371

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

1374 1375 1376 1377 1378 1379 1380 1381
                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);
1382 1383 1384

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1385
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DISCARDING FILES" << ": " << er.what();
1386 1387 1388
            return Status::DBTransactionError("QUERY ERROR WHEN DISCARDING FILES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1389
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DISCARDING FILES" << ": " << er.what();
1390 1391
            return Status::DBTransactionError("GENERAL ERROR WHEN DISCARDING FILES", er.what());
        }
Z
update  
zhiru 已提交
1392 1393
    }

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

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

1399 1400
        file_schema.updated_time_ = utils::GetMicroSecTimeStamp();
        try {
Z
update  
zhiru 已提交
1401 1402

            MetricCollector metric;
1403

1404
            {
Z
update  
zhiru 已提交
1405 1406
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);

Z
update  
zhiru 已提交
1407 1408 1409 1410
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1411 1412 1413
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::UpdateTableFile connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
Z
zhiru 已提交
1414

1415
                Query updateTableFileQuery = connectionPtr->query();
1416

1417 1418 1419 1420
                //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 已提交
1421

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

1424 1425 1426 1427 1428 1429 1430 1431
                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 已提交
1432 1433 1434
                    file_schema.file_type_ = TableFileSchema::TO_DELETE;
                }

1435 1436 1437 1438 1439 1440 1441 1442 1443
                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_);
1444

1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
                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 << ";";
1455

Z
update  
zhiru 已提交
1456
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::UpdateTableFile: " << updateTableFileQuery.str();
Z
update  
zhiru 已提交
1457 1458

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

1460 1461 1462 1463 1464 1465 1466
                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
1467 1468 1469 1470

        } 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 已提交
1471
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN UPDATING TABLE FILE" << ": " << er.what();
1472 1473 1474 1475
            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 已提交
1476
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN UPDATING TABLE FILE" << ": " << er.what();
1477 1478
            return Status::DBTransactionError("GENERAL ERROR WHEN UPDATING TABLE FILE", er.what());
        }
Z
update  
zhiru 已提交
1479 1480 1481 1482
        return Status::OK();
    }

    Status MySQLMetaImpl::UpdateTableFiles(TableFilesSchema &files) {
Z
zhiru 已提交
1483

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

1486
        try {
Z
update  
zhiru 已提交
1487
            MetricCollector metric;
1488

1489
            {
Z
update  
zhiru 已提交
1490 1491
                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);

Z
update  
zhiru 已提交
1492 1493 1494 1495
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1496 1497 1498
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::UpdateTableFiles connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//                }
Z
update  
zhiru 已提交
1499

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

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

1505 1506 1507
                    if (has_tables.find(file_schema.table_id_) != has_tables.end()) {
                        continue;
                    }
Z
update  
zhiru 已提交
1508

1509 1510 1511 1512 1513
                    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 已提交
1514

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

1517
                    StoreQueryResult res = updateTableFilesQuery.store();
1518

1519 1520
                    int check = res[0]["check"];
                    has_tables[file_schema.table_id_] = (check == 1);
Z
update  
zhiru 已提交
1521 1522
                }

1523
                for (auto &file_schema : files) {
1524

1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
                    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 已提交
1551
                    ENGINE_LOG_DEBUG << "MySQLMetaImpl::UpdateTableFiles: " << updateTableFilesQuery.str();
Z
update  
zhiru 已提交
1552

1553 1554 1555 1556 1557 1558 1559
                    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
1560 1561 1562

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1563
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN UPDATING TABLE FILES" << ": " << er.what();
1564 1565 1566
            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 已提交
1567
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN UPDATING TABLE FILES" << ": " << er.what();
1568 1569
            return Status::DBTransactionError("GENERAL ERROR WHEN UPDATING TABLE FILES", er.what());
        }
Z
update  
zhiru 已提交
1570 1571 1572 1573
        return Status::OK();
    }

    Status MySQLMetaImpl::CleanUpFilesWithTTL(uint16_t seconds) {
Z
zhiru 已提交
1574 1575 1576 1577
//        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 已提交
1578

1579 1580
        auto now = utils::GetMicroSecTimeStamp();
        try {
Z
update  
zhiru 已提交
1581
            MetricCollector metric;
1582

1583
            {
Z
update  
zhiru 已提交
1584 1585 1586 1587 1588 1589

//                ENGINE_LOG_WARNING << "MySQLMetaImpl::CleanUpFilesWithTTL: clean table files: connection in use before creating ScopedConnection = "
//                << mysql_connection_pool_->getConnectionsInUse();

                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);

Z
update  
zhiru 已提交
1590 1591 1592 1593
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1594 1595 1596 1597
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::CleanUpFilesWithTTL: clean table files: connection in use after creating ScopedConnection = "
//                    << mysql_connection_pool_->getConnectionsInUse();
//                }
Z
zhiru 已提交
1598

1599 1600 1601 1602 1603
                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 已提交
1604

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

1607
                StoreQueryResult res = cleanUpFilesWithTTLQuery.store();
1608

1609 1610
                TableFileSchema table_file;
                std::vector<std::string> idsToDelete;
1611

1612
                for (auto &resRow : res) {
1613

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

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

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

1624
                    table_file.date_ = resRow["date"];
1625

1626
                    GetTableFilePath(table_file);
1627

1628 1629 1630
                    ENGINE_LOG_DEBUG << "Removing deleted id =" << table_file.id_ << " location = "
                                     << table_file.location_ << std::endl;
                    boost::filesystem::remove(table_file.location_);
1631

1632 1633
                    idsToDelete.emplace_back(std::to_string(table_file.id_));
                }
1634

Z
fix  
zhiru 已提交
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
                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 已提交
1646

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

Z
fix  
zhiru 已提交
1649 1650 1651 1652 1653
                    if (!cleanUpFilesWithTTLQuery.exec()) {
                        ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES WITH TTL";
                        return Status::DBTransactionError("CleanUpFilesWithTTL Error",
                                                          cleanUpFilesWithTTLQuery.error());
                    }
1654 1655
                }
            } //Scoped Connection
1656 1657 1658

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1659
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES WITH TTL" << ": " << er.what();
1660 1661 1662
            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 已提交
1663
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN CLEANING UP FILES WITH TTL" << ": " << er.what();
1664 1665
            return Status::DBTransactionError("GENERAL ERROR WHEN CLEANING UP FILES WITH TTL", er.what());
        }
Z
update  
zhiru 已提交
1666

1667
        try {
Z
update  
zhiru 已提交
1668
            MetricCollector metric;
1669

1670
            {
Z
update  
zhiru 已提交
1671 1672 1673 1674 1675
//                ENGINE_LOG_WARNING << "MySQLMetaImpl::CleanUpFilesWithTTL: clean tables: connection in use before creating ScopedConnection = "
//                                   << mysql_connection_pool_->getConnectionsInUse();

                ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);

Z
update  
zhiru 已提交
1676 1677 1678 1679
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1680 1681 1682 1683
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::CleanUpFilesWithTTL: clean tables: connection in use after creating ScopedConnection = "
//                    << mysql_connection_pool_->getConnectionsInUse();
//                }
Z
zhiru 已提交
1684

1685 1686 1687 1688
                Query cleanUpFilesWithTTLQuery = connectionPtr->query();
                cleanUpFilesWithTTLQuery << "SELECT id, table_id " <<
                                         "FROM Tables " <<
                                         "WHERE state = " << std::to_string(TableSchema::TO_DELETE) << ";";
Z
update  
zhiru 已提交
1689

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

1692
                StoreQueryResult res = cleanUpFilesWithTTLQuery.store();
Z
zhiru 已提交
1693
//            std::cout << res.num_rows() << std::endl;
1694

Z
fix  
zhiru 已提交
1695
                if (!res.empty()) {
1696

Z
fix  
zhiru 已提交
1697 1698 1699 1700 1701
                    std::stringstream idsToDeleteSS;
                    for (auto &resRow : res) {
                        size_t id = resRow["id"];
                        std::string table_id;
                        resRow["table_id"].to_string(table_id);
1702

Z
fix  
zhiru 已提交
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
                        auto table_path = GetTablePath(table_id);

                        ENGINE_LOG_DEBUG << "Remove table folder: " << table_path;
                        boost::filesystem::remove_all(table_path);

                        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 已提交
1714

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

Z
fix  
zhiru 已提交
1717 1718 1719 1720 1721
                    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());
                    }
1722
                }
Z
fix  
zhiru 已提交
1723
           } //Scoped Connection
1724

Z
update  
zhiru 已提交
1725 1726
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1727
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES WITH TTL" << ": " << er.what();
Z
update  
zhiru 已提交
1728 1729 1730
            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 已提交
1731
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN CLEANING UP FILES WITH TTL" << ": " << er.what();
Z
update  
zhiru 已提交
1732 1733
            return Status::DBTransactionError("GENERAL ERROR WHEN CLEANING UP FILES WITH TTL", er.what());
        }
1734

Z
update  
zhiru 已提交
1735 1736
        return Status::OK();
    }
1737

Z
update  
zhiru 已提交
1738 1739
    Status MySQLMetaImpl::CleanUp() {

Z
zhiru 已提交
1740
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
update  
zhiru 已提交
1741 1742

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

Z
update  
zhiru 已提交
1745 1746 1747 1748
            if (connectionPtr == nullptr) {
                return Status::Error("Failed to connect to database server");
            }

Z
update  
zhiru 已提交
1749 1750 1751
//            if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                ENGINE_LOG_WARNING << "MySQLMetaImpl::CleanUp: connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//            }
Z
zhiru 已提交
1752

Z
update  
zhiru 已提交
1753
            Query cleanUpQuery = connectionPtr->query();
Z
update  
zhiru 已提交
1754 1755
            cleanUpQuery << "SELECT table_name " <<
                         "FROM information_schema.tables " <<
Z
zhiru 已提交
1756 1757
                         "WHERE table_schema = " << quote << mysql_connection_pool_->getDB() << " " <<
                         "AND table_name = " << quote << "TableFiles" << ";";
1758

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

Z
update  
zhiru 已提交
1761
            StoreQueryResult res = cleanUpQuery.store();
Z
update  
zhiru 已提交
1762

Z
update  
zhiru 已提交
1763 1764 1765 1766
            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 已提交
1767
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::CleanUp: " << cleanUpQuery.str();
Z
update  
zhiru 已提交
1768 1769 1770 1771 1772

                if (!cleanUpQuery.exec()) {
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES";
                    return Status::DBTransactionError("Clean up Error", cleanUpQuery.error());
                }
1773 1774 1775 1776
            }

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1777
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES" << ": " << er.what();
1778 1779 1780
            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 已提交
1781
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN CLEANING UP FILES" << ": " << er.what();
1782 1783
            return Status::DBTransactionError("GENERAL ERROR WHEN CLEANING UP FILES", er.what());
        }
Z
update  
zhiru 已提交
1784 1785 1786 1787 1788 1789

        return Status::OK();
    }

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

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

1792
        try {
Z
update  
zhiru 已提交
1793
            MetricCollector metric;
1794 1795 1796 1797 1798 1799 1800 1801 1802

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

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

1803 1804 1805
            StoreQueryResult res;

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

Z
update  
zhiru 已提交
1808 1809 1810 1811
                if (connectionPtr == nullptr) {
                    return Status::Error("Failed to connect to database server");
                }

Z
update  
zhiru 已提交
1812 1813 1814
//                if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::Count: connection in use = " << mysql_connection_pool_->getConnectionsInUse();
//                }
1815 1816 1817 1818 1819 1820 1821 1822

                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 已提交
1823

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

1826 1827 1828
                res = countQuery.store();
            } //Scoped Connection

1829 1830 1831 1832 1833 1834
            result = 0;
            for (auto &resRow : res) {
                size_t size = resRow["size"];
                result += size;
            }

Z
update  
zhiru 已提交
1835 1836 1837 1838 1839 1840
            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());
            }
1841 1842 1843 1844 1845
            result /= table_schema.dimension_;
            result /= sizeof(float);

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1846
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN RETRIEVING COUNT" << ": " << er.what();
1847 1848 1849
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING COUNT", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1850
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN RETRIEVING COUNT" << ": " << er.what();
1851 1852
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING COUNT", er.what());
        }
Z
update  
zhiru 已提交
1853 1854 1855 1856
        return Status::OK();
    }

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

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

1860 1861 1862 1863
        if (boost::filesystem::is_directory(options_.path)) {
            boost::filesystem::remove_all(options_.path);
        }
        try {
Z
zhiru 已提交
1864

Z
update  
zhiru 已提交
1865 1866
            ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab);

Z
update  
zhiru 已提交
1867 1868 1869 1870
            if (connectionPtr == nullptr) {
                return Status::Error("Failed to connect to database server");
            }

Z
update  
zhiru 已提交
1871 1872 1873
//            if (mysql_connection_pool_->getConnectionsInUse() <= 0) {
//                ENGINE_LOG_WARNING << "MySQLMetaImpl::DropAll: connection in use  = " << mysql_connection_pool_->getConnectionsInUse();
//            }
Z
zhiru 已提交
1874

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

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

1880 1881 1882 1883
            if (dropTableQuery.exec()) {
                return Status::OK();
            }
            else {
Z
update  
zhiru 已提交
1884
                ENGINE_LOG_ERROR << "QUERY ERROR WHEN DROPPING TABLE";
1885 1886 1887 1888
                return Status::DBTransactionError("DROP TABLE ERROR", dropTableQuery.error());
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1889
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DROPPING TABLE" << ": " << er.what();
1890 1891 1892
            return Status::DBTransactionError("QUERY ERROR WHEN DROPPING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1893
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DROPPING TABLE" << ": " << er.what();
1894 1895
            return Status::DBTransactionError("GENERAL ERROR WHEN DROPPING TABLE", er.what());
        }
Z
zhiru 已提交
1896
        return Status::OK();
Z
update  
zhiru 已提交
1897 1898 1899
    }

    MySQLMetaImpl::~MySQLMetaImpl() {
Z
zhiru 已提交
1900
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
zhiru 已提交
1901 1902 1903
        if (mode_ != Options::MODE::READ_ONLY) {
            CleanUp();
        }
Z
update  
zhiru 已提交
1904 1905 1906 1907 1908 1909
    }

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