MySQLMetaImpl.cpp 69.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 106 107
    }

    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();
    }

    MySQLMetaImpl::MySQLMetaImpl(const DBMetaOptions &options_)
            : options_(options_) {
108
        Initialize();
Z
update  
zhiru 已提交
109 110 111
    }

    Status MySQLMetaImpl::Initialize() {
112

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

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

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

            try {
163 164 165 166 167

                CleanUp();

                {
                    ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
168 169 170
//                if (!connectionPtr->connect(dbName, serverAddress, username, password, port)) {
//                    return Status::Error("DB connection failed: ", connectionPtr->error());
//                }
171 172 173 174 175
                    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 已提交
176

Z
zhiru 已提交
177 178 179 180 181
//                InitializeQuery << "SET max_allowed_packet=67108864;";
//                if (!InitializeQuery.exec()) {
//                    return Status::DBTransactionError("Initialization Error", InitializeQuery.error());
//                }

182 183
//                InitializeQuery << "DROP TABLE IF EXISTS Tables, TableFiles;";
                    InitializeQuery << "CREATE TABLE IF NOT EXISTS Tables (" <<
184 185
                                    "id BIGINT PRIMARY KEY AUTO_INCREMENT, " <<
                                    "table_id VARCHAR(255) UNIQUE NOT NULL, " <<
Z
update  
zhiru 已提交
186
                                    "state INT NOT NULL, " <<
187 188 189 190 191
                                    "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);";
192 193 194
                    if (!InitializeQuery.exec()) {
                        return Status::DBTransactionError("Initialization Error", InitializeQuery.error());
                    }
195

196 197 198 199 200 201 202 203 204 205 206 207 208 209
                    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);";
                    if (!InitializeQuery.exec()) {
                        return Status::DBTransactionError("Initialization Error", InitializeQuery.error());
                    }
                } //Scoped Connection
210

Z
zhiru 已提交
211 212 213 214
//                //Consume all results to avoid "Commands out of sync" error
//                while (InitializeQuery.more_results()) {
//                    InitializeQuery.store_next();
//                }
215 216 217 218 219 220 221 222 223 224 225
                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 已提交
226
            } catch (const ConnectionFailed& er) {
Z
update  
zhiru 已提交
227
                ENGINE_LOG_ERROR << "Failed to connect to database server" << ": " << er.what();
228
                return Status::DBTransactionError("Failed to connect to database server", er.what());
Z
update  
zhiru 已提交
229 230
            } catch (const BadQuery& er) {
                // Handle any query errors
Z
update  
zhiru 已提交
231
                ENGINE_LOG_ERROR << "QUERY ERROR DURING INITIALIZATION" << ": " << er.what();
232
                return Status::DBTransactionError("QUERY ERROR DURING INITIALIZATION", er.what());
Z
update  
zhiru 已提交
233 234
            } catch (const Exception& er) {
                // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
235
                ENGINE_LOG_ERROR << "GENERAL ERROR DURING INITIALIZATION" << ": " << er.what();
236
                return Status::DBTransactionError("GENERAL ERROR DURING INITIALIZATION", er.what());
Z
zhiru 已提交
237 238
            } catch (std::exception &e) {
                return HandleException("Encounter exception during initialization", e);
Z
update  
zhiru 已提交
239 240 241
            }
        }
        else {
Z
zhiru 已提交
242
            ENGINE_LOG_ERROR << "Wrong URI format. URI = " << uri;
Z
update  
zhiru 已提交
243 244 245 246 247 248 249
            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 已提交
250

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

253
        if (dates.empty()) {
254 255 256 257 258 259 260 261 262 263
            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 已提交
264
        try {
265

Z
update  
zhiru 已提交
266
            auto yesterday = GetDateWithDelta(-1);
267

Z
update  
zhiru 已提交
268 269 270 271 272
            for (auto &date : dates) {
                if (date >= yesterday) {
                    return Status::Error("Could not delete partitions within 2 days");
                }
            }
273 274 275

            std::stringstream dateListSS;
            for (auto &date : dates) {
276
                dateListSS << std::to_string(date) << ", ";
277 278 279 280
            }
            std::string dateListStr = dateListSS.str();
            dateListStr = dateListStr.substr(0, dateListStr.size() - 2); //remove the last ", "

281 282
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
283

284 285 286 287 288 289 290 291 292 293 294 295 296
                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 << ");";

                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
297 298 299

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
300
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DROPPING PARTITIONS BY DATES" << ": " << er.what();
301 302 303
            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 已提交
304
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DROPPING PARTITIONS BY DATES" << ": " << er.what();
305 306
            return Status::DBTransactionError("GENERAL ERROR WHEN DROPPING PARTITIONS BY DATES", er.what());
        }
Z
update  
zhiru 已提交
307 308 309 310
        return Status::OK();
    }

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

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

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

            MetricCollector metric;

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

322 323 324 325 326 327 328
                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 已提交
329
//                    ENGINE_LOG_DEBUG << "Create Table : " << createTableQuery.str();
330 331 332 333 334 335 336 337 338 339
                    StoreQueryResult res = createTableQuery.store();
                    assert(res && res.num_rows() <= 1);
                    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);
                    }
340
                }
Z
zhiru 已提交
341
//                ENGINE_LOG_DEBUG << "Create Table start";
342

343 344 345
                table_schema.files_cnt_ = 0;
                table_schema.id_ = -1;
                table_schema.created_on_ = utils::GetMicroSecTimeStamp();
Z
update  
zhiru 已提交
346 347 348

//            auto start_time = METRICS_NOW_TIME;

349 350 351 352 353 354 355 356 357 358 359 360
                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 已提交
361
//                ENGINE_LOG_DEBUG << "Create Table : " << createTableQuery.str();
362 363
                if (SimpleResult res = createTableQuery.execute()) {
                    table_schema.id_ = res.insert_id(); //Might need to use SELECT LAST_INSERT_ID()?
Z
update  
zhiru 已提交
364
//                    std::cout << table_schema.id_ << std::endl;
365
                    //Consume all results to avoid "Commands out of sync" error
Z
update  
zhiru 已提交
366 367 368
//                while (createTableQuery.more_results()) {
//                    createTableQuery.store_next();
//                }
369 370 371 372 373
                } else {
                    ENGINE_LOG_ERROR << "Add Table Error";
                    return Status::DBTransactionError("Add Table Error", createTableQuery.error());
                }
            } //Scoped Connection
Z
update  
zhiru 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386

//        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");
                }
387
            }
Z
update  
zhiru 已提交
388 389
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
390
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN ADDING TABLE" << ": " << er.what();
Z
update  
zhiru 已提交
391 392 393
            return Status::DBTransactionError("QUERY ERROR WHEN ADDING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
394
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN ADDING TABLE" << ": " << er.what();
Z
update  
zhiru 已提交
395
            return Status::DBTransactionError("GENERAL ERROR WHEN ADDING TABLE", er.what());
Z
zhiru 已提交
396 397
        } catch (std::exception &e) {
            return HandleException("Encounter exception when create table", e);
398
        }
Z
update  
zhiru 已提交
399 400 401 402 403

        return Status::OK();
    }

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

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

407
        try {
Z
update  
zhiru 已提交
408 409 410

            MetricCollector metric;

411 412
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
413

414 415
                //soft delete table
                Query deleteTableQuery = connectionPtr->query();
Z
update  
zhiru 已提交
416
//
417 418 419
                deleteTableQuery << "UPDATE Tables " <<
                                    "SET state = " << std::to_string(TableSchema::TO_DELETE) << " " <<
                                    "WHERE table_id = " << quote << table_id << ";";
Z
update  
zhiru 已提交
420

421 422 423 424 425 426
                if (!deleteTableQuery.exec()) {
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN DELETING TABLE";
                    return Status::DBTransactionError("QUERY ERROR WHEN DELETING TABLE", deleteTableQuery.error());
                }

            } //Scoped Connection
427 428
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
429
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DELETING TABLE" << ": " << er.what();
430 431 432
            return Status::DBTransactionError("QUERY ERROR WHEN DELETING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
433
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DELETING TABLE" << ": " << er.what();
434 435
            return Status::DBTransactionError("GENERAL ERROR WHEN DELETING TABLE", er.what());
        }
Z
update  
zhiru 已提交
436 437 438 439 440 441 442 443

        return Status::OK();
    }

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

444 445
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
update  
zhiru 已提交
446

447 448 449 450
                //soft delete table files
                Query deleteTableFilesQuery = connectionPtr->query();
                //
                deleteTableFilesQuery << "UPDATE TableFiles " <<
Z
update  
zhiru 已提交
451
                                      "SET file_type = " << std::to_string(TableSchema::TO_DELETE) << ", " <<
452
                                      "updated_time = " << std::to_string(utils::GetMicroSecTimeStamp()) << " " <<
Z
update  
zhiru 已提交
453 454
                                      "WHERE table_id = " << quote << table_id << " AND " <<
                                      "file_type <> " << std::to_string(TableSchema::TO_DELETE) << ";";
455 456 457 458 459 460

                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 已提交
461 462
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
463
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DELETING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
464 465 466
            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 已提交
467
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DELETING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
468 469 470 471
            return Status::DBTransactionError("GENERAL ERROR WHEN DELETING TABLE FILES", er.what());
        }

        return Status::OK();
Z
update  
zhiru 已提交
472 473 474
    }

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

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

478
        try {
Z
update  
zhiru 已提交
479 480

            MetricCollector metric;
481

482 483 484 485
            StoreQueryResult res;

            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
486

487 488 489 490 491 492 493
                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) << ";";
                res = describeTableQuery.store();
            } //Scoped Connection
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517

            assert(res && res.num_rows() <= 1);
            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"];

                table_schema.store_raw_data_ = (resRow["store_raw_data"].compare("true") == 0);
            }
            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 已提交
518
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DESCRIBING TABLE" << ": " << er.what();
519 520 521
            return Status::DBTransactionError("QUERY ERROR WHEN DESCRIBING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
522
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DESCRIBING TABLE" << ": " << er.what();
523 524
            return Status::DBTransactionError("GENERAL ERROR WHEN DESCRIBING TABLE", er.what());
        }
Z
update  
zhiru 已提交
525 526 527 528 529

        return Status::OK();
    }

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

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

533
        try {
Z
update  
zhiru 已提交
534 535 536

            MetricCollector metric;

537 538 539 540
            StoreQueryResult res;

            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
541

542 543 544 545 546 547 548 549 550
                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" << ";";
                res = hasTableQuery.store();
            } //Scoped Connection
551 552 553 554 555 556 557

            assert(res && res.num_rows() == 1);
            int check = res[0]["check"];
            has_or_not = (check == 1);

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
558
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN CHECKING IF TABLE EXISTS" << ": " << er.what();
559 560 561
            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 已提交
562
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN CHECKING IF TABLE EXISTS" << ": " << er.what();
563 564 565
            return Status::DBTransactionError("GENERAL ERROR WHEN CHECKING IF TABLE EXISTS", er.what());
        }

Z
update  
zhiru 已提交
566 567 568 569
        return Status::OK();
    }

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

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

573
        try {
Z
update  
zhiru 已提交
574 575

            MetricCollector metric;
576

577 578 579 580
            StoreQueryResult res;

            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
581

582 583 584 585 586 587
                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) << ";";
                res = allTablesQuery.store();
            } //Scoped Connection
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609

            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"];

                table_schema.store_raw_data_ = (resRow["store_raw_data"].compare("true") == 0);

                table_schema_array.emplace_back(table_schema);
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
610
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DESCRIBING ALL TABLES" << ": " << er.what();
611 612 613
            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 已提交
614
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DESCRIBING ALL TABLES" << ": " << er.what();
615 616
            return Status::DBTransactionError("GENERAL ERROR WHEN DESCRIBING ALL TABLES", er.what());
        }
Z
update  
zhiru 已提交
617 618 619 620 621

        return Status::OK();
    }

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

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

625 626 627 628 629 630 631 632 633 634
        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 已提交
635
        try {
636

Z
update  
zhiru 已提交
637
            MetricCollector metric;
638

Z
update  
zhiru 已提交
639 640 641 642 643 644 645 646
            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);
647

Z
update  
zhiru 已提交
648 649 650 651 652 653 654 655 656
            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_);
657

658 659
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
660

661
                Query createTableFileQuery = connectionPtr->query();
662

663 664 665 666 667 668 669 670 671
                createTableFileQuery << "INSERT INTO TableFiles VALUES" <<
                                     "(" << id << ", " << quote << table_id << ", " << engine_type << ", " <<
                                     quote << file_id << ", " << file_type << ", " << size << ", " <<
                                     updated_time << ", " << created_on << ", " << date << ");";

                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 已提交
672 673 674
//                while (createTableFileQuery.more_results()) {
//                    createTableFileQuery.store_next();
//                }
675 676 677 678 679
                } else {
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN ADDING TABLE FILE";
                    return Status::DBTransactionError("Add file Error", createTableFileQuery.error());
                }
            } // Scoped Connection
680

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

Z
update  
zhiru 已提交
683 684 685 686 687 688
            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");
                }
689
            }
Z
update  
zhiru 已提交
690 691 692

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
693
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN ADDING TABLE FILE" << ": " << er.what();
Z
update  
zhiru 已提交
694 695 696
            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 已提交
697
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN ADDING TABLE FILE" << ": " << er.what();
Z
update  
zhiru 已提交
698
            return Status::DBTransactionError("GENERAL ERROR WHEN ADDING TABLE FILE", er.what());
Z
zhiru 已提交
699 700
        } catch (std::exception& ex) {
            return HandleException("Encounter exception when create table file", ex);
701
        }
Z
update  
zhiru 已提交
702 703 704 705 706

        return Status::OK();
    }

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

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

710 711 712
        files.clear();

        try {
Z
update  
zhiru 已提交
713 714

            MetricCollector metric;
715

716 717 718 719
            StoreQueryResult res;

            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
720

721 722 723 724 725 726
                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) << ";";
                res = filesToIndexQuery.store();
            } //Scoped Connection
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768

            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 已提交
769
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN FINDING TABLE FILES TO INDEX" << ": " << er.what();
770 771 772
            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 已提交
773
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN FINDING TABLE FILES TO INDEX" << ": " << er.what();
774 775
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO INDEX", er.what());
        }
Z
update  
zhiru 已提交
776 777 778 779 780 781 782

        return Status::OK();
    }

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

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

786 787 788
        files.clear();

        try {
Z
update  
zhiru 已提交
789 790

            MetricCollector metric;
791 792 793

            StoreQueryResult res;

794 795
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
796

797
                if (partition.empty()) {
798

799 800 801 802 803 804 805 806
                    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) << ");";
                    res = filesToSearchQuery.store();
807

808
                } else {
809

810
                    Query filesToSearchQuery = connectionPtr->query();
811

812 813 814 815 816 817 818 819 820
                    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 已提交
821 822 823 824 825
                                       "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) << ");";
826
                    res = filesToSearchQuery.store();
827

828 829
                }
            } //Scoped Connection
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871

            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 已提交
872
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN FINDING TABLE FILES TO SEARCH" << ": " << er.what();
873 874 875
            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 已提交
876
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN FINDING TABLE FILES TO SEARCH" << ": " << er.what();
877 878
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO SEARCH", er.what());
        }
Z
update  
zhiru 已提交
879 880 881 882 883 884

        return Status::OK();
    }

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

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

888 889 890
        files.clear();

        try {
Z
update  
zhiru 已提交
891
            MetricCollector metric;
892

893
            StoreQueryResult res;
Z
zhiru 已提交
894

895 896 897 898 899 900 901 902 903 904 905
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

                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" << ";";
                res = filesToMergeQuery.store();
            } //Scoped Connection
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947

            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 已提交
948
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN FINDING TABLE FILES TO MERGE" << ": " << er.what();
949 950 951
            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 已提交
952
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN FINDING TABLE FILES TO MERGE" << ": " << er.what();
953 954
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO MERGE", er.what());
        }
Z
update  
zhiru 已提交
955 956 957 958

        return Status::OK();
    }

Z
update  
zhiru 已提交
959 960 961
    Status MySQLMetaImpl::GetTableFiles(const std::string& table_id,
                                        const std::vector<size_t>& ids,
                                        TableFilesSchema& table_files) {
Z
update  
zhiru 已提交
962

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

Z
fix  
zhiru 已提交
965 966 967 968
        if (ids.empty()) {
            return Status::OK();
        }

Z
update  
zhiru 已提交
969 970 971 972 973 974 975
        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 "

976 977
        try {

978 979 980 981
            StoreQueryResult res;

            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
982

983 984 985 986 987 988 989
                Query getTableFileQuery = connectionPtr->query();
                getTableFileQuery << "SELECT engine_type, file_id, file_type, size, date " <<
                                  "FROM TableFiles " <<
                                  "WHERE table_id = " << quote << table_id << " AND " <<
                                  "(" << idStr << ");";
                res = getTableFileQuery.store();
            } //Scoped Connection
990

Z
update  
zhiru 已提交
991
            assert(res);
992

Z
update  
zhiru 已提交
993 994 995 996 997 998
            TableSchema table_schema;
            table_schema.table_id_ = table_id;
            auto status = DescribeTable(table_schema);
            if (!status.ok()) {
                return status;
            }
999

Z
update  
zhiru 已提交
1000 1001 1002
            for (auto& resRow : res) {

                TableFileSchema file_schema;
1003 1004 1005

                file_schema.table_id_ = table_id;

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

1008 1009 1010 1011 1012 1013 1014 1015 1016
                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 已提交
1017 1018 1019 1020 1021 1022

                file_schema.dimension_ = table_schema.dimension_;

                GetTableFilePath(file_schema);

                table_files.emplace_back(file_schema);
1023 1024 1025
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1026
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN RETRIEVING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
1027
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING TABLE FILES", er.what());
1028 1029
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1030
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN RETRIEVING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
1031
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING TABLE FILES", er.what());
1032
        }
Z
update  
zhiru 已提交
1033 1034 1035 1036 1037 1038

        return Status::OK();
    }

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

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

1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
        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 已提交
1053

1054 1055
                try {

Z
zhiru 已提交
1056 1057
                    ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

1058
                    Query archiveQuery = connectionPtr->query();
1059
                    archiveQuery << "UPDATE TableFiles " <<
1060 1061 1062 1063 1064 1065 1066 1067 1068
                                    "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) << ";";
                    if (!archiveQuery.exec()) {
                        return Status::DBTransactionError("QUERY ERROR DURING ARCHIVE", archiveQuery.error());
                    }

                } catch (const BadQuery& er) {
                    // Handle any query errors
Z
update  
zhiru 已提交
1069
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN DURING ARCHIVE" << ": " << er.what();
1070 1071 1072
                    return Status::DBTransactionError("QUERY ERROR WHEN DURING ARCHIVE", er.what());
                } catch (const Exception& er) {
                    // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1073
                    ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DURING ARCHIVE" << ": " << er.what();
1074 1075 1076 1077 1078 1079 1080
                    return Status::DBTransactionError("GENERAL ERROR WHEN DURING ARCHIVE", er.what());
                }
            }
            if (criteria == "disk") {
                uint64_t sum = 0;
                Size(sum);

Z
update  
zhiru 已提交
1081
                auto to_delete = (sum - limit * G);
1082 1083 1084
                DiscardFiles(to_delete);
            }
        }
Z
update  
zhiru 已提交
1085 1086 1087 1088 1089

        return Status::OK();
    }

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

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

1093 1094 1095
        result = 0;
        try {

1096 1097 1098 1099
            StoreQueryResult res;

            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
1100

1101 1102 1103 1104 1105 1106
                Query getSizeQuery = connectionPtr->query();
                getSizeQuery << "SELECT SUM(size) AS sum " <<
                             "FROM TableFiles " <<
                             "WHERE file_type <> " << std::to_string(TableFileSchema::TO_DELETE) << ";";
                res = getSizeQuery.store();
            } //Scoped Connection
1107 1108

            assert(res && res.num_rows() == 1);
Z
zhiru 已提交
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
//            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;
            }
1121 1122 1123

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1124
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN RETRIEVING SIZE" << ": " << er.what();
1125 1126 1127
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING SIZE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1128
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN RETRIEVING SIZE" << ": " << er.what();
1129 1130
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING SIZE", er.what());
        }
Z
update  
zhiru 已提交
1131 1132 1133 1134

        return Status::OK();
    }

Z
zhiru 已提交
1135 1136
    Status MySQLMetaImpl::DiscardFiles(long long to_discard_size) {

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

1139 1140 1141 1142
        if (to_discard_size <= 0) {
//            std::cout << "in" << std::endl;
            return Status::OK();
        }
Z
update  
zhiru 已提交
1143 1144
        ENGINE_LOG_DEBUG << "About to discard size=" << to_discard_size;

1145 1146
        try {

Z
update  
zhiru 已提交
1147 1148
            MetricCollector metric;

1149 1150 1151 1152
            bool status;

            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
1153

1154 1155 1156 1157 1158 1159
                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;";
1160
//            std::cout << discardFilesQuery.str() << std::endl;
1161
                StoreQueryResult res = discardFilesQuery.store();
1162

1163 1164 1165 1166
                assert(res);
                if (res.num_rows() == 0) {
                    return Status::OK();
                }
1167

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
                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_;
1180 1181
                }

1182 1183
                std::string idsToDiscardStr = idsToDiscardSS.str();
                idsToDiscardStr = idsToDiscardStr.substr(0, idsToDiscardStr.size() - 4); //remove the last " OR "
1184

1185 1186 1187 1188
                discardFilesQuery << "UPDATE TableFiles " <<
                                  "SET file_type = " << std::to_string(TableFileSchema::TO_DELETE) << ", " <<
                                  "updated_time = " << std::to_string(utils::GetMicroSecTimeStamp()) << " " <<
                                  "WHERE " << idsToDiscardStr << ";";
1189

1190 1191 1192 1193 1194 1195 1196 1197
                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);
1198 1199 1200

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1201
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DISCARDING FILES" << ": " << er.what();
1202 1203 1204
            return Status::DBTransactionError("QUERY ERROR WHEN DISCARDING FILES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1205
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DISCARDING FILES" << ": " << er.what();
1206 1207
            return Status::DBTransactionError("GENERAL ERROR WHEN DISCARDING FILES", er.what());
        }
Z
update  
zhiru 已提交
1208 1209
    }

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

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

1215 1216
        file_schema.updated_time_ = utils::GetMicroSecTimeStamp();
        try {
Z
update  
zhiru 已提交
1217 1218

            MetricCollector metric;
1219

1220 1221
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
1222

1223
                Query updateTableFileQuery = connectionPtr->query();
1224

1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
                //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_ << ";";
                StoreQueryResult res = updateTableFileQuery.store();

                assert(res && res.num_rows() <= 1);
                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 已提交
1238 1239 1240
                    file_schema.file_type_ = TableFileSchema::TO_DELETE;
                }

1241 1242 1243 1244 1245 1246 1247 1248 1249
                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_);
1250

1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
                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 << ";";
1261 1262 1263

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

1264 1265 1266 1267 1268 1269 1270
                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
1271 1272 1273 1274

        } 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 已提交
1275
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN UPDATING TABLE FILE" << ": " << er.what();
1276 1277 1278 1279
            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 已提交
1280
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN UPDATING TABLE FILE" << ": " << er.what();
1281 1282
            return Status::DBTransactionError("GENERAL ERROR WHEN UPDATING TABLE FILE", er.what());
        }
Z
update  
zhiru 已提交
1283 1284 1285 1286
        return Status::OK();
    }

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

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

1290
        try {
Z
update  
zhiru 已提交
1291
            MetricCollector metric;
1292

1293 1294
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
update  
zhiru 已提交
1295

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

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

1301 1302 1303
                    if (has_tables.find(file_schema.table_id_) != has_tables.end()) {
                        continue;
                    }
Z
update  
zhiru 已提交
1304

1305 1306 1307 1308 1309 1310
                    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" << ";";
                    StoreQueryResult res = updateTableFilesQuery.store();
1311

1312 1313 1314
                    assert(res && res.num_rows() == 1);
                    int check = res[0]["check"];
                    has_tables[file_schema.table_id_] = (check == 1);
Z
update  
zhiru 已提交
1315 1316
                }

1317
                for (auto &file_schema : files) {
1318

1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351
                    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 << ";";

                    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
1352 1353 1354

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1355
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN UPDATING TABLE FILES" << ": " << er.what();
1356 1357 1358
            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 已提交
1359
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN UPDATING TABLE FILES" << ": " << er.what();
1360 1361
            return Status::DBTransactionError("GENERAL ERROR WHEN UPDATING TABLE FILES", er.what());
        }
Z
update  
zhiru 已提交
1362 1363 1364 1365
        return Status::OK();
    }

    Status MySQLMetaImpl::CleanUpFilesWithTTL(uint16_t seconds) {
Z
zhiru 已提交
1366 1367 1368 1369
//        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 已提交
1370

1371 1372
        auto now = utils::GetMicroSecTimeStamp();
        try {
Z
update  
zhiru 已提交
1373
            MetricCollector metric;
1374

1375 1376
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
1377

1378 1379 1380 1381 1382 1383
                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) << ";";
                StoreQueryResult res = cleanUpFilesWithTTLQuery.store();
1384

1385
                assert(res);
1386

1387 1388
                TableFileSchema table_file;
                std::vector<std::string> idsToDelete;
1389

1390
                for (auto &resRow : res) {
1391

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

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

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

1402
                    table_file.date_ = resRow["date"];
1403

1404
                    GetTableFilePath(table_file);
1405

1406 1407 1408
                    ENGINE_LOG_DEBUG << "Removing deleted id =" << table_file.id_ << " location = "
                                     << table_file.location_ << std::endl;
                    boost::filesystem::remove(table_file.location_);
1409

1410 1411
                    idsToDelete.emplace_back(std::to_string(table_file.id_));
                }
1412

Z
fix  
zhiru 已提交
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
                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 << ";";
                    if (!cleanUpFilesWithTTLQuery.exec()) {
                        ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES WITH TTL";
                        return Status::DBTransactionError("CleanUpFilesWithTTL Error",
                                                          cleanUpFilesWithTTLQuery.error());
                    }
1429 1430
                }
            } //Scoped Connection
1431 1432 1433

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1434
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES WITH TTL" << ": " << er.what();
1435 1436 1437
            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 已提交
1438
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN CLEANING UP FILES WITH TTL" << ": " << er.what();
1439 1440
            return Status::DBTransactionError("GENERAL ERROR WHEN CLEANING UP FILES WITH TTL", er.what());
        }
Z
update  
zhiru 已提交
1441

1442
        try {
Z
update  
zhiru 已提交
1443
            MetricCollector metric;
1444

1445 1446
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
1447

1448 1449 1450 1451 1452 1453
                Query cleanUpFilesWithTTLQuery = connectionPtr->query();
                cleanUpFilesWithTTLQuery << "SELECT id, table_id " <<
                                         "FROM Tables " <<
                                         "WHERE state = " << std::to_string(TableSchema::TO_DELETE) << ";";
                StoreQueryResult res = cleanUpFilesWithTTLQuery.store();
                assert(res);
Z
zhiru 已提交
1454
//            std::cout << res.num_rows() << std::endl;
1455

Z
fix  
zhiru 已提交
1456
                if (!res.empty()) {
1457

Z
fix  
zhiru 已提交
1458 1459 1460 1461 1462
                    std::stringstream idsToDeleteSS;
                    for (auto &resRow : res) {
                        size_t id = resRow["id"];
                        std::string table_id;
                        resRow["table_id"].to_string(table_id);
1463

Z
fix  
zhiru 已提交
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
                        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 << ";";
                    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());
                    }
1480
                }
Z
fix  
zhiru 已提交
1481
           } //Scoped Connection
1482

Z
update  
zhiru 已提交
1483 1484
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1485
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES WITH TTL" << ": " << er.what();
Z
update  
zhiru 已提交
1486 1487 1488
            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 已提交
1489
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN CLEANING UP FILES WITH TTL" << ": " << er.what();
Z
update  
zhiru 已提交
1490 1491
            return Status::DBTransactionError("GENERAL ERROR WHEN CLEANING UP FILES WITH TTL", er.what());
        }
1492

Z
update  
zhiru 已提交
1493 1494
        return Status::OK();
    }
1495

Z
update  
zhiru 已提交
1496 1497
    Status MySQLMetaImpl::CleanUp() {

Z
zhiru 已提交
1498
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
update  
zhiru 已提交
1499 1500

        try {
Z
zhiru 已提交
1501 1502
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

Z
update  
zhiru 已提交
1503 1504
            ENGINE_LOG_DEBUG << "Remove table file type as NEW";
            Query cleanUpQuery = connectionPtr->query();
1505
            cleanUpQuery << "DELETE FROM TableFiles WHERE file_type = " << std::to_string(TableFileSchema::NEW) << ";";
1506 1507

            if (!cleanUpQuery.exec()) {
Z
update  
zhiru 已提交
1508
                ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES";
1509 1510 1511 1512 1513
                return Status::DBTransactionError("Clean up Error", cleanUpQuery.error());
            }

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1514
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES" << ": " << er.what();
1515 1516 1517
            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 已提交
1518
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN CLEANING UP FILES" << ": " << er.what();
1519 1520
            return Status::DBTransactionError("GENERAL ERROR WHEN CLEANING UP FILES", er.what());
        }
Z
update  
zhiru 已提交
1521 1522 1523 1524 1525 1526

        return Status::OK();
    }

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

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

1529
        try {
Z
update  
zhiru 已提交
1530
            MetricCollector metric;
1531 1532 1533 1534 1535 1536 1537 1538 1539

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

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

1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554
            StoreQueryResult res;

            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

                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) << ");";
                res = countQuery.store();
            } //Scoped Connection

1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
            result = 0;
            for (auto &resRow : res) {
                size_t size = resRow["size"];
                result += size;
            }

            assert(table_schema.dimension_ != 0);
            result /= table_schema.dimension_;
            result /= sizeof(float);

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1567
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN RETRIEVING COUNT" << ": " << er.what();
1568 1569 1570
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING COUNT", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1571
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN RETRIEVING COUNT" << ": " << er.what();
1572 1573
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING COUNT", er.what());
        }
Z
update  
zhiru 已提交
1574 1575 1576 1577
        return Status::OK();
    }

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

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

1581 1582 1583 1584
        if (boost::filesystem::is_directory(options_.path)) {
            boost::filesystem::remove_all(options_.path);
        }
        try {
Z
zhiru 已提交
1585 1586 1587

            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

1588
            Query dropTableQuery = connectionPtr->query();
1589
            dropTableQuery << "DROP TABLE IF EXISTS Tables, TableFiles;";
1590 1591 1592 1593
            if (dropTableQuery.exec()) {
                return Status::OK();
            }
            else {
Z
update  
zhiru 已提交
1594
                ENGINE_LOG_ERROR << "QUERY ERROR WHEN DROPPING TABLE";
1595 1596 1597 1598
                return Status::DBTransactionError("DROP TABLE ERROR", dropTableQuery.error());
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1599
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DROPPING TABLE" << ": " << er.what();
1600 1601 1602
            return Status::DBTransactionError("QUERY ERROR WHEN DROPPING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1603
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DROPPING TABLE" << ": " << er.what();
1604 1605
            return Status::DBTransactionError("GENERAL ERROR WHEN DROPPING TABLE", er.what());
        }
Z
zhiru 已提交
1606
        return Status::OK();
Z
update  
zhiru 已提交
1607 1608 1609
    }

    MySQLMetaImpl::~MySQLMetaImpl() {
Z
zhiru 已提交
1610
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
update  
zhiru 已提交
1611 1612 1613 1614 1615 1616 1617
        CleanUp();
    }

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