MySQLMetaImpl.cpp 57.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
update  
zhiru 已提交
23 24 25 26 27 28 29 30 31 32

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

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

    using namespace mysqlpp;

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

    namespace {

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

Z
update  
zhiru 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
        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 已提交
67 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
    }

    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_) {
107
        Initialize();
Z
update  
zhiru 已提交
108 109 110
    }

    Status MySQLMetaImpl::Initialize() {
111

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

Z
update  
zhiru 已提交
114 115
        if (!boost::filesystem::is_directory(options_.path)) {
            auto ret = boost::filesystem::create_directory(options_.path);
116
            if (!ret) {
Z
update  
zhiru 已提交
117 118
                ENGINE_LOG_ERROR << "Failed to create db directory " << options_.path;
                return Status::DBTransactionError("Failed to create db directory", options_.path);
119 120
            }
        }
Z
update  
zhiru 已提交
121 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

        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;
154
//            connectionPtr->set_option(new MultiStatementsOption(true));
Z
zhiru 已提交
155 156 157
//            connectionPtr->set_option(new mysqlpp::ReconnectOption(true));
            connectionPtr->set_option(new mysqlpp::ReconnectOption(true));
            std::cout << "MySQL++ thread aware:" << std::to_string(connectionPtr->thread_aware()) << std::endl;
Z
update  
zhiru 已提交
158 159 160 161 162 163 164 165 166

            try {
                if (!connectionPtr->connect(dbName, serverAddress, username, password, port)) {
                    return Status::Error("DB connection failed: ", connectionPtr->error());
                }

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

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

172 173 174 175
//                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 已提交
176
                                    "state INT NOT NULL, " <<
177 178 179 180 181 182 183
                                    "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 已提交
184
                }
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

                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 已提交
200 201 202 203
//                //Consume all results to avoid "Commands out of sync" error
//                while (InitializeQuery.more_results()) {
//                    InitializeQuery.store_next();
//                }
204 205 206 207 208 209 210 211 212 213 214
                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 已提交
215
            } catch (const ConnectionFailed& er) {
216
                return Status::DBTransactionError("Failed to connect to database server", er.what());
Z
update  
zhiru 已提交
217 218
            } catch (const BadQuery& er) {
                // Handle any query errors
219
                return Status::DBTransactionError("QUERY ERROR DURING INITIALIZATION", er.what());
Z
update  
zhiru 已提交
220 221
            } catch (const Exception& er) {
                // Catch-all for any other MySQL++ exceptions
222
                return Status::DBTransactionError("GENERAL ERROR DURING INITIALIZATION", er.what());
Z
update  
zhiru 已提交
223 224 225 226 227 228 229 230 231 232
            }
        }
        else {
            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 已提交
233 234 235

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

236 237 238 239 240 241 242 243 244 245 246
        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 已提交
247
        try {
248

Z
update  
zhiru 已提交
249
            auto yesterday = GetDateWithDelta(-1);
250

Z
update  
zhiru 已提交
251 252 253 254 255
            for (auto &date : dates) {
                if (date >= yesterday) {
                    return Status::Error("Could not delete partitions within 2 days");
                }
            }
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281

            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 已提交
282 283 284 285
        return Status::OK();
    }

    Status MySQLMetaImpl::CreateTable(TableSchema &table_schema) {
Z
zhiru 已提交
286 287 288

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

Z
update  
zhiru 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
//        server::Metrics::GetInstance().MetaAccessTotalIncrement();
        try {

            MetricCollector metric;

            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) ?
                                      "Table already exists" : "Table already exists and it is in delete state, please wait a second";
                    return Status::Error(msg);
309
                }
Z
update  
zhiru 已提交
310
            }
311

Z
update  
zhiru 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
            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();
//                }
339
            }
Z
update  
zhiru 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
            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");
                }
356
            }
Z
update  
zhiru 已提交
357 358 359 360 361 362
        } 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());
363
        }
Z
update  
zhiru 已提交
364 365 366 367 368

        return Status::OK();
    }

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

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

372
        try {
Z
update  
zhiru 已提交
373 374 375 376

            MetricCollector metric;

            //soft delete table
377
            Query deleteTableQuery = connectionPtr->query();
Z
update  
zhiru 已提交
378 379 380 381 382 383 384
//
            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());
385 386 387 388 389 390 391 392
            }
        } 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 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

        return Status::OK();
    }

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

            //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 已提交
422 423 424
    }

    Status MySQLMetaImpl::DescribeTable(TableSchema &table_schema) {
Z
zhiru 已提交
425 426 427

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

428
        try {
Z
update  
zhiru 已提交
429 430

            MetricCollector metric;
431 432

            Query describeTableQuery = connectionPtr->query();
Z
update  
zhiru 已提交
433
            describeTableQuery << "SELECT id, dimension, files_cnt, engine_type, store_raw_data " <<
434
                                  "FROM meta " <<
Z
update  
zhiru 已提交
435 436
                                  "WHERE table_id = " << quote << table_schema.table_id_ << " " <<
                                  "AND state <> " << std::to_string(TableSchema::TO_DELETE) << ";";
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
            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 已提交
467 468 469 470 471

        return Status::OK();
    }

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

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

475
        try {
Z
update  
zhiru 已提交
476 477 478 479

            MetricCollector metric;


480 481 482

            Query hasTableQuery = connectionPtr->query();
            //since table_id is a unique column we just need to check whether it exists or not
Z
update  
zhiru 已提交
483 484 485 486 487
            hasTableQuery << "SELECT EXISTS " <<
                             "(SELECT 1 FROM meta " <<
                             "WHERE table_id = " << quote << table_id << " " <<
                             "AND state <> " << std::to_string(TableSchema::TO_DELETE) << ") " <<
                             "AS " << quote << "check" << ";";
488 489 490 491 492 493 494 495 496 497 498 499 500 501
            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 已提交
502 503 504 505
        return Status::OK();
    }

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

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

509
        try {
Z
update  
zhiru 已提交
510 511

            MetricCollector metric;
512 513 514

            Query allTablesQuery = connectionPtr->query();
            allTablesQuery << "SELECT id, table_id, dimension, files_cnt, engine_type, store_raw_data " <<
Z
update  
zhiru 已提交
515 516
                              "FROM meta " <<
                              "WHERE state <> " << std::to_string(TableSchema::TO_DELETE) << ";";
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
            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 已提交
545 546 547 548 549

        return Status::OK();
    }

    Status MySQLMetaImpl::CreateTableFile(TableFileSchema &file_schema) {
Z
zhiru 已提交
550 551 552

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

553 554 555 556 557 558 559 560 561 562
        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 已提交
563
        try {
564

Z
update  
zhiru 已提交
565
            MetricCollector metric;
566

Z
update  
zhiru 已提交
567 568 569 570 571 572 573 574
            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);
575

Z
update  
zhiru 已提交
576 577 578 579 580 581 582 583 584 585
            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_);
586

Z
update  
zhiru 已提交
587 588 589 590
            createTableFileQuery << "INSERT INTO metaFile VALUES" <<
                                    "(" << id << ", " << quote << table_id << ", " << engine_type << ", " <<
                                    quote << file_id << ", " << file_type << ", " << size << ", " <<
                                    updated_time << ", " << created_on << ", " << date << ");";
Z
zhiru 已提交
591

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

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

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

Z
update  
zhiru 已提交
606 607 608 609 610 611
            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");
                }
612
            }
Z
update  
zhiru 已提交
613 614 615 616 617 618 619

        } 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());
620
        }
Z
update  
zhiru 已提交
621 622 623 624 625

        return Status::OK();
    }

    Status MySQLMetaImpl::FilesToIndex(TableFilesSchema &files) {
Z
zhiru 已提交
626 627 628

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

629 630 631
        files.clear();

        try {
Z
update  
zhiru 已提交
632 633

            MetricCollector metric;
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686

            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 已提交
687 688 689 690 691 692 693

        return Status::OK();
    }

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

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

697 698 699
        files.clear();

        try {
Z
update  
zhiru 已提交
700 701

            MetricCollector metric;
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728

            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 已提交
729 730 731 732 733 734
                                       "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) << ");";
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 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
                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 已提交
785 786 787 788 789 790

        return Status::OK();
    }

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

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

794 795 796
        files.clear();

        try {
Z
update  
zhiru 已提交
797
            MetricCollector metric;
798 799 800 801 802

            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 已提交
803 804
                                 "file_type = " << std::to_string(TableFileSchema::RAW) << " " <<
                                 "ORDER BY size DESC" << ";";
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
            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 已提交
853 854 855 856

        return Status::OK();
    }

Z
update  
zhiru 已提交
857 858 859
    Status MySQLMetaImpl::GetTableFiles(const std::string& table_id,
                                        const std::vector<size_t>& ids,
                                        TableFilesSchema& table_files) {
Z
update  
zhiru 已提交
860

Z
zhiru 已提交
861 862
        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

Z
update  
zhiru 已提交
863 864 865 866 867 868 869
        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 "

870 871 872
        try {

            Query getTableFileQuery = connectionPtr->query();
Z
update  
zhiru 已提交
873
            getTableFileQuery << "SELECT engine_type, file_id, file_type, size, date " <<
874
                                 "FROM metaFile " <<
Z
update  
zhiru 已提交
875 876
                                 "WHERE table_id = " << quote << table_id << " AND " <<
                                 "(" << idStr << ");";
877 878
            StoreQueryResult res = getTableFileQuery.store();

Z
update  
zhiru 已提交
879
            assert(res);
880

Z
update  
zhiru 已提交
881 882 883 884 885 886
            TableSchema table_schema;
            table_schema.table_id_ = table_id;
            auto status = DescribeTable(table_schema);
            if (!status.ok()) {
                return status;
            }
887

Z
update  
zhiru 已提交
888 889 890
            for (auto& resRow : res) {

                TableFileSchema file_schema;
891 892 893

                file_schema.table_id_ = table_id;

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

896 897 898 899 900 901 902 903 904
                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 已提交
905 906 907 908 909 910

                file_schema.dimension_ = table_schema.dimension_;

                GetTableFilePath(file_schema);

                table_files.emplace_back(file_schema);
911 912 913
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
914
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING TABLE FILES", er.what());
915 916
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
917
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING TABLE FILES", er.what());
918
        }
Z
update  
zhiru 已提交
919 920 921 922 923 924

        return Status::OK();
    }

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

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
        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();
                try {

                    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 已提交
962
                auto to_delete = (sum - limit * G);
963 964 965
                DiscardFiles(to_delete);
            }
        }
Z
update  
zhiru 已提交
966 967 968 969 970

        return Status::OK();
    }

    Status MySQLMetaImpl::Size(uint64_t &result) {
Z
zhiru 已提交
971 972 973

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

974 975 976 977 978 979 980 981 982 983
        result = 0;
        try {

            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 已提交
984 985 986 987 988 989 990 991 992 993 994 995
//            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;
            }
996 997 998 999 1000 1001 1002 1003

        } 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 已提交
1004 1005 1006 1007

        return Status::OK();
    }

Z
zhiru 已提交
1008 1009 1010 1011
    Status MySQLMetaImpl::DiscardFiles(long long to_discard_size) {

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

1012 1013 1014 1015
        if (to_discard_size <= 0) {
//            std::cout << "in" << std::endl;
            return Status::OK();
        }
Z
update  
zhiru 已提交
1016 1017
        ENGINE_LOG_DEBUG << "About to discard size=" << to_discard_size;

1018 1019
        try {

Z
update  
zhiru 已提交
1020 1021
            MetricCollector metric;

1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
            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 已提交
1054 1055
                                 "SET file_type = " << std::to_string(TableFileSchema::TO_DELETE) << ", " <<
                                 "updated_time = " << std::to_string(utils::GetMicroSecTimeStamp()) << " " <<
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
                                 "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 已提交
1072 1073
    }

1074
    //ZR: this function assumes all fields in file_schema have value
Z
update  
zhiru 已提交
1075
    Status MySQLMetaImpl::UpdateTableFile(TableFileSchema &file_schema) {
Z
zhiru 已提交
1076 1077 1078

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

1079 1080
        file_schema.updated_time_ = utils::GetMicroSecTimeStamp();
        try {
Z
update  
zhiru 已提交
1081 1082

            MetricCollector metric;
1083 1084 1085

            Query updateTableFileQuery = connectionPtr->query();

Z
update  
zhiru 已提交
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
            //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;
            }

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
            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 已提交
1139 1140 1141 1142
        return Status::OK();
    }

    Status MySQLMetaImpl::UpdateTableFiles(TableFilesSchema &files) {
Z
zhiru 已提交
1143 1144 1145

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

1146
        try {
Z
update  
zhiru 已提交
1147
            MetricCollector metric;
1148 1149 1150

            Query updateTableFilesQuery = connectionPtr->query();

Z
update  
zhiru 已提交
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
            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);
            }

1170 1171
            for (auto& file_schema : files) {

Z
update  
zhiru 已提交
1172 1173 1174 1175 1176
                if(!has_tables[file_schema.table_id_]) {
                    file_schema.file_type_ = TableFileSchema::TO_DELETE;
                }
                file_schema.updated_time_ = utils::GetMicroSecTimeStamp();

1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
                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 已提交
1211 1212 1213 1214
        return Status::OK();
    }

    Status MySQLMetaImpl::CleanUpFilesWithTTL(uint16_t seconds) {
Z
zhiru 已提交
1215 1216 1217

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

1218 1219
        auto now = utils::GetMicroSecTimeStamp();
        try {
Z
update  
zhiru 已提交
1220
            MetricCollector metric;
1221 1222

            Query cleanUpFilesWithTTLQuery = connectionPtr->query();
Z
update  
zhiru 已提交
1223
            cleanUpFilesWithTTLQuery << "SELECT id, table_id, file_id, date " <<
1224 1225
                                        "FROM metaFile " <<
                                        "WHERE file_type = " << std::to_string(TableFileSchema::TO_DELETE) << " AND " <<
Z
update  
zhiru 已提交
1226
                                        "updated_time < " << std::to_string(now - seconds * US_PS) << ";";
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
            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 已提交
1250 1251
                ENGINE_LOG_DEBUG << "Removing deleted id =" << table_file.id_ << " location = " << table_file.location_ << std::endl;
                boost::filesystem::remove(table_file.location_);
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274

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

1276
        try {
Z
update  
zhiru 已提交
1277
            MetricCollector metric;
1278

Z
update  
zhiru 已提交
1279 1280 1281 1282 1283
            Query cleanUpFilesWithTTLQuery = connectionPtr->query();
            cleanUpFilesWithTTLQuery << "SELECT id, table_id " <<
                                        "FROM meta " <<
                                        "WHERE state = " << std::to_string(TableSchema::TO_DELETE) << ";";
            StoreQueryResult res = cleanUpFilesWithTTLQuery.store();
1284
            assert(res);
Z
update  
zhiru 已提交
1285
            std::stringstream idsToDeleteSS;
1286
            for (auto& resRow : res) {
Z
update  
zhiru 已提交
1287
                size_t id = resRow["id"];
1288 1289 1290
                std::string table_id;
                resRow["table_id"].to_string(table_id);

Z
update  
zhiru 已提交
1291
                auto table_path = GetTablePath(table_id);
1292

Z
update  
zhiru 已提交
1293 1294
                ENGINE_LOG_DEBUG << "Remove table folder: " << table_path;
                boost::filesystem::remove_all(table_path);
1295

Z
update  
zhiru 已提交
1296 1297 1298 1299 1300 1301 1302 1303 1304
                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());
            }
1305 1306


Z
update  
zhiru 已提交
1307 1308 1309 1310 1311 1312 1313
        } 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());
        }
1314

Z
update  
zhiru 已提交
1315 1316
        return Status::OK();
    }
1317

Z
update  
zhiru 已提交
1318 1319 1320 1321 1322 1323 1324 1325
    Status MySQLMetaImpl::CleanUp() {

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

        try {
            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) << ";";
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337

            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 已提交
1338 1339 1340 1341 1342 1343

        return Status::OK();
    }

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

Z
zhiru 已提交
1344 1345
        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

1346
        try {
Z
update  
zhiru 已提交
1347
            MetricCollector metric;
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382

            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 已提交
1383 1384 1385 1386
        return Status::OK();
    }

    Status MySQLMetaImpl::DropAll() {
Z
zhiru 已提交
1387 1388 1389

        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);

1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
        if (boost::filesystem::is_directory(options_.path)) {
            boost::filesystem::remove_all(options_.path);
        }
        try {
            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
update  
zhiru 已提交
1409 1410 1411
    }

    MySQLMetaImpl::~MySQLMetaImpl() {
Z
zhiru 已提交
1412
        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
update  
zhiru 已提交
1413 1414 1415 1416 1417 1418 1419
        CleanUp();
    }

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