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

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

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

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

    using namespace mysqlpp;

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

    namespace {

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

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

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

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

Z
update  
zhiru 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
    }

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

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

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

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

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

Z
update  
zhiru 已提交
106 107 108
    MySQLMetaImpl::MySQLMetaImpl(const DBMetaOptions &options_, const std::string& mode)
            : options_(options_),
              mode_(mode) {
109
        Initialize();
Z
update  
zhiru 已提交
110 111 112
    }

    Status MySQLMetaImpl::Initialize() {
113

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

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

        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;
156
//            connectionPtr->set_option(new MultiStatementsOption(true));
Z
zhiru 已提交
157
//            connectionPtr->set_option(new mysqlpp::ReconnectOption(true));
Z
zhiru 已提交
158 159 160 161
            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 已提交
162
            ENGINE_LOG_DEBUG << "MySQL connection pool: maximum pool size = " << std::to_string(maxPoolSize);
Z
update  
zhiru 已提交
163
            try {
164 165 166 167 168

                CleanUp();

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

//                    ENGINE_LOG_DEBUG << "MySQLMetaImpl::Initialize: connections in use = " << mySQLConnectionPool_->getConnectionsInUse();
Z
zhiru 已提交
171 172 173
//                if (!connectionPtr->connect(dbName, serverAddress, username, password, port)) {
//                    return Status::Error("DB connection failed: ", connectionPtr->error());
//                }
174 175 176 177 178
                    if (!connectionPtr->thread_aware()) {
                        ENGINE_LOG_ERROR << "MySQL++ wasn't built with thread awareness! Can't run without it.";
                        return Status::Error("MySQL++ wasn't built with thread awareness! Can't run without it.");
                    }
                    Query InitializeQuery = connectionPtr->query();
Z
update  
zhiru 已提交
179

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

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

199 200 201 202 203 204 205 206 207 208 209 210 211 212
                    InitializeQuery << "CREATE TABLE IF NOT EXISTS TableFiles (" <<
                                    "id BIGINT PRIMARY KEY AUTO_INCREMENT, " <<
                                    "table_id VARCHAR(255) NOT NULL, " <<
                                    "engine_type INT DEFAULT 1 NOT NULL, " <<
                                    "file_id VARCHAR(255) NOT NULL, " <<
                                    "file_type INT DEFAULT 0 NOT NULL, " <<
                                    "size BIGINT DEFAULT 0 NOT NULL, " <<
                                    "updated_time BIGINT NOT NULL, " <<
                                    "created_on BIGINT NOT NULL, " <<
                                    "date INT DEFAULT -1 NOT NULL);";
                    if (!InitializeQuery.exec()) {
                        return Status::DBTransactionError("Initialization Error", InitializeQuery.error());
                    }
                } //Scoped Connection
213

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

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

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

Z
update  
zhiru 已提交
269
            auto yesterday = GetDateWithDelta(-1);
270

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

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

284 285
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
286

Z
update  
zhiru 已提交
287 288 289 290
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DropPartitionsByDates connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

291 292 293 294 295 296 297 298 299 300 301 302 303
                Query dropPartitionsByDatesQuery = connectionPtr->query();

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

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

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

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

Z
update  
zhiru 已提交
320 321 322 323 324
//        server::Metrics::GetInstance().MetaAccessTotalIncrement();
        try {

            MetricCollector metric;

325 326
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
update  
zhiru 已提交
327

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

332
                Query createTableQuery = connectionPtr->query();
Z
update  
zhiru 已提交
333
//                ENGINE_LOG_DEBUG << "Create Table in";
334 335 336 337 338
                if (table_schema.table_id_.empty()) {
                    NextTableId(table_schema.table_id_);
                } else {
                    createTableQuery << "SELECT state FROM Tables " <<
                                        "WHERE table_id = " << quote << table_schema.table_id_ << ";";
Z
zhiru 已提交
339
//                    ENGINE_LOG_DEBUG << "Create Table : " << createTableQuery.str();
340 341 342 343
                    StoreQueryResult res = createTableQuery.store();
                    assert(res && res.num_rows() <= 1);
                    if (res.num_rows() == 1) {
                        int state = res[0]["state"];
Z
update  
zhiru 已提交
344 345 346 347 348 349
                        if (TableSchema::TO_DELETE == state) {
                            return Status::Error("Table already exists and it is in delete state, please wait a second");
                        }
                        else {
                            return Status::OK();//table already exists, no error
                        }
350
                    }
351
                }
Z
zhiru 已提交
352
//                ENGINE_LOG_DEBUG << "Create Table start";
353

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

//            auto start_time = METRICS_NOW_TIME;

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

                createTableQuery << "INSERT INTO Tables VALUES" <<
                                 "(" << id << ", " << quote << table_id << ", " << state << ", " << dimension << ", " <<
                                 created_on << ", " << files_cnt << ", " << engine_type << ", " << store_raw_data << ");";
Z
zhiru 已提交
372
//                ENGINE_LOG_DEBUG << "Create Table : " << createTableQuery.str();
373 374
                if (SimpleResult res = createTableQuery.execute()) {
                    table_schema.id_ = res.insert_id(); //Might need to use SELECT LAST_INSERT_ID()?
Z
update  
zhiru 已提交
375
//                    std::cout << table_schema.id_ << std::endl;
376
                    //Consume all results to avoid "Commands out of sync" error
Z
update  
zhiru 已提交
377 378 379
//                while (createTableQuery.more_results()) {
//                    createTableQuery.store_next();
//                }
380 381 382 383 384
                } else {
                    ENGINE_LOG_ERROR << "Add Table Error";
                    return Status::DBTransactionError("Add Table Error", createTableQuery.error());
                }
            } //Scoped Connection
Z
update  
zhiru 已提交
385 386 387 388 389 390 391 392 393 394 395 396 397

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

        return Status::OK();
    }

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

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

418
        try {
Z
update  
zhiru 已提交
419 420 421

            MetricCollector metric;

422 423
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
424

Z
update  
zhiru 已提交
425 426 427 428
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DeleteTable connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

429 430
                //soft delete table
                Query deleteTableQuery = connectionPtr->query();
Z
update  
zhiru 已提交
431
//
432 433 434
                deleteTableQuery << "UPDATE Tables " <<
                                    "SET state = " << std::to_string(TableSchema::TO_DELETE) << " " <<
                                    "WHERE table_id = " << quote << table_id << ";";
Z
update  
zhiru 已提交
435

436 437 438 439 440 441
                if (!deleteTableQuery.exec()) {
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN DELETING TABLE";
                    return Status::DBTransactionError("QUERY ERROR WHEN DELETING TABLE", deleteTableQuery.error());
                }

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

Z
update  
zhiru 已提交
443 444 445 446 447 448

//            ConfigNode& serverConfig = ServerConfig::GetInstance().GetConfig(CONFIG_SERVER);
//            opt.mode = serverConfig.GetValue(CONFIG_CLUSTER_MODE, "single");
            if (mode_ != "single") {
                DeleteTableFiles(table_id);
            }
Z
update  
zhiru 已提交
449

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

        return Status::OK();
    }

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

467 468
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
update  
zhiru 已提交
469

Z
update  
zhiru 已提交
470 471 472 473
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DeleteTableFiles connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

474 475 476 477
                //soft delete table files
                Query deleteTableFilesQuery = connectionPtr->query();
                //
                deleteTableFilesQuery << "UPDATE TableFiles " <<
Z
update  
zhiru 已提交
478
                                      "SET file_type = " << std::to_string(TableFileSchema::TO_DELETE) << ", " <<
479
                                      "updated_time = " << std::to_string(utils::GetMicroSecTimeStamp()) << " " <<
Z
update  
zhiru 已提交
480
                                      "WHERE table_id = " << quote << table_id << " AND " <<
Z
update  
zhiru 已提交
481
                                      "file_type <> " << std::to_string(TableFileSchema::TO_DELETE) << ";";
482 483 484 485 486 487

                if (!deleteTableFilesQuery.exec()) {
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN DELETING TABLE FILES";
                    return Status::DBTransactionError("QUERY ERROR WHEN DELETING TABLE", deleteTableFilesQuery.error());
                }
            } //Scoped Connection
Z
update  
zhiru 已提交
488 489
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
490
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DELETING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
491 492 493
            return Status::DBTransactionError("QUERY ERROR WHEN DELETING TABLE FILES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
494
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DELETING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
495 496 497 498
            return Status::DBTransactionError("GENERAL ERROR WHEN DELETING TABLE FILES", er.what());
        }

        return Status::OK();
Z
update  
zhiru 已提交
499 500 501
    }

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

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

505
        try {
Z
update  
zhiru 已提交
506 507

            MetricCollector metric;
508

509 510 511 512
            StoreQueryResult res;

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

Z
update  
zhiru 已提交
514 515 516 517
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DescribeTable connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

518 519 520 521 522 523 524
                Query describeTableQuery = connectionPtr->query();
                describeTableQuery << "SELECT id, dimension, files_cnt, engine_type, store_raw_data " <<
                                      "FROM Tables " <<
                                      "WHERE table_id = " << quote << table_schema.table_id_ << " " <<
                                      "AND state <> " << std::to_string(TableSchema::TO_DELETE) << ";";
                res = describeTableQuery.store();
            } //Scoped Connection
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548

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

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

                table_schema.dimension_ = resRow["dimension"];

                table_schema.files_cnt_ = resRow["files_cnt"];

                table_schema.engine_type_ = resRow["engine_type"];

                table_schema.store_raw_data_ = (resRow["store_raw_data"].compare("true") == 0);
            }
            else {
                return Status::NotFound("Table " + table_schema.table_id_ + " not found");
            }

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

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
549
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DESCRIBING TABLE" << ": " << er.what();
550 551 552
            return Status::DBTransactionError("QUERY ERROR WHEN DESCRIBING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
553
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DESCRIBING TABLE" << ": " << er.what();
554 555
            return Status::DBTransactionError("GENERAL ERROR WHEN DESCRIBING TABLE", er.what());
        }
Z
update  
zhiru 已提交
556 557 558 559 560

        return Status::OK();
    }

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

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

564
        try {
Z
update  
zhiru 已提交
565 566 567

            MetricCollector metric;

568 569 570 571
            StoreQueryResult res;

            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
572

Z
update  
zhiru 已提交
573 574 575 576
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::HasTable connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

577 578 579 580 581 582 583 584 585
                Query hasTableQuery = connectionPtr->query();
                //since table_id is a unique column we just need to check whether it exists or not
                hasTableQuery << "SELECT EXISTS " <<
                              "(SELECT 1 FROM Tables " <<
                              "WHERE table_id = " << quote << table_id << " " <<
                              "AND state <> " << std::to_string(TableSchema::TO_DELETE) << ") " <<
                              "AS " << quote << "check" << ";";
                res = hasTableQuery.store();
            } //Scoped Connection
586 587 588 589 590 591 592

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

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

Z
update  
zhiru 已提交
601 602 603 604
        return Status::OK();
    }

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

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

608
        try {
Z
update  
zhiru 已提交
609 610

            MetricCollector metric;
611

612 613 614 615
            StoreQueryResult res;

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

Z
update  
zhiru 已提交
617 618 619 620
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::AllTables connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

621 622 623 624 625 626
                Query allTablesQuery = connectionPtr->query();
                allTablesQuery << "SELECT id, table_id, dimension, files_cnt, engine_type, store_raw_data " <<
                               "FROM Tables " <<
                               "WHERE state <> " << std::to_string(TableSchema::TO_DELETE) << ";";
                res = allTablesQuery.store();
            } //Scoped Connection
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648

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

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

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

                table_schema.dimension_ = resRow["dimension"];

                table_schema.files_cnt_ = resRow["files_cnt"];

                table_schema.engine_type_ = resRow["engine_type"];

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

                table_schema_array.emplace_back(table_schema);
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
649
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DESCRIBING ALL TABLES" << ": " << er.what();
650 651 652
            return Status::DBTransactionError("QUERY ERROR WHEN DESCRIBING ALL TABLES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
653
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DESCRIBING ALL TABLES" << ": " << er.what();
654 655
            return Status::DBTransactionError("GENERAL ERROR WHEN DESCRIBING ALL TABLES", er.what());
        }
Z
update  
zhiru 已提交
656 657 658 659 660

        return Status::OK();
    }

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

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

664 665 666 667 668 669 670 671 672 673
        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 已提交
674
        try {
675

Z
update  
zhiru 已提交
676
            MetricCollector metric;
677

Z
update  
zhiru 已提交
678 679 680 681 682 683 684 685
            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);
686

Z
update  
zhiru 已提交
687 688 689 690 691 692 693 694 695
            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_);
696

697 698
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
699

Z
update  
zhiru 已提交
700 701 702 703
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::CreateTableFile connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

704
                Query createTableFileQuery = connectionPtr->query();
705

706 707 708 709 710 711 712 713 714
                createTableFileQuery << "INSERT INTO TableFiles VALUES" <<
                                     "(" << id << ", " << quote << table_id << ", " << engine_type << ", " <<
                                     quote << file_id << ", " << file_type << ", " << size << ", " <<
                                     updated_time << ", " << created_on << ", " << date << ");";

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

                    //Consume all results to avoid "Commands out of sync" error
Z
update  
zhiru 已提交
715 716 717
//                while (createTableFileQuery.more_results()) {
//                    createTableFileQuery.store_next();
//                }
718 719 720 721 722
                } else {
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN ADDING TABLE FILE";
                    return Status::DBTransactionError("Add file Error", createTableFileQuery.error());
                }
            } // Scoped Connection
723

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

Z
update  
zhiru 已提交
726 727 728 729 730 731
            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");
                }
732
            }
Z
update  
zhiru 已提交
733 734 735

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
736
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN ADDING TABLE FILE" << ": " << er.what();
Z
update  
zhiru 已提交
737 738 739
            return Status::DBTransactionError("QUERY ERROR WHEN ADDING TABLE FILE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
740
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN ADDING TABLE FILE" << ": " << er.what();
Z
update  
zhiru 已提交
741
            return Status::DBTransactionError("GENERAL ERROR WHEN ADDING TABLE FILE", er.what());
Z
zhiru 已提交
742 743
        } catch (std::exception& ex) {
            return HandleException("Encounter exception when create table file", ex);
744
        }
Z
update  
zhiru 已提交
745 746 747 748 749

        return Status::OK();
    }

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

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

753 754 755
        files.clear();

        try {
Z
update  
zhiru 已提交
756 757

            MetricCollector metric;
758

759 760 761 762
            StoreQueryResult res;

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

Z
update  
zhiru 已提交
764 765 766 767
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::FilesToIndex connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

768 769 770 771 772 773
                Query filesToIndexQuery = connectionPtr->query();
                filesToIndexQuery << "SELECT id, table_id, engine_type, file_id, file_type, size, date " <<
                                     "FROM TableFiles " <<
                                     "WHERE file_type = " << std::to_string(TableFileSchema::TO_INDEX) << ";";
                res = filesToIndexQuery.store();
            } //Scoped Connection
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

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

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

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

                table_file.engine_type_ = resRow["engine_type"];

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

                table_file.file_type_ = resRow["file_type"];

                table_file.size_ = resRow["size"];

                table_file.date_ = resRow["date"];

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

                GetTableFilePath(table_file);

                files.push_back(table_file);
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
816
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN FINDING TABLE FILES TO INDEX" << ": " << er.what();
817 818 819
            return Status::DBTransactionError("QUERY ERROR WHEN FINDING TABLE FILES TO INDEX", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
820
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN FINDING TABLE FILES TO INDEX" << ": " << er.what();
821 822
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO INDEX", er.what());
        }
Z
update  
zhiru 已提交
823 824 825 826 827 828 829

        return Status::OK();
    }

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

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

833 834 835
        files.clear();

        try {
Z
update  
zhiru 已提交
836 837

            MetricCollector metric;
838 839 840

            StoreQueryResult res;

841 842
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
843

Z
update  
zhiru 已提交
844 845 846 847
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::FilesToSearch connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

848
                if (partition.empty()) {
849

850 851 852 853 854 855 856 857
                    Query filesToSearchQuery = connectionPtr->query();
                    filesToSearchQuery << "SELECT id, table_id, engine_type, file_id, file_type, size, date " <<
                                       "FROM TableFiles " <<
                                       "WHERE table_id = " << quote << table_id << " AND " <<
                                       "(file_type = " << std::to_string(TableFileSchema::RAW) << " OR " <<
                                       "file_type = " << std::to_string(TableFileSchema::TO_INDEX) << " OR " <<
                                       "file_type = " << std::to_string(TableFileSchema::INDEX) << ");";
                    res = filesToSearchQuery.store();
858

859
                } else {
860

861
                    Query filesToSearchQuery = connectionPtr->query();
862

863 864 865 866 867 868 869 870 871
                    std::stringstream partitionListSS;
                    for (auto &date : partition) {
                        partitionListSS << std::to_string(date) << ", ";
                    }
                    std::string partitionListStr = partitionListSS.str();
                    partitionListStr = partitionListStr.substr(0, partitionListStr.size() - 2); //remove the last ", "

                    filesToSearchQuery << "SELECT id, table_id, engine_type, file_id, file_type, size, date " <<
                                       "FROM TableFiles " <<
Z
update  
zhiru 已提交
872 873 874 875 876
                                       "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) << ");";
877
                    res = filesToSearchQuery.store();
878

879 880
                }
            } //Scoped Connection
881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922

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

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

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

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

                table_file.engine_type_ = resRow["engine_type"];

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

                table_file.file_type_ = resRow["file_type"];

                table_file.size_ = resRow["size"];

                table_file.date_ = resRow["date"];

                table_file.dimension_ = table_schema.dimension_;

                GetTableFilePath(table_file);

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

                files[table_file.date_].push_back(table_file);
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
923
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN FINDING TABLE FILES TO SEARCH" << ": " << er.what();
924 925 926
            return Status::DBTransactionError("QUERY ERROR WHEN FINDING TABLE FILES TO SEARCH", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
927
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN FINDING TABLE FILES TO SEARCH" << ": " << er.what();
928 929
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO SEARCH", er.what());
        }
Z
update  
zhiru 已提交
930 931 932 933 934 935

        return Status::OK();
    }

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

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

939 940 941
        files.clear();

        try {
Z
update  
zhiru 已提交
942
            MetricCollector metric;
943

944
            StoreQueryResult res;
Z
zhiru 已提交
945

946 947 948
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

Z
update  
zhiru 已提交
949 950 951 952
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::FilesToMerge connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

953 954 955 956 957 958 959 960
                Query filesToMergeQuery = connectionPtr->query();
                filesToMergeQuery << "SELECT id, table_id, file_id, file_type, size, date " <<
                                  "FROM TableFiles " <<
                                  "WHERE table_id = " << quote << table_id << " AND " <<
                                  "file_type = " << std::to_string(TableFileSchema::RAW) << " " <<
                                  "ORDER BY size DESC" << ";";
                res = filesToMergeQuery.store();
            } //Scoped Connection
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002

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

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

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

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

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

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

                table_file.file_type_ = resRow["file_type"];

                table_file.size_ = resRow["size"];

                table_file.date_ = resRow["date"];

                table_file.dimension_ = table_schema.dimension_;

                GetTableFilePath(table_file);

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

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

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1003
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN FINDING TABLE FILES TO MERGE" << ": " << er.what();
1004 1005 1006
            return Status::DBTransactionError("QUERY ERROR WHEN FINDING TABLE FILES TO MERGE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1007
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN FINDING TABLE FILES TO MERGE" << ": " << er.what();
1008 1009
            return Status::DBTransactionError("GENERAL ERROR WHEN FINDING TABLE FILES TO MERGE", er.what());
        }
Z
update  
zhiru 已提交
1010 1011 1012 1013

        return Status::OK();
    }

Z
update  
zhiru 已提交
1014 1015 1016
    Status MySQLMetaImpl::GetTableFiles(const std::string& table_id,
                                        const std::vector<size_t>& ids,
                                        TableFilesSchema& table_files) {
Z
update  
zhiru 已提交
1017

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

Z
fix  
zhiru 已提交
1020 1021 1022 1023
        if (ids.empty()) {
            return Status::OK();
        }

Z
update  
zhiru 已提交
1024 1025 1026 1027 1028 1029 1030
        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 "

1031 1032
        try {

1033 1034 1035 1036
            StoreQueryResult res;

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

Z
update  
zhiru 已提交
1038 1039 1040 1041
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::GetTableFiles connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

1042 1043 1044 1045 1046 1047 1048
                Query getTableFileQuery = connectionPtr->query();
                getTableFileQuery << "SELECT engine_type, file_id, file_type, size, date " <<
                                  "FROM TableFiles " <<
                                  "WHERE table_id = " << quote << table_id << " AND " <<
                                  "(" << idStr << ");";
                res = getTableFileQuery.store();
            } //Scoped Connection
1049

Z
update  
zhiru 已提交
1050
            assert(res);
1051

Z
update  
zhiru 已提交
1052 1053 1054 1055 1056 1057
            TableSchema table_schema;
            table_schema.table_id_ = table_id;
            auto status = DescribeTable(table_schema);
            if (!status.ok()) {
                return status;
            }
1058

Z
update  
zhiru 已提交
1059 1060 1061
            for (auto& resRow : res) {

                TableFileSchema file_schema;
1062 1063 1064

                file_schema.table_id_ = table_id;

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

1067 1068 1069 1070 1071 1072 1073 1074 1075
                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 已提交
1076 1077 1078 1079 1080 1081

                file_schema.dimension_ = table_schema.dimension_;

                GetTableFilePath(file_schema);

                table_files.emplace_back(file_schema);
1082 1083 1084
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1085
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN RETRIEVING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
1086
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING TABLE FILES", er.what());
1087 1088
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1089
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN RETRIEVING TABLE FILES" << ": " << er.what();
Z
update  
zhiru 已提交
1090
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING TABLE FILES", er.what());
1091
        }
Z
update  
zhiru 已提交
1092 1093 1094 1095 1096 1097

        return Status::OK();
    }

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

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

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
        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 已提交
1112

1113 1114
                try {

Z
zhiru 已提交
1115 1116
                    ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

Z
update  
zhiru 已提交
1117 1118 1119 1120
//                    if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                        ENGINE_LOG_WARNING << "MySQLMetaImpl::Archive connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                    }

1121
                    Query archiveQuery = connectionPtr->query();
1122
                    archiveQuery << "UPDATE TableFiles " <<
1123 1124 1125 1126 1127 1128 1129 1130 1131
                                    "SET file_type = " << std::to_string(TableFileSchema::TO_DELETE) << " " <<
                                    "WHERE created_on < " << std::to_string(now - usecs) << " AND " <<
                                    "file_type <> " << std::to_string(TableFileSchema::TO_DELETE) << ";";
                    if (!archiveQuery.exec()) {
                        return Status::DBTransactionError("QUERY ERROR DURING ARCHIVE", archiveQuery.error());
                    }

                } catch (const BadQuery& er) {
                    // Handle any query errors
Z
update  
zhiru 已提交
1132
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN DURING ARCHIVE" << ": " << er.what();
1133 1134 1135
                    return Status::DBTransactionError("QUERY ERROR WHEN DURING ARCHIVE", er.what());
                } catch (const Exception& er) {
                    // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1136
                    ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DURING ARCHIVE" << ": " << er.what();
1137 1138 1139 1140 1141 1142 1143
                    return Status::DBTransactionError("GENERAL ERROR WHEN DURING ARCHIVE", er.what());
                }
            }
            if (criteria == "disk") {
                uint64_t sum = 0;
                Size(sum);

Z
update  
zhiru 已提交
1144
                auto to_delete = (sum - limit * G);
1145 1146 1147
                DiscardFiles(to_delete);
            }
        }
Z
update  
zhiru 已提交
1148 1149 1150 1151 1152

        return Status::OK();
    }

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

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

1156 1157 1158
        result = 0;
        try {

1159 1160 1161 1162
            StoreQueryResult res;

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

Z
update  
zhiru 已提交
1164 1165 1166 1167
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::Size connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

1168 1169 1170 1171 1172 1173
                Query getSizeQuery = connectionPtr->query();
                getSizeQuery << "SELECT SUM(size) AS sum " <<
                             "FROM TableFiles " <<
                             "WHERE file_type <> " << std::to_string(TableFileSchema::TO_DELETE) << ";";
                res = getSizeQuery.store();
            } //Scoped Connection
1174 1175

            assert(res && res.num_rows() == 1);
Z
zhiru 已提交
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
//            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;
            }
1188 1189 1190

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1191
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN RETRIEVING SIZE" << ": " << er.what();
1192 1193 1194
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING SIZE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1195
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN RETRIEVING SIZE" << ": " << er.what();
1196 1197
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING SIZE", er.what());
        }
Z
update  
zhiru 已提交
1198 1199 1200 1201

        return Status::OK();
    }

Z
zhiru 已提交
1202 1203
    Status MySQLMetaImpl::DiscardFiles(long long to_discard_size) {

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

1206 1207 1208 1209
        if (to_discard_size <= 0) {
//            std::cout << "in" << std::endl;
            return Status::OK();
        }
Z
update  
zhiru 已提交
1210 1211
        ENGINE_LOG_DEBUG << "About to discard size=" << to_discard_size;

1212 1213
        try {

Z
update  
zhiru 已提交
1214 1215
            MetricCollector metric;

1216 1217 1218 1219
            bool status;

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

Z
update  
zhiru 已提交
1221 1222 1223 1224
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::DiscardFiles connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

1225 1226 1227 1228 1229 1230
                Query discardFilesQuery = connectionPtr->query();
                discardFilesQuery << "SELECT id, size " <<
                                  "FROM TableFiles " <<
                                  "WHERE file_type <> " << std::to_string(TableFileSchema::TO_DELETE) << " " <<
                                  "ORDER BY id ASC " <<
                                  "LIMIT 10;";
1231
//            std::cout << discardFilesQuery.str() << std::endl;
1232
                StoreQueryResult res = discardFilesQuery.store();
1233

1234 1235 1236 1237
                assert(res);
                if (res.num_rows() == 0) {
                    return Status::OK();
                }
1238

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
                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_;
1251 1252
                }

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

1256 1257 1258 1259
                discardFilesQuery << "UPDATE TableFiles " <<
                                  "SET file_type = " << std::to_string(TableFileSchema::TO_DELETE) << ", " <<
                                  "updated_time = " << std::to_string(utils::GetMicroSecTimeStamp()) << " " <<
                                  "WHERE " << idsToDiscardStr << ";";
1260

1261 1262 1263 1264 1265 1266 1267 1268
                status = discardFilesQuery.exec();
                if (!status) {
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN DISCARDING FILES";
                    return Status::DBTransactionError("QUERY ERROR WHEN DISCARDING FILES", discardFilesQuery.error());
                }
            } //Scoped Connection

            return DiscardFiles(to_discard_size);
1269 1270 1271

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1272
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DISCARDING FILES" << ": " << er.what();
1273 1274 1275
            return Status::DBTransactionError("QUERY ERROR WHEN DISCARDING FILES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1276
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DISCARDING FILES" << ": " << er.what();
1277 1278
            return Status::DBTransactionError("GENERAL ERROR WHEN DISCARDING FILES", er.what());
        }
Z
update  
zhiru 已提交
1279 1280
    }

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

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

1286 1287
        file_schema.updated_time_ = utils::GetMicroSecTimeStamp();
        try {
Z
update  
zhiru 已提交
1288 1289

            MetricCollector metric;
1290

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

Z
update  
zhiru 已提交
1294 1295 1296 1297
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::UpdateTableFile connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

1298
                Query updateTableFileQuery = connectionPtr->query();
1299

1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
                //if the table has been deleted, just mark the table file as TO_DELETE
                //clean thread will delete the file later
                updateTableFileQuery << "SELECT state FROM Tables " <<
                                     "WHERE table_id = " << quote << file_schema.table_id_ << ";";
                StoreQueryResult res = updateTableFileQuery.store();

                assert(res && res.num_rows() <= 1);
                if (res.num_rows() == 1) {
                    int state = res[0]["state"];
                    if (state == TableSchema::TO_DELETE) {
                        file_schema.file_type_ = TableFileSchema::TO_DELETE;
                    }
                } else {
Z
update  
zhiru 已提交
1313 1314 1315
                    file_schema.file_type_ = TableFileSchema::TO_DELETE;
                }

1316 1317 1318 1319 1320 1321 1322 1323 1324
                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_);
1325

1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
                updateTableFileQuery << "UPDATE TableFiles " <<
                                     "SET table_id = " << quote << table_id << ", " <<
                                     "engine_type = " << engine_type << ", " <<
                                     "file_id = " << quote << file_id << ", " <<
                                     "file_type = " << file_type << ", " <<
                                     "size = " << size << ", " <<
                                     "updated_time = " << updated_time << ", " <<
                                     "created_on = " << created_on << ", " <<
                                     "date = " << date << " " <<
                                     "WHERE id = " << id << ";";
1336 1337 1338

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

1339 1340 1341 1342 1343 1344 1345
                if (!updateTableFileQuery.exec()) {
                    ENGINE_LOG_DEBUG << "table_id= " << file_schema.table_id_ << " file_id=" << file_schema.file_id_;
                    ENGINE_LOG_ERROR << "QUERY ERROR WHEN UPDATING TABLE FILE";
                    return Status::DBTransactionError("QUERY ERROR WHEN UPDATING TABLE FILE",
                                                      updateTableFileQuery.error());
                }
            } //Scoped Connection
1346 1347 1348 1349

        } catch (const BadQuery& er) {
            // Handle any query errors
            ENGINE_LOG_DEBUG << "table_id= " << file_schema.table_id_ << " file_id=" << file_schema.file_id_;
Z
update  
zhiru 已提交
1350
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN UPDATING TABLE FILE" << ": " << er.what();
1351 1352 1353 1354
            return Status::DBTransactionError("QUERY ERROR WHEN UPDATING TABLE FILE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
            ENGINE_LOG_DEBUG << "table_id= " << file_schema.table_id_ << " file_id=" << file_schema.file_id_;
Z
update  
zhiru 已提交
1355
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN UPDATING TABLE FILE" << ": " << er.what();
1356 1357
            return Status::DBTransactionError("GENERAL ERROR WHEN UPDATING TABLE FILE", er.what());
        }
Z
update  
zhiru 已提交
1358 1359 1360 1361
        return Status::OK();
    }

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

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

1365
        try {
Z
update  
zhiru 已提交
1366
            MetricCollector metric;
1367

1368 1369
            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
update  
zhiru 已提交
1370

Z
update  
zhiru 已提交
1371 1372 1373 1374
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::UpdateTableFiles connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

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

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

1380 1381 1382
                    if (has_tables.find(file_schema.table_id_) != has_tables.end()) {
                        continue;
                    }
Z
update  
zhiru 已提交
1383

1384 1385 1386 1387 1388 1389
                    updateTableFilesQuery << "SELECT EXISTS " <<
                                          "(SELECT 1 FROM Tables " <<
                                          "WHERE table_id = " << quote << file_schema.table_id_ << " " <<
                                          "AND state <> " << std::to_string(TableSchema::TO_DELETE) << ") " <<
                                          "AS " << quote << "check" << ";";
                    StoreQueryResult res = updateTableFilesQuery.store();
1390

1391 1392 1393
                    assert(res && res.num_rows() == 1);
                    int check = res[0]["check"];
                    has_tables[file_schema.table_id_] = (check == 1);
Z
update  
zhiru 已提交
1394 1395
                }

1396
                for (auto &file_schema : files) {
1397

1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
                    if (!has_tables[file_schema.table_id_]) {
                        file_schema.file_type_ = TableFileSchema::TO_DELETE;
                    }
                    file_schema.updated_time_ = utils::GetMicroSecTimeStamp();

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

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

                    if (!updateTableFilesQuery.exec()) {
                        ENGINE_LOG_ERROR << "QUERY ERROR WHEN UPDATING TABLE FILES";
                        return Status::DBTransactionError("QUERY ERROR WHEN UPDATING TABLE FILES",
                                                          updateTableFilesQuery.error());
                    }
                }
            } //Scoped Connection
1431 1432 1433

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1434
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN UPDATING TABLE FILES" << ": " << er.what();
1435 1436 1437
            return Status::DBTransactionError("QUERY ERROR WHEN UPDATING TABLE FILES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1438
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN UPDATING TABLE FILES" << ": " << er.what();
1439 1440
            return Status::DBTransactionError("GENERAL ERROR WHEN UPDATING TABLE FILES", er.what());
        }
Z
update  
zhiru 已提交
1441 1442 1443 1444
        return Status::OK();
    }

    Status MySQLMetaImpl::CleanUpFilesWithTTL(uint16_t seconds) {
Z
zhiru 已提交
1445 1446 1447 1448
//        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 已提交
1449

1450 1451
        auto now = utils::GetMicroSecTimeStamp();
        try {
Z
update  
zhiru 已提交
1452
            MetricCollector metric;
1453

1454
            {
Z
update  
zhiru 已提交
1455 1456 1457 1458

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

1459
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
1460

Z
update  
zhiru 已提交
1461 1462 1463 1464 1465
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::CleanUpFilesWithTTL: clean table files: connection in use after creating ScopedConnection = "
//                    << mySQLConnectionPool_->getConnectionsInUse();
//                }

1466 1467 1468 1469 1470 1471
                Query cleanUpFilesWithTTLQuery = connectionPtr->query();
                cleanUpFilesWithTTLQuery << "SELECT id, table_id, file_id, date " <<
                                         "FROM TableFiles " <<
                                         "WHERE file_type = " << std::to_string(TableFileSchema::TO_DELETE) << " AND " <<
                                         "updated_time < " << std::to_string(now - seconds * US_PS) << ";";
                StoreQueryResult res = cleanUpFilesWithTTLQuery.store();
1472

1473
                assert(res);
1474

1475 1476
                TableFileSchema table_file;
                std::vector<std::string> idsToDelete;
1477

1478
                for (auto &resRow : res) {
1479

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

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

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

1490
                    table_file.date_ = resRow["date"];
1491

1492
                    GetTableFilePath(table_file);
1493

1494 1495 1496
                    ENGINE_LOG_DEBUG << "Removing deleted id =" << table_file.id_ << " location = "
                                     << table_file.location_ << std::endl;
                    boost::filesystem::remove(table_file.location_);
1497

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

Z
fix  
zhiru 已提交
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516
                if (!idsToDelete.empty()) {

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

                    std::string idsToDeleteStr = idsToDeleteSS.str();
                    idsToDeleteStr = idsToDeleteStr.substr(0, idsToDeleteStr.size() - 4); //remove the last " OR "
                    cleanUpFilesWithTTLQuery << "DELETE FROM TableFiles WHERE " <<
                                             idsToDeleteStr << ";";
                    if (!cleanUpFilesWithTTLQuery.exec()) {
                        ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES WITH TTL";
                        return Status::DBTransactionError("CleanUpFilesWithTTL Error",
                                                          cleanUpFilesWithTTLQuery.error());
                    }
1517 1518
                }
            } //Scoped Connection
1519 1520 1521

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

1530
        try {
Z
update  
zhiru 已提交
1531
            MetricCollector metric;
1532

1533
            {
Z
update  
zhiru 已提交
1534 1535 1536
//                ENGINE_LOG_WARNING << "MySQLMetaImpl::CleanUpFilesWithTTL: clean tables: connection in use before creating ScopedConnection = "
//                                   << mySQLConnectionPool_->getConnectionsInUse();

1537
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);
Z
zhiru 已提交
1538

Z
update  
zhiru 已提交
1539 1540 1541 1542 1543
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::CleanUpFilesWithTTL: clean tables: connection in use after creating ScopedConnection = "
//                    << mySQLConnectionPool_->getConnectionsInUse();
//                }

1544 1545 1546 1547 1548 1549
                Query cleanUpFilesWithTTLQuery = connectionPtr->query();
                cleanUpFilesWithTTLQuery << "SELECT id, table_id " <<
                                         "FROM Tables " <<
                                         "WHERE state = " << std::to_string(TableSchema::TO_DELETE) << ";";
                StoreQueryResult res = cleanUpFilesWithTTLQuery.store();
                assert(res);
Z
zhiru 已提交
1550
//            std::cout << res.num_rows() << std::endl;
1551

Z
fix  
zhiru 已提交
1552
                if (!res.empty()) {
1553

Z
fix  
zhiru 已提交
1554 1555 1556 1557 1558
                    std::stringstream idsToDeleteSS;
                    for (auto &resRow : res) {
                        size_t id = resRow["id"];
                        std::string table_id;
                        resRow["table_id"].to_string(table_id);
1559

Z
fix  
zhiru 已提交
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575
                        auto table_path = GetTablePath(table_id);

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

                        idsToDeleteSS << "id = " << std::to_string(id) << " OR ";
                    }
                    std::string idsToDeleteStr = idsToDeleteSS.str();
                    idsToDeleteStr = idsToDeleteStr.substr(0, idsToDeleteStr.size() - 4); //remove the last " OR "
                    cleanUpFilesWithTTLQuery << "DELETE FROM Tables WHERE " <<
                                             idsToDeleteStr << ";";
                    if (!cleanUpFilesWithTTLQuery.exec()) {
                        ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES WITH TTL";
                        return Status::DBTransactionError("QUERY ERROR WHEN CLEANING UP FILES WITH TTL",
                                                          cleanUpFilesWithTTLQuery.error());
                    }
1576
                }
Z
fix  
zhiru 已提交
1577
           } //Scoped Connection
1578

Z
update  
zhiru 已提交
1579 1580
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1581
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES WITH TTL" << ": " << er.what();
Z
update  
zhiru 已提交
1582 1583 1584
            return Status::DBTransactionError("QUERY ERROR WHEN CLEANING UP FILES WITH TTL", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1585
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN CLEANING UP FILES WITH TTL" << ": " << er.what();
Z
update  
zhiru 已提交
1586 1587
            return Status::DBTransactionError("GENERAL ERROR WHEN CLEANING UP FILES WITH TTL", er.what());
        }
1588

Z
update  
zhiru 已提交
1589 1590
        return Status::OK();
    }
1591

Z
update  
zhiru 已提交
1592 1593
    Status MySQLMetaImpl::CleanUp() {

Z
zhiru 已提交
1594
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
update  
zhiru 已提交
1595 1596

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

Z
update  
zhiru 已提交
1599 1600 1601 1602
//            if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                ENGINE_LOG_WARNING << "MySQLMetaImpl::CleanUp: connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//            }

Z
update  
zhiru 已提交
1603 1604
            ENGINE_LOG_DEBUG << "Remove table file type as NEW";
            Query cleanUpQuery = connectionPtr->query();
1605
            cleanUpQuery << "DELETE FROM TableFiles WHERE file_type = " << std::to_string(TableFileSchema::NEW) << ";";
1606 1607

            if (!cleanUpQuery.exec()) {
Z
update  
zhiru 已提交
1608
                ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES";
1609 1610 1611 1612 1613
                return Status::DBTransactionError("Clean up Error", cleanUpQuery.error());
            }

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1614
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN CLEANING UP FILES" << ": " << er.what();
1615 1616 1617
            return Status::DBTransactionError("QUERY ERROR WHEN CLEANING UP FILES", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1618
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN CLEANING UP FILES" << ": " << er.what();
1619 1620
            return Status::DBTransactionError("GENERAL ERROR WHEN CLEANING UP FILES", er.what());
        }
Z
update  
zhiru 已提交
1621 1622 1623 1624 1625 1626

        return Status::OK();
    }

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

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

1629
        try {
Z
update  
zhiru 已提交
1630
            MetricCollector metric;
1631 1632 1633 1634 1635 1636 1637 1638 1639

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

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

1640 1641 1642 1643 1644
            StoreQueryResult res;

            {
                ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

Z
update  
zhiru 已提交
1645 1646 1647 1648
//                if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                    ENGINE_LOG_WARNING << "MySQLMetaImpl::Count: connection in use = " << mySQLConnectionPool_->getConnectionsInUse();
//                }

1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
                Query countQuery = connectionPtr->query();
                countQuery << "SELECT size " <<
                           "FROM TableFiles " <<
                           "WHERE table_id = " << quote << table_id << " AND " <<
                           "(file_type = " << std::to_string(TableFileSchema::RAW) << " OR " <<
                           "file_type = " << std::to_string(TableFileSchema::TO_INDEX) << " OR " <<
                           "file_type = " << std::to_string(TableFileSchema::INDEX) << ");";
                res = countQuery.store();
            } //Scoped Connection

1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
            result = 0;
            for (auto &resRow : res) {
                size_t size = resRow["size"];
                result += size;
            }

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

        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1671
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN RETRIEVING COUNT" << ": " << er.what();
1672 1673 1674
            return Status::DBTransactionError("QUERY ERROR WHEN RETRIEVING COUNT", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1675
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN RETRIEVING COUNT" << ": " << er.what();
1676 1677
            return Status::DBTransactionError("GENERAL ERROR WHEN RETRIEVING COUNT", er.what());
        }
Z
update  
zhiru 已提交
1678 1679 1680 1681
        return Status::OK();
    }

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

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

1685 1686 1687 1688
        if (boost::filesystem::is_directory(options_.path)) {
            boost::filesystem::remove_all(options_.path);
        }
        try {
Z
zhiru 已提交
1689 1690 1691

            ScopedConnection connectionPtr(*mySQLConnectionPool_, safe_grab);

Z
update  
zhiru 已提交
1692 1693 1694 1695
//            if (mySQLConnectionPool_->getConnectionsInUse() <= 0) {
//                ENGINE_LOG_WARNING << "MySQLMetaImpl::DropAll: connection in use  = " << mySQLConnectionPool_->getConnectionsInUse();
//            }

1696
            Query dropTableQuery = connectionPtr->query();
1697
            dropTableQuery << "DROP TABLE IF EXISTS Tables, TableFiles;";
1698 1699 1700 1701
            if (dropTableQuery.exec()) {
                return Status::OK();
            }
            else {
Z
update  
zhiru 已提交
1702
                ENGINE_LOG_ERROR << "QUERY ERROR WHEN DROPPING TABLE";
1703 1704 1705 1706
                return Status::DBTransactionError("DROP TABLE ERROR", dropTableQuery.error());
            }
        } catch (const BadQuery& er) {
            // Handle any query errors
Z
update  
zhiru 已提交
1707
            ENGINE_LOG_ERROR << "QUERY ERROR WHEN DROPPING TABLE" << ": " << er.what();
1708 1709 1710
            return Status::DBTransactionError("QUERY ERROR WHEN DROPPING TABLE", er.what());
        } catch (const Exception& er) {
            // Catch-all for any other MySQL++ exceptions
Z
update  
zhiru 已提交
1711
            ENGINE_LOG_ERROR << "GENERAL ERROR WHEN DROPPING TABLE" << ": " << er.what();
1712 1713
            return Status::DBTransactionError("GENERAL ERROR WHEN DROPPING TABLE", er.what());
        }
Z
zhiru 已提交
1714
        return Status::OK();
Z
update  
zhiru 已提交
1715 1716 1717
    }

    MySQLMetaImpl::~MySQLMetaImpl() {
Z
zhiru 已提交
1718
//        std::lock_guard<std::recursive_mutex> lock(mysql_mutex);
Z
update  
zhiru 已提交
1719 1720 1721 1722 1723 1724 1725
        CleanUp();
    }

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