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

                CleanUp();
                Query InitializeQuery = connectionPtr->query();

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

180 181 182 183
//                InitializeQuery << "DROP TABLE IF EXISTS meta, metaFile;";
                InitializeQuery << "CREATE TABLE IF NOT EXISTS meta (" <<
                                    "id BIGINT PRIMARY KEY AUTO_INCREMENT, " <<
                                    "table_id VARCHAR(255) UNIQUE NOT NULL, " <<
Z
update  
zhiru 已提交
184
                                    "state INT NOT NULL, " <<
185 186 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);";
                if (!InitializeQuery.exec()) {
                    return Status::DBTransactionError("Initialization Error", InitializeQuery.error());
Z
update  
zhiru 已提交
192
                }
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207

                InitializeQuery << "CREATE TABLE IF NOT EXISTS metaFile (" <<
                                   "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());
                }

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

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

247 248 249 250 251 252 253 254 255 256 257
        if (dates.size() == 0) {
            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 已提交
258
        try {
259

Z
zhiru 已提交
260 261
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

Z
update  
zhiru 已提交
262
            auto yesterday = GetDateWithDelta(-1);
263

Z
update  
zhiru 已提交
264 265 266 267 268
            for (auto &date : dates) {
                if (date >= yesterday) {
                    return Status::Error("Could not delete partitions within 2 days");
                }
            }
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

            Query dropPartitionsByDatesQuery = connectionPtr->query();

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

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

            if (!dropPartitionsByDatesQuery.exec()) {
                return Status::DBTransactionError("QUERY ERROR WHEN DROPPING PARTITIONS BY DATES", dropPartitionsByDatesQuery.error());
            }

        } catch (const BadQuery& er) {
            // Handle any query errors
            return Status::DBTransactionError("QUERY ERROR WHEN DROPPING PARTITIONS BY DATES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN DROPPING PARTITIONS BY DATES", er.what());
        }
Z
update  
zhiru 已提交
295 296 297 298
        return Status::OK();
    }

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

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

Z
update  
zhiru 已提交
302 303 304 305 306
//        server::Metrics::GetInstance().MetaAccessTotalIncrement();
        try {

            MetricCollector metric;

Z
zhiru 已提交
307 308
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

Z
update  
zhiru 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321
            Query createTableQuery = connectionPtr->query();

            if (table_schema.table_id_.empty()) {
                NextTableId(table_schema.table_id_);
            }
            else {
                createTableQuery << "SELECT state FROM meta " <<
                                    "WHERE table_id = " << quote << table_schema.table_id_ << ";";
                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) ?
Z
zhiru 已提交
322
                                      "Table already exists and it is in delete state, please wait a second" : "Table already exists";
Z
update  
zhiru 已提交
323
                    return Status::Error(msg);
324
                }
Z
update  
zhiru 已提交
325
            }
326

Z
update  
zhiru 已提交
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
            table_schema.files_cnt_ = 0;
            table_schema.id_ = -1;
            table_schema.created_on_ = utils::GetMicroSecTimeStamp();

//            auto start_time = METRICS_NOW_TIME;

            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 meta VALUES" <<
                                "(" << id << ", " << quote << table_id << ", " << state << ", " << dimension << ", " <<
                                created_on << ", " << files_cnt << ", " << engine_type << ", " << store_raw_data
                                << ");";

            if (SimpleResult res = createTableQuery.execute()) {
                table_schema.id_ = res.insert_id(); //Might need to use SELECT LAST_INSERT_ID()?
//                    std::cout << table_schema.id_ << std::endl;
                //Consume all results to avoid "Commands out of sync" error
//                while (createTableQuery.more_results()) {
//                    createTableQuery.store_next();
//                }
354
            }
Z
update  
zhiru 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
            else {
                return Status::DBTransactionError("Add Table Error", createTableQuery.error());
            }

//        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");
                }
371
            }
Z
update  
zhiru 已提交
372 373 374 375 376 377
        } catch (const BadQuery& er) {
            // Handle any query errors
            return Status::DBTransactionError("QUERY ERROR WHEN ADDING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN ADDING TABLE", er.what());
Z
zhiru 已提交
378 379
        } catch (std::exception &e) {
            return HandleException("Encounter exception when create table", e);
380
        }
Z
update  
zhiru 已提交
381 382 383 384 385

        return Status::OK();
    }

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

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

389
        try {
Z
update  
zhiru 已提交
390 391 392

            MetricCollector metric;

Z
zhiru 已提交
393 394
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

Z
update  
zhiru 已提交
395
            //soft delete table
396
            Query deleteTableQuery = connectionPtr->query();
Z
update  
zhiru 已提交
397 398 399 400 401 402 403
//
            deleteTableQuery << "UPDATE meta " <<
                                "SET state = " << std::to_string(TableSchema::TO_DELETE) << " " <<
                                "WHERE table_id = " << quote << table_id << ";";

            if (!deleteTableQuery.exec()) {
                return Status::DBTransactionError("QUERY ERROR WHEN DELETING TABLE", deleteTableQuery.error());
404 405 406 407 408 409 410 411
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
            return Status::DBTransactionError("QUERY ERROR WHEN DELETING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN DELETING TABLE", er.what());
        }
Z
update  
zhiru 已提交
412 413 414 415 416 417 418 419

        return Status::OK();
    }

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

Z
zhiru 已提交
420 421
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

Z
update  
zhiru 已提交
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
            //soft delete table files
            Query deleteTableFilesQuery = connectionPtr->query();
    //
            deleteTableFilesQuery << "UPDATE metaFile " <<
                                     "SET state = " << std::to_string(TableSchema::TO_DELETE) << ", " <<
                                     "updated_time = " << std::to_string(utils::GetMicroSecTimeStamp()) << " "
                                     "WHERE table_id = " << quote << table_id << ";";

            if (!deleteTableFilesQuery.exec()) {
                return Status::DBTransactionError("QUERY ERROR WHEN DELETING TABLE", deleteTableFilesQuery.error());
            }

        } catch (const BadQuery& er) {
            // Handle any query errors
            return Status::DBTransactionError("QUERY ERROR WHEN DELETING TABLE FILES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN DELETING TABLE FILES", er.what());
        }

        return Status::OK();
Z
update  
zhiru 已提交
443 444 445
    }

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

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

449
        try {
Z
update  
zhiru 已提交
450 451

            MetricCollector metric;
452

Z
zhiru 已提交
453 454
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

455
            Query describeTableQuery = connectionPtr->query();
Z
update  
zhiru 已提交
456
            describeTableQuery << "SELECT id, dimension, files_cnt, engine_type, store_raw_data " <<
457
                                  "FROM meta " <<
Z
update  
zhiru 已提交
458 459
                                  "WHERE table_id = " << quote << table_schema.table_id_ << " " <<
                                  "AND state <> " << std::to_string(TableSchema::TO_DELETE) << ";";
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
            StoreQueryResult res = describeTableQuery.store();

            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
            return Status::DBTransactionError("QUERY ERROR WHEN DESCRIBING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN DESCRIBING TABLE", er.what());
        }
Z
update  
zhiru 已提交
490 491 492 493 494

        return Status::OK();
    }

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

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

498
        try {
Z
update  
zhiru 已提交
499 500 501

            MetricCollector metric;

Z
zhiru 已提交
502
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
503 504 505

            Query hasTableQuery = connectionPtr->query();
            //since table_id is a unique column we just need to check whether it exists or not
Z
update  
zhiru 已提交
506 507 508 509 510
            hasTableQuery << "SELECT EXISTS " <<
                             "(SELECT 1 FROM meta " <<
                             "WHERE table_id = " << quote << table_id << " " <<
                             "AND state <> " << std::to_string(TableSchema::TO_DELETE) << ") " <<
                             "AS " << quote << "check" << ";";
511 512 513 514 515 516 517 518 519 520 521 522 523 524
            StoreQueryResult res = hasTableQuery.store();

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

        } catch (const BadQuery& er) {
            // Handle any query errors
            return Status::DBTransactionError("QUERY ERROR WHEN CHECKING IF TABLE EXISTS", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN CHECKING IF TABLE EXISTS", er.what());
        }

Z
update  
zhiru 已提交
525 526 527 528
        return Status::OK();
    }

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

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

532
        try {
Z
update  
zhiru 已提交
533 534

            MetricCollector metric;
535

Z
zhiru 已提交
536 537
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

538 539
            Query allTablesQuery = connectionPtr->query();
            allTablesQuery << "SELECT id, table_id, dimension, files_cnt, engine_type, store_raw_data " <<
Z
update  
zhiru 已提交
540 541
                              "FROM meta " <<
                              "WHERE state <> " << std::to_string(TableSchema::TO_DELETE) << ";";
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
            StoreQueryResult res = allTablesQuery.store();

            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
            return Status::DBTransactionError("QUERY ERROR WHEN DESCRIBING ALL TABLES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN DESCRIBING ALL TABLES", er.what());
        }
Z
update  
zhiru 已提交
570 571 572 573 574

        return Status::OK();
    }

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

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

578 579 580 581 582 583 584 585 586 587
        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 已提交
588
        try {
589

Z
update  
zhiru 已提交
590
            MetricCollector metric;
591

Z
zhiru 已提交
592 593
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

Z
update  
zhiru 已提交
594 595 596 597 598 599 600 601
            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);
602

Z
update  
zhiru 已提交
603 604 605 606 607 608 609 610 611 612
            Query createTableFileQuery = connectionPtr->query();
            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_);
613

Z
update  
zhiru 已提交
614 615 616 617
            createTableFileQuery << "INSERT INTO metaFile VALUES" <<
                                    "(" << id << ", " << quote << table_id << ", " << engine_type << ", " <<
                                    quote << file_id << ", " << file_type << ", " << size << ", " <<
                                    updated_time << ", " << created_on << ", " << date << ");";
Z
zhiru 已提交
618

Z
update  
zhiru 已提交
619 620
            if (SimpleResult res = createTableFileQuery.execute()) {
                file_schema.id_ = res.insert_id(); //Might need to use SELECT LAST_INSERT_ID()?
621

Z
update  
zhiru 已提交
622 623 624 625 626 627 628
                //Consume all results to avoid "Commands out of sync" error
//                while (createTableFileQuery.more_results()) {
//                    createTableFileQuery.store_next();
//                }
            }
            else {
                return Status::DBTransactionError("Add file Error", createTableFileQuery.error());
629 630
            }

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

Z
update  
zhiru 已提交
633 634 635 636 637 638
            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");
                }
639
            }
Z
update  
zhiru 已提交
640 641 642 643 644 645 646

        } catch (const BadQuery& er) {
            // Handle any query errors
            return Status::DBTransactionError("QUERY ERROR WHEN ADDING TABLE FILE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN ADDING TABLE FILE", er.what());
Z
zhiru 已提交
647 648
        } catch (std::exception& ex) {
            return HandleException("Encounter exception when create table file", ex);
649
        }
Z
update  
zhiru 已提交
650 651 652 653 654

        return Status::OK();
    }

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

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

658 659 660
        files.clear();

        try {
Z
update  
zhiru 已提交
661 662

            MetricCollector metric;
663

Z
zhiru 已提交
664 665
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
            Query filesToIndexQuery = connectionPtr->query();
            filesToIndexQuery << "SELECT id, table_id, engine_type, file_id, file_type, size, date " <<
                                 "FROM metaFile " <<
                                 "WHERE file_type = " << std::to_string(TableFileSchema::TO_INDEX) << ";";
            StoreQueryResult res = filesToIndexQuery.store();

            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
            return Status::DBTransactionError("QUERY ERROR WHEN FINDING TABLE FILES TO INDEX", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO INDEX", er.what());
        }
Z
update  
zhiru 已提交
718 719 720 721 722 723 724

        return Status::OK();
    }

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

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

728 729 730
        files.clear();

        try {
Z
update  
zhiru 已提交
731 732

            MetricCollector metric;
733

Z
zhiru 已提交
734 735
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

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
            StoreQueryResult res;

            if (partition.empty()) {

                Query filesToSearchQuery = connectionPtr->query();
                filesToSearchQuery << "SELECT id, table_id, engine_type, file_id, file_type, size, date " <<
                                      "FROM metaFile " <<
                                      "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();

            }
            else {

                Query filesToSearchQuery = connectionPtr->query();

                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 " <<
Z
update  
zhiru 已提交
762 763 764 765 766 767
                                       "FROM metaFile " <<
                                       "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) << ");";
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
                res = filesToSearchQuery.store();

            }

            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
            return Status::DBTransactionError("QUERY ERROR WHEN FINDING TABLE FILES TO SEARCH", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO SEARCH", er.what());
        }
Z
update  
zhiru 已提交
818 819 820 821 822 823

        return Status::OK();
    }

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

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

827 828 829
        files.clear();

        try {
Z
update  
zhiru 已提交
830
            MetricCollector metric;
831

Z
zhiru 已提交
832 833
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

834 835 836 837
            Query filesToMergeQuery = connectionPtr->query();
            filesToMergeQuery << "SELECT id, table_id, file_id, file_type, size, date " <<
                                 "FROM metaFile " <<
                                 "WHERE table_id = " << quote << table_id << " AND " <<
Z
update  
zhiru 已提交
838 839
                                 "file_type = " << std::to_string(TableFileSchema::RAW) << " " <<
                                 "ORDER BY size DESC" << ";";
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 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
            StoreQueryResult res = filesToMergeQuery.store();

            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
            return Status::DBTransactionError("QUERY ERROR WHEN FINDING TABLE FILES TO MERGE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO MERGE", er.what());
        }
Z
update  
zhiru 已提交
888 889 890 891

        return Status::OK();
    }

Z
update  
zhiru 已提交
892 893 894
    Status MySQLMetaImpl::GetTableFiles(const std::string& table_id,
                                        const std::vector<size_t>& ids,
                                        TableFilesSchema& table_files) {
Z
update  
zhiru 已提交
895

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

Z
update  
zhiru 已提交
898 899 900 901 902 903 904
        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 "

905 906
        try {

Z
zhiru 已提交
907 908
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

909
            Query getTableFileQuery = connectionPtr->query();
Z
update  
zhiru 已提交
910
            getTableFileQuery << "SELECT engine_type, file_id, file_type, size, date " <<
911
                                 "FROM metaFile " <<
Z
update  
zhiru 已提交
912 913
                                 "WHERE table_id = " << quote << table_id << " AND " <<
                                 "(" << idStr << ");";
914 915
            StoreQueryResult res = getTableFileQuery.store();

Z
update  
zhiru 已提交
916
            assert(res);
917

Z
update  
zhiru 已提交
918 919 920 921 922 923
            TableSchema table_schema;
            table_schema.table_id_ = table_id;
            auto status = DescribeTable(table_schema);
            if (!status.ok()) {
                return status;
            }
924

Z
update  
zhiru 已提交
925 926 927
            for (auto& resRow : res) {

                TableFileSchema file_schema;
928 929 930

                file_schema.table_id_ = table_id;

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

933 934 935 936 937 938 939 940 941
                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 已提交
942 943 944 945 946 947

                file_schema.dimension_ = table_schema.dimension_;

                GetTableFilePath(file_schema);

                table_files.emplace_back(file_schema);
948 949 950
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
951
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING TABLE FILES", er.what());
952 953
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
954
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING TABLE FILES", er.what());
955
        }
Z
update  
zhiru 已提交
956 957 958 959 960 961

        return Status::OK();
    }

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

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

965 966 967 968 969 970 971 972 973 974 975
        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 已提交
976

977 978
                try {

Z
zhiru 已提交
979 980
                    ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
                    Query archiveQuery = connectionPtr->query();
                    archiveQuery << "UPDATE metaFile " <<
                                    "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
                    return Status::DBTransactionError("QUERY ERROR WHEN DURING ARCHIVE", er.what());
                } catch (const Exception& er) {
                    // Catch-all for any other MySQL++ exceptions
                    return Status::DBTransactionError("GENERAL ERROR WHEN DURING ARCHIVE", er.what());
                }
            }
            if (criteria == "disk") {
                uint64_t sum = 0;
                Size(sum);

Z
update  
zhiru 已提交
1002
                auto to_delete = (sum - limit * G);
1003 1004 1005
                DiscardFiles(to_delete);
            }
        }
Z
update  
zhiru 已提交
1006 1007 1008 1009 1010

        return Status::OK();
    }

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

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

1014 1015 1016
        result = 0;
        try {

Z
zhiru 已提交
1017 1018
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

1019 1020 1021 1022 1023 1024 1025
            Query getSizeQuery = connectionPtr->query();
            getSizeQuery << "SELECT SUM(size) AS sum " <<
                            "FROM metaFile " <<
                            "WHERE file_type <> " << std::to_string(TableFileSchema::TO_DELETE) << ";";
            StoreQueryResult res = getSizeQuery.store();

            assert(res && res.num_rows() == 1);
Z
zhiru 已提交
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
//            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;
            }
1038 1039 1040 1041 1042 1043 1044 1045

        } catch (const BadQuery& er) {
            // Handle any query errors
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING SIZE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING SIZE", er.what());
        }
Z
update  
zhiru 已提交
1046 1047 1048 1049

        return Status::OK();
    }

Z
zhiru 已提交
1050 1051
    Status MySQLMetaImpl::DiscardFiles(long long to_discard_size) {

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

1054 1055 1056 1057
        if (to_discard_size <= 0) {
//            std::cout << "in" << std::endl;
            return Status::OK();
        }
Z
update  
zhiru 已提交
1058 1059
        ENGINE_LOG_DEBUG << "About to discard size=" << to_discard_size;

1060 1061
        try {

Z
update  
zhiru 已提交
1062 1063
            MetricCollector metric;

Z
zhiru 已提交
1064 1065
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
            Query discardFilesQuery = connectionPtr->query();
            discardFilesQuery << "SELECT id, size " <<
                                 "FROM metaFile " <<
                                 "WHERE file_type <> " << std::to_string(TableFileSchema::TO_DELETE) << " " <<
                                 "ORDER BY id ASC " <<
                                 "LIMIT 10;";
//            std::cout << discardFilesQuery.str() << std::endl;
            StoreQueryResult res = discardFilesQuery.store();

            assert(res);
            if (res.num_rows() == 0) {
                return Status::OK();
            }

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

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

            discardFilesQuery << "UPDATE metaFile " <<
Z
update  
zhiru 已提交
1098 1099
                                 "SET file_type = " << std::to_string(TableFileSchema::TO_DELETE) << ", " <<
                                 "updated_time = " << std::to_string(utils::GetMicroSecTimeStamp()) << " " <<
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
                                 "WHERE " << idsToDiscardStr << ";";

            if (discardFilesQuery.exec()) {
                return DiscardFiles(to_discard_size);
            }
            else {
                return Status::DBTransactionError("QUERY ERROR WHEN DISCARDING FILES", discardFilesQuery.error());
            }

        } catch (const BadQuery& er) {
            // Handle any query errors
            return Status::DBTransactionError("QUERY ERROR WHEN DISCARDING FILES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN DISCARDING FILES", er.what());
        }
Z
update  
zhiru 已提交
1116 1117
    }

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

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

1123 1124
        file_schema.updated_time_ = utils::GetMicroSecTimeStamp();
        try {
Z
update  
zhiru 已提交
1125 1126

            MetricCollector metric;
1127

Z
zhiru 已提交
1128 1129
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

1130 1131
            Query updateTableFileQuery = connectionPtr->query();

Z
update  
zhiru 已提交
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
            //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 meta " <<
                                    "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 {
                file_schema.file_type_ = TableFileSchema::TO_DELETE;
            }

1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
            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_);

            updateTableFileQuery << "UPDATE metaFile " <<
                                    "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 << ";";

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

            if (!updateTableFileQuery.exec()) {
                ENGINE_LOG_DEBUG << "table_id= " << file_schema.table_id_ << " file_id=" << file_schema.file_id_;
                return Status::DBTransactionError("QUERY ERROR WHEN UPDATING TABLE FILE", updateTableFileQuery.error());
            }

        } catch (const BadQuery& er) {
            // Handle any query errors
            ENGINE_LOG_DEBUG << "table_id= " << file_schema.table_id_ << " file_id=" << file_schema.file_id_;
            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_;
            return Status::DBTransactionError("GENERAL ERROR WHEN UPDATING TABLE FILE", er.what());
        }
Z
update  
zhiru 已提交
1185 1186 1187 1188
        return Status::OK();
    }

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

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

1192
        try {
Z
update  
zhiru 已提交
1193
            MetricCollector metric;
1194

Z
zhiru 已提交
1195 1196
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

1197 1198
            Query updateTableFilesQuery = connectionPtr->query();

Z
update  
zhiru 已提交
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
            std::map<std::string, bool> has_tables;
            for (auto &file_schema : files) {

                if(has_tables.find(file_schema.table_id_) != has_tables.end()) {
                    continue;
                }

                updateTableFilesQuery << "SELECT EXISTS " <<
                                         "(SELECT 1 FROM meta " <<
                                         "WHERE table_id = " << quote << file_schema.table_id_ << " " <<
                                         "AND state <> " << std::to_string(TableSchema::TO_DELETE) << ") " <<
                                         "AS " << quote << "check" << ";";
                StoreQueryResult res = updateTableFilesQuery.store();

                assert(res && res.num_rows() == 1);
                int check = res[0]["check"];
                has_tables[file_schema.table_id_] = (check == 1);
            }

1218 1219
            for (auto& file_schema : files) {

Z
update  
zhiru 已提交
1220 1221 1222 1223 1224
                if(!has_tables[file_schema.table_id_]) {
                    file_schema.file_type_ = TableFileSchema::TO_DELETE;
                }
                file_schema.updated_time_ = utils::GetMicroSecTimeStamp();

1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258
                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 metaFile " <<
                                         "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()) {
                return Status::DBTransactionError("QUERY ERROR WHEN UPDATING TABLE FILES", updateTableFilesQuery.error());
            }

        } catch (const BadQuery& er) {
            // Handle any query errors
            return Status::DBTransactionError("QUERY ERROR WHEN UPDATING TABLE FILES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN UPDATING TABLE FILES", er.what());
        }
Z
update  
zhiru 已提交
1259 1260 1261 1262
        return Status::OK();
    }

    Status MySQLMetaImpl::CleanUpFilesWithTTL(uint16_t seconds) {
Z
zhiru 已提交
1263 1264 1265 1266
//        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 已提交
1267

1268 1269
        auto now = utils::GetMicroSecTimeStamp();
        try {
Z
update  
zhiru 已提交
1270
            MetricCollector metric;
1271

Z
zhiru 已提交
1272 1273
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

1274
            Query cleanUpFilesWithTTLQuery = connectionPtr->query();
Z
update  
zhiru 已提交
1275
            cleanUpFilesWithTTLQuery << "SELECT id, table_id, file_id, date " <<
1276 1277
                                        "FROM metaFile " <<
                                        "WHERE file_type = " << std::to_string(TableFileSchema::TO_DELETE) << " AND " <<
Z
update  
zhiru 已提交
1278
                                        "updated_time < " << std::to_string(now - seconds * US_PS) << ";";
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
            StoreQueryResult res = cleanUpFilesWithTTLQuery.store();

            assert(res);

            TableFileSchema table_file;
            std::vector<std::string> idsToDelete;

            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;

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

                table_file.date_ = resRow["date"];

                GetTableFilePath(table_file);

Z
update  
zhiru 已提交
1302 1303
                ENGINE_LOG_DEBUG << "Removing deleted id =" << table_file.id_ << " location = " << table_file.location_ << std::endl;
                boost::filesystem::remove(table_file.location_);
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326

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

            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 metaFile WHERE " <<
                                        idsToDeleteStr << ";";
            if (!cleanUpFilesWithTTLQuery.exec()) {
                return Status::DBTransactionError("CleanUpFilesWithTTL Error", cleanUpFilesWithTTLQuery.error());
            }

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

1328
        try {
Z
update  
zhiru 已提交
1329
            MetricCollector metric;
1330

Z
zhiru 已提交
1331 1332
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

Z
update  
zhiru 已提交
1333 1334 1335 1336 1337
            Query cleanUpFilesWithTTLQuery = connectionPtr->query();
            cleanUpFilesWithTTLQuery << "SELECT id, table_id " <<
                                        "FROM meta " <<
                                        "WHERE state = " << std::to_string(TableSchema::TO_DELETE) << ";";
            StoreQueryResult res = cleanUpFilesWithTTLQuery.store();
1338
            assert(res);
Z
zhiru 已提交
1339
//            std::cout << res.num_rows() << std::endl;
Z
update  
zhiru 已提交
1340
            std::stringstream idsToDeleteSS;
1341
            for (auto& resRow : res) {
Z
update  
zhiru 已提交
1342
                size_t id = resRow["id"];
1343 1344 1345
                std::string table_id;
                resRow["table_id"].to_string(table_id);

Z
update  
zhiru 已提交
1346
                auto table_path = GetTablePath(table_id);
1347

Z
update  
zhiru 已提交
1348 1349
                ENGINE_LOG_DEBUG << "Remove table folder: " << table_path;
                boost::filesystem::remove_all(table_path);
1350

Z
update  
zhiru 已提交
1351 1352 1353 1354 1355 1356 1357 1358 1359
                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 meta WHERE " <<
                                        idsToDeleteStr << ";";
            if (!cleanUpFilesWithTTLQuery.exec()) {
                return Status::DBTransactionError("QUERY ERROR WHEN CLEANING UP FILES WITH TTL", cleanUpFilesWithTTLQuery.error());
            }
1360 1361


Z
update  
zhiru 已提交
1362 1363 1364 1365 1366 1367 1368
        } catch (const BadQuery& er) {
            // Handle any query errors
            return Status::DBTransactionError("QUERY ERROR WHEN CLEANING UP FILES WITH TTL", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN CLEANING UP FILES WITH TTL", er.what());
        }
1369

Z
update  
zhiru 已提交
1370 1371
        return Status::OK();
    }
1372

Z
update  
zhiru 已提交
1373 1374
    Status MySQLMetaImpl::CleanUp() {

Z
zhiru 已提交
1375
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
update  
zhiru 已提交
1376 1377

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

Z
update  
zhiru 已提交
1380 1381 1382
            ENGINE_LOG_DEBUG << "Remove table file type as NEW";
            Query cleanUpQuery = connectionPtr->query();
            cleanUpQuery << "DELETE FROM metaFile WHERE file_type = " << std::to_string(TableFileSchema::NEW) << ";";
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394

            if (!cleanUpQuery.exec()) {
                return Status::DBTransactionError("Clean up Error", cleanUpQuery.error());
            }

        } catch (const BadQuery& er) {
            // Handle any query errors
            return Status::DBTransactionError("QUERY ERROR WHEN CLEANING UP FILES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN CLEANING UP FILES", er.what());
        }
Z
update  
zhiru 已提交
1395 1396 1397 1398 1399 1400

        return Status::OK();
    }

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

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

1403
        try {
Z
update  
zhiru 已提交
1404
            MetricCollector metric;
1405

Z
zhiru 已提交
1406 1407
            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
            Query countQuery = connectionPtr->query();
            countQuery << "SELECT size " <<
                          "FROM metaFile " <<
                          "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) << ");";
            StoreQueryResult res = countQuery.store();

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

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

            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
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING COUNT", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING COUNT", er.what());
        }
Z
update  
zhiru 已提交
1442 1443 1444 1445
        return Status::OK();
    }

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

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

1449 1450 1451 1452
        if (boost::filesystem::is_directory(options_.path)) {
            boost::filesystem::remove_all(options_.path);
        }
        try {
Z
zhiru 已提交
1453 1454 1455

            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
            Query dropTableQuery = connectionPtr->query();
            dropTableQuery << "DROP TABLE IF EXISTS meta, metaFile;";
            if (dropTableQuery.exec()) {
                return Status::OK();
            }
            else {
                return Status::DBTransactionError("DROP TABLE ERROR", dropTableQuery.error());
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
            return Status::DBTransactionError("QUERY ERROR WHEN DROPPING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            return Status::DBTransactionError("GENERAL ERROR WHEN DROPPING TABLE", er.what());
        }
Z
zhiru 已提交
1471
        return Status::OK();
Z
update  
zhiru 已提交
1472 1473 1474
    }

    MySQLMetaImpl::~MySQLMetaImpl() {
Z
zhiru 已提交
1475
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
update  
zhiru 已提交
1476 1477 1478 1479 1480 1481 1482
        CleanUp();
    }

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