MySQLMetaImpl.cpp 83.6 KB
Newer Older
J
jinhai 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

S
starlord 已提交
18
#include "db/meta/MySQLMetaImpl.h"
S
starlord 已提交
19
#include "MetaConsts.h"
S
starlord 已提交
20 21
#include "db/IDGenerator.h"
#include "db/Utils.h"
Z
update  
zhiru 已提交
22
#include "metrics/Metrics.h"
23
#include "utils/CommonUtil.h"
S
starlord 已提交
24 25
#include "utils/Exception.h"
#include "utils/Log.h"
26
#include "utils/StringHelpFunctions.h"
Z
update  
zhiru 已提交
27

S
starlord 已提交
28 29
#include <mysql++/mysql++.h>
#include <string.h>
Z
update  
zhiru 已提交
30
#include <unistd.h>
S
starlord 已提交
31
#include <boost/filesystem.hpp>
Z
update  
zhiru 已提交
32 33
#include <chrono>
#include <fstream>
S
starlord 已提交
34 35 36
#include <iostream>
#include <map>
#include <mutex>
Z
update  
zhiru 已提交
37
#include <regex>
S
starlord 已提交
38 39
#include <set>
#include <sstream>
Z
update  
zhiru 已提交
40
#include <string>
Z
zhiru 已提交
41
#include <thread>
Z
update  
zhiru 已提交
42 43 44 45 46

namespace milvus {
namespace engine {
namespace meta {

47
namespace {
Z
update  
zhiru 已提交
48

S
starlord 已提交
49
Status
S
starlord 已提交
50
HandleException(const std::string& desc, const char* what = nullptr) {
S
starlord 已提交
51
    if (what == nullptr) {
S
starlord 已提交
52 53 54
        ENGINE_LOG_ERROR << desc;
        return Status(DB_META_TRANSACTION_FAILED, desc);
    }
S
starlord 已提交
55 56 57 58

    std::string msg = desc + ":" + what;
    ENGINE_LOG_ERROR << msg;
    return Status(DB_META_TRANSACTION_FAILED, msg);
59
}
Z
update  
zhiru 已提交
60

61
class MetaField {
S
starlord 已提交
62
 public:
S
starlord 已提交
63 64
    MetaField(const std::string& name, const std::string& type, const std::string& setting)
        : name_(name), type_(type), setting_(setting) {
65 66
    }

S
starlord 已提交
67 68
    std::string
    name() const {
69 70 71
        return name_;
    }

S
starlord 已提交
72 73
    std::string
    ToString() const {
74 75 76 77 78
        return name_ + " " + type_ + " " + setting_;
    }

    // mysql field type has additional information. for instance, a filed type is defined as 'BIGINT'
    // we get the type from sql is 'bigint(20)', so we need to ignore the '(20)'
S
starlord 已提交
79 80
    bool
    IsEqual(const MetaField& field) const {
81 82 83
        size_t name_len_min = field.name_.length() > name_.length() ? name_.length() : field.name_.length();
        size_t type_len_min = field.type_.length() > type_.length() ? type_.length() : field.type_.length();
        return strncasecmp(field.name_.c_str(), name_.c_str(), name_len_min) == 0 &&
S
starlord 已提交
84
               strncasecmp(field.type_.c_str(), type_.c_str(), type_len_min) == 0;
85 86
    }

S
starlord 已提交
87
 private:
88 89 90 91 92 93 94
    std::string name_;
    std::string type_;
    std::string setting_;
};

using MetaFields = std::vector<MetaField>;
class MetaSchema {
S
starlord 已提交
95
 public:
S
starlord 已提交
96
    MetaSchema(const std::string& name, const MetaFields& fields) : name_(name), fields_(fields) {
97 98
    }

S
starlord 已提交
99 100
    std::string
    name() const {
101 102 103
        return name_;
    }

S
starlord 已提交
104 105
    std::string
    ToString() const {
106
        std::string result;
S
starlord 已提交
107
        for (auto& field : fields_) {
S
starlord 已提交
108
            if (!result.empty()) {
109 110 111 112 113 114 115
                result += ",";
            }
            result += field.ToString();
        }
        return result;
    }

S
starlord 已提交
116 117 118 119
    // if the outer fields contains all this MetaSchema fields, return true
    // otherwise return false
    bool
    IsEqual(const MetaFields& fields) const {
120
        std::vector<std::string> found_field;
S
starlord 已提交
121 122
        for (const auto& this_field : fields_) {
            for (const auto& outer_field : fields) {
S
starlord 已提交
123
                if (this_field.IsEqual(outer_field)) {
124 125 126 127 128 129 130 131 132
                    found_field.push_back(this_field.name());
                    break;
                }
            }
        }

        return found_field.size() == fields_.size();
    }

S
starlord 已提交
133
 private:
134 135 136 137
    std::string name_;
    MetaFields fields_;
};

S
starlord 已提交
138
// Tables schema
139
static const MetaSchema TABLES_SCHEMA(META_TABLES, {
S
starlord 已提交
140 141 142 143 144 145 146 147 148 149
                                                       MetaField("id", "BIGINT", "PRIMARY KEY AUTO_INCREMENT"),
                                                       MetaField("table_id", "VARCHAR(255)", "UNIQUE NOT NULL"),
                                                       MetaField("state", "INT", "NOT NULL"),
                                                       MetaField("dimension", "SMALLINT", "NOT NULL"),
                                                       MetaField("created_on", "BIGINT", "NOT NULL"),
                                                       MetaField("flag", "BIGINT", "DEFAULT 0 NOT NULL"),
                                                       MetaField("index_file_size", "BIGINT", "DEFAULT 1024 NOT NULL"),
                                                       MetaField("engine_type", "INT", "DEFAULT 1 NOT NULL"),
                                                       MetaField("nlist", "INT", "DEFAULT 16384 NOT NULL"),
                                                       MetaField("metric_type", "INT", "DEFAULT 1 NOT NULL"),
G
groot 已提交
150 151 152 153
                                                       MetaField("owner_table", "VARCHAR(255)", "NOT NULL"),
                                                       MetaField("partition_tag", "VARCHAR(255)", "NOT NULL"),
                                                       MetaField("version", "VARCHAR(64)",
                                                                 std::string("DEFAULT '") + CURRENT_VERSION + "'"),
S
starlord 已提交
154 155 156
                                                   });

// TableFiles schema
J
JinHai-CN 已提交
157 158 159 160 161 162 163 164 165 166 167 168
static const MetaSchema TABLEFILES_SCHEMA(META_TABLEFILES, {
                                                               MetaField("id", "BIGINT", "PRIMARY KEY AUTO_INCREMENT"),
                                                               MetaField("table_id", "VARCHAR(255)", "NOT NULL"),
                                                               MetaField("engine_type", "INT", "DEFAULT 1 NOT NULL"),
                                                               MetaField("file_id", "VARCHAR(255)", "NOT NULL"),
                                                               MetaField("file_type", "INT", "DEFAULT 0 NOT NULL"),
                                                               MetaField("file_size", "BIGINT", "DEFAULT 0 NOT NULL"),
                                                               MetaField("row_count", "BIGINT", "DEFAULT 0 NOT NULL"),
                                                               MetaField("updated_time", "BIGINT", "NOT NULL"),
                                                               MetaField("created_on", "BIGINT", "NOT NULL"),
                                                               MetaField("date", "INT", "DEFAULT -1 NOT NULL"),
                                                           });
S
starlord 已提交
169 170

}  // namespace
171

172
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
S
starlord 已提交
173
MySQLMetaImpl::MySQLMetaImpl(const DBMetaOptions& options, const int& mode) : options_(options), mode_(mode) {
174 175 176 177 178 179
    Initialize();
}

MySQLMetaImpl::~MySQLMetaImpl() {
}

S
starlord 已提交
180
Status
S
starlord 已提交
181
MySQLMetaImpl::NextTableId(std::string& table_id) {
G
groot 已提交
182
    std::lock_guard<std::mutex> lock(genid_mutex_);  // avoid duplicated id
183 184 185 186 187 188 189
    std::stringstream ss;
    SimpleIDGenerator g;
    ss << g.GetNextIDNumber();
    table_id = ss.str();
    return Status::OK();
}

S
starlord 已提交
190
Status
S
starlord 已提交
191
MySQLMetaImpl::NextFileId(std::string& file_id) {
G
groot 已提交
192
    std::lock_guard<std::mutex> lock(genid_mutex_);  // avoid duplicated id
193 194 195 196 197 198 199
    std::stringstream ss;
    SimpleIDGenerator g;
    ss << g.GetNextIDNumber();
    file_id = ss.str();
    return Status::OK();
}

S
starlord 已提交
200 201 202
void
MySQLMetaImpl::ValidateMetaSchema() {
    if (nullptr == mysql_connection_pool_) {
203 204 205
        return;
    }

S
starlord 已提交
206
    mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
207 208 209 210
    if (connectionPtr == nullptr) {
        return;
    }

S
starlord 已提交
211
    auto validate_func = [&](const MetaSchema& schema) {
S
starlord 已提交
212
        mysqlpp::Query query_statement = connectionPtr->query();
213 214 215 216 217
        query_statement << "DESC " << schema.name() << ";";

        MetaFields exist_fields;

        try {
S
starlord 已提交
218
            mysqlpp::StoreQueryResult res = query_statement.store();
219
            for (size_t i = 0; i < res.num_rows(); i++) {
S
starlord 已提交
220
                const mysqlpp::Row& row = res[i];
221 222 223 224 225 226
                std::string name, type;
                row["Field"].to_string(name);
                row["Type"].to_string(type);

                exist_fields.push_back(MetaField(name, type, ""));
            }
S
starlord 已提交
227
        } catch (std::exception& e) {
228 229 230
            ENGINE_LOG_DEBUG << "Meta table '" << schema.name() << "' not exist and will be created";
        }

S
starlord 已提交
231
        if (exist_fields.empty()) {
232 233 234 235 236 237
            return true;
        }

        return schema.IsEqual(exist_fields);
    };

S
starlord 已提交
238
    // verify Tables
239 240 241 242
    if (!validate_func(TABLES_SCHEMA)) {
        throw Exception(DB_INCOMPATIB_META, "Meta Tables schema is created by Milvus old version");
    }

S
starlord 已提交
243
    // verufy TableFiles
244 245 246 247 248
    if (!validate_func(TABLEFILES_SCHEMA)) {
        throw Exception(DB_INCOMPATIB_META, "Meta TableFiles schema is created by Milvus old version");
    }
}

S
starlord 已提交
249 250
Status
MySQLMetaImpl::Initialize() {
S
starlord 已提交
251
    // step 1: create db root path
S
starlord 已提交
252 253
    if (!boost::filesystem::is_directory(options_.path_)) {
        auto ret = boost::filesystem::create_directory(options_.path_);
254
        if (!ret) {
S
starlord 已提交
255
            std::string msg = "Failed to create db directory " + options_.path_;
S
starlord 已提交
256
            ENGINE_LOG_ERROR << msg;
S
shengjh 已提交
257
            throw Exception(DB_META_TRANSACTION_FAILED, msg);
Z
update  
zhiru 已提交
258 259 260
        }
    }

S
starlord 已提交
261
    std::string uri = options_.backend_uri_;
262

S
starlord 已提交
263
    // step 2: parse and check meta uri
264 265
    utils::MetaUriInfo uri_info;
    auto status = utils::ParseMetaUri(uri, uri_info);
S
starlord 已提交
266
    if (!status.ok()) {
267 268 269 270 271 272 273 274 275 276 277
        std::string msg = "Wrong URI format: " + uri;
        ENGINE_LOG_ERROR << msg;
        throw Exception(DB_INVALID_META_URI, msg);
    }

    if (strcasecmp(uri_info.dialect_.c_str(), "mysql") != 0) {
        std::string msg = "URI's dialect is not MySQL";
        ENGINE_LOG_ERROR << msg;
        throw Exception(DB_INVALID_META_URI, msg);
    }

S
starlord 已提交
278
    // step 3: connect mysql
279 280 281 282 283 284 285
    int thread_hint = std::thread::hardware_concurrency();
    int max_pool_size = (thread_hint == 0) ? 8 : thread_hint;
    unsigned int port = 0;
    if (!uri_info.port_.empty()) {
        port = std::stoi(uri_info.port_);
    }

S
starlord 已提交
286 287
    mysql_connection_pool_ = std::make_shared<MySQLConnectionPool>(
        uri_info.db_name_, uri_info.username_, uri_info.password_, uri_info.host_, port, max_pool_size);
288 289
    ENGINE_LOG_DEBUG << "MySQL connection pool: maximum pool size = " << std::to_string(max_pool_size);

S
starlord 已提交
290
    // step 4: validate to avoid open old version schema
291 292
    ValidateMetaSchema();

293 294 295 296
    // step 5: clean shadow files
    if (mode_ != DBOptions::MODE::CLUSTER_READONLY) {
        CleanUpShadowFiles();
    }
297

298 299
    // step 6: try connect mysql server
    mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
300

301
    if (connectionPtr == nullptr) {
G
groot 已提交
302
        std::string msg = "Failed to connect MySQL meta server: " + uri;
303 304 305
        ENGINE_LOG_ERROR << msg;
        throw Exception(DB_INVALID_META_URI, msg);
    }
306

307
    if (!connectionPtr->thread_aware()) {
G
groot 已提交
308 309
        std::string msg =
            "Failed to initialize MySQL meta backend: MySQL client component wasn't built with thread awareness";
310 311 312
        ENGINE_LOG_ERROR << msg;
        throw Exception(DB_INVALID_META_URI, msg);
    }
313

314 315
    // step 7: create meta table Tables
    mysqlpp::Query InitializeQuery = connectionPtr->query();
316

317
    InitializeQuery << "CREATE TABLE IF NOT EXISTS " << TABLES_SCHEMA.name() << " (" << TABLES_SCHEMA.ToString() + ");";
Z
update  
zhiru 已提交
318

319
    ENGINE_LOG_DEBUG << "MySQLMetaImpl::Initialize: " << InitializeQuery.str();
320

321
    if (!InitializeQuery.exec()) {
G
groot 已提交
322
        std::string msg = "Failed to create meta table 'Tables' in MySQL";
323 324 325
        ENGINE_LOG_ERROR << msg;
        throw Exception(DB_META_TRANSACTION_FAILED, msg);
    }
Z
update  
zhiru 已提交
326

327 328 329
    // step 8: create meta table TableFiles
    InitializeQuery << "CREATE TABLE IF NOT EXISTS " << TABLEFILES_SCHEMA.name() << " ("
                    << TABLEFILES_SCHEMA.ToString() + ");";
Z
update  
zhiru 已提交
330

331 332 333
    ENGINE_LOG_DEBUG << "MySQLMetaImpl::Initialize: " << InitializeQuery.str();

    if (!InitializeQuery.exec()) {
G
groot 已提交
334
        std::string msg = "Failed to create meta table 'TableFiles' in MySQL";
335 336
        ENGINE_LOG_ERROR << msg;
        throw Exception(DB_META_TRANSACTION_FAILED, msg);
Z
update  
zhiru 已提交
337
    }
S
starlord 已提交
338 339

    return Status::OK();
340 341
}

S
starlord 已提交
342
Status
S
starlord 已提交
343
MySQLMetaImpl::CreateTable(TableSchema& table_schema) {
344
    try {
Y
Yu Kun 已提交
345
        server::MetricCollector metric;
346
        {
S
starlord 已提交
347
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
348

349
            if (connectionPtr == nullptr) {
G
groot 已提交
350
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
351
            }
Z
update  
zhiru 已提交
352

S
starlord 已提交
353
            mysqlpp::Query createTableQuery = connectionPtr->query();
Z
update  
zhiru 已提交
354

355 356 357
            if (table_schema.table_id_.empty()) {
                NextTableId(table_schema.table_id_);
            } else {
G
groot 已提交
358 359
                createTableQuery << "SELECT state FROM " << META_TABLES << " WHERE table_id = " << mysqlpp::quote
                                 << table_schema.table_id_ << ";";
Z
zhiru 已提交
360

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

S
starlord 已提交
363
                mysqlpp::StoreQueryResult res = createTableQuery.store();
364

365 366 367
                if (res.num_rows() == 1) {
                    int state = res[0]["state"];
                    if (TableSchema::TO_DELETE == state) {
S
starlord 已提交
368
                        return Status(DB_ERROR, "Table already exists and it is in delete state, please wait a second");
369
                    } else {
S
starlord 已提交
370
                        return Status(DB_ALREADY_EXIST, "Table already exists");
371 372 373
                    }
                }
            }
374

375 376
            table_schema.id_ = -1;
            table_schema.created_on_ = utils::GetMicroSecTimeStamp();
Z
update  
zhiru 已提交
377

S
starlord 已提交
378
            std::string id = "NULL";  // auto-increment
G
groot 已提交
379
            std::string& table_id = table_schema.table_id_;
380 381 382
            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_);
S
starlord 已提交
383 384
            std::string flag = std::to_string(table_schema.flag_);
            std::string index_file_size = std::to_string(table_schema.index_file_size_);
385
            std::string engine_type = std::to_string(table_schema.engine_type_);
S
starlord 已提交
386 387
            std::string nlist = std::to_string(table_schema.nlist_);
            std::string metric_type = std::to_string(table_schema.metric_type_);
G
groot 已提交
388 389 390
            std::string& owner_table = table_schema.owner_table_;
            std::string& partition_tag = table_schema.partition_tag_;
            std::string& version = table_schema.version_;
Z
update  
zhiru 已提交
391

G
groot 已提交
392 393 394 395 396
            createTableQuery << "INSERT INTO " << META_TABLES << " VALUES(" << id << ", " << mysqlpp::quote << table_id
                             << ", " << state << ", " << dimension << ", " << created_on << ", " << flag << ", "
                             << index_file_size << ", " << engine_type << ", " << nlist << ", " << metric_type << ", "
                             << mysqlpp::quote << owner_table << ", " << mysqlpp::quote << partition_tag << ", "
                             << mysqlpp::quote << version << ");";
Z
update  
zhiru 已提交
397

398
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::CreateTable: " << createTableQuery.str();
399

S
starlord 已提交
400
            if (mysqlpp::SimpleResult res = createTableQuery.execute()) {
S
starlord 已提交
401
                table_schema.id_ = res.insert_id();  // Might need to use SELECT LAST_INSERT_ID()?
402

S
starlord 已提交
403
                // Consume all results to avoid "Commands out of sync" error
404
            } else {
S
starlord 已提交
405
                return HandleException("Add Table Error", createTableQuery.error());
406
            }
S
starlord 已提交
407
        }  // Scoped Connection
408

409
        ENGINE_LOG_DEBUG << "Successfully create table: " << table_schema.table_id_;
410
        return utils::CreateTablePath(options_, table_schema.table_id_);
S
starlord 已提交
411
    } catch (std::exception& e) {
S
starlord 已提交
412
        return HandleException("GENERAL ERROR WHEN CREATING TABLE", e.what());
413 414
    }
}
415

S
starlord 已提交
416
Status
G
groot 已提交
417
MySQLMetaImpl::DescribeTable(TableSchema& table_schema) {
Z
zhiru 已提交
418
    try {
G
groot 已提交
419
        server::MetricCollector metric;
S
starlord 已提交
420
        mysqlpp::StoreQueryResult res;
Z
zhiru 已提交
421
        {
S
starlord 已提交
422
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
Z
zhiru 已提交
423 424

            if (connectionPtr == nullptr) {
G
groot 已提交
425
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
426 427
            }

G
groot 已提交
428 429 430 431 432 433
            mysqlpp::Query describeTableQuery = connectionPtr->query();
            describeTableQuery
                << "SELECT id, state, dimension, created_on, flag, index_file_size, engine_type, nlist, metric_type"
                << " ,owner_table, partition_tag, version"
                << " FROM " << META_TABLES << " WHERE table_id = " << mysqlpp::quote << table_schema.table_id_
                << " AND state <> " << std::to_string(TableSchema::TO_DELETE) << ";";
Z
zhiru 已提交
434

G
groot 已提交
435
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::DescribeTable: " << describeTableQuery.str();
Z
zhiru 已提交
436

G
groot 已提交
437
            res = describeTableQuery.store();
S
starlord 已提交
438
        }  // Scoped Connection
Z
zhiru 已提交
439

G
groot 已提交
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
        if (res.num_rows() == 1) {
            const mysqlpp::Row& resRow = res[0];
            table_schema.id_ = resRow["id"];  // implicit conversion
            table_schema.state_ = resRow["state"];
            table_schema.dimension_ = resRow["dimension"];
            table_schema.created_on_ = resRow["created_on"];
            table_schema.flag_ = resRow["flag"];
            table_schema.index_file_size_ = resRow["index_file_size"];
            table_schema.engine_type_ = resRow["engine_type"];
            table_schema.nlist_ = resRow["nlist"];
            table_schema.metric_type_ = resRow["metric_type"];
            resRow["owner_table"].to_string(table_schema.owner_table_);
            resRow["partition_tag"].to_string(table_schema.partition_tag_);
            resRow["version"].to_string(table_schema.version_);
        } else {
            return Status(DB_NOT_FOUND, "Table " + table_schema.table_id_ + " not found");
456
        }
S
starlord 已提交
457
    } catch (std::exception& e) {
G
groot 已提交
458
        return HandleException("GENERAL ERROR WHEN DESCRIBING TABLE", e.what());
Z
zhiru 已提交
459 460
    }

461 462
    return Status::OK();
}
463

S
starlord 已提交
464
Status
G
groot 已提交
465
MySQLMetaImpl::HasTable(const std::string& table_id, bool& has_or_not) {
S
starlord 已提交
466
    try {
Y
Yu Kun 已提交
467
        server::MetricCollector metric;
G
groot 已提交
468
        mysqlpp::StoreQueryResult res;
S
starlord 已提交
469
        {
S
starlord 已提交
470
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
S
starlord 已提交
471 472

            if (connectionPtr == nullptr) {
G
groot 已提交
473
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
S
starlord 已提交
474 475
            }

G
groot 已提交
476 477 478 479 480 481 482
            mysqlpp::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 " << META_TABLES << " WHERE table_id = " << mysqlpp::quote << table_id
                          << " AND state <> " << std::to_string(TableSchema::TO_DELETE) << ")"
                          << " AS " << mysqlpp::quote << "check"
                          << ";";
S
starlord 已提交
483

G
groot 已提交
484
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::HasTable: " << hasTableQuery.str();
S
starlord 已提交
485

G
groot 已提交
486
            res = hasTableQuery.store();
S
starlord 已提交
487
        }  // Scoped Connection
S
starlord 已提交
488

G
groot 已提交
489 490
        int check = res[0]["check"];
        has_or_not = (check == 1);
S
starlord 已提交
491
    } catch (std::exception& e) {
G
groot 已提交
492
        return HandleException("GENERAL ERROR WHEN CHECKING IF TABLE EXISTS", e.what());
S
starlord 已提交
493 494
    }

495 496 497
    return Status::OK();
}

S
starlord 已提交
498
Status
G
groot 已提交
499
MySQLMetaImpl::AllTables(std::vector<TableSchema>& table_schema_array) {
S
starlord 已提交
500
    try {
Y
Yu Kun 已提交
501
        server::MetricCollector metric;
G
groot 已提交
502
        mysqlpp::StoreQueryResult res;
S
starlord 已提交
503
        {
S
starlord 已提交
504
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
S
starlord 已提交
505 506

            if (connectionPtr == nullptr) {
G
groot 已提交
507
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
S
starlord 已提交
508 509
            }

G
groot 已提交
510 511 512 513 514
            mysqlpp::Query allTablesQuery = connectionPtr->query();
            allTablesQuery << "SELECT id, table_id, dimension, engine_type, nlist, index_file_size, metric_type"
                           << " ,owner_table, partition_tag, version"
                           << " FROM " << META_TABLES << " WHERE state <> " << std::to_string(TableSchema::TO_DELETE)
                           << ";";
S
starlord 已提交
515

G
groot 已提交
516
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::AllTables: " << allTablesQuery.str();
S
starlord 已提交
517

G
groot 已提交
518
            res = allTablesQuery.store();
S
starlord 已提交
519
        }  // Scoped Connection
S
starlord 已提交
520

G
groot 已提交
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
        for (auto& resRow : res) {
            TableSchema table_schema;
            table_schema.id_ = resRow["id"];  // implicit conversion
            resRow["table_id"].to_string(table_schema.table_id_);
            table_schema.dimension_ = resRow["dimension"];
            table_schema.index_file_size_ = resRow["index_file_size"];
            table_schema.engine_type_ = resRow["engine_type"];
            table_schema.nlist_ = resRow["nlist"];
            table_schema.metric_type_ = resRow["metric_type"];
            resRow["owner_table"].to_string(table_schema.owner_table_);
            resRow["partition_tag"].to_string(table_schema.partition_tag_);
            resRow["version"].to_string(table_schema.version_);

            table_schema_array.emplace_back(table_schema);
        }
S
starlord 已提交
536
    } catch (std::exception& e) {
G
groot 已提交
537
        return HandleException("GENERAL ERROR WHEN DESCRIBING ALL TABLES", e.what());
S
starlord 已提交
538 539 540 541 542
    }

    return Status::OK();
}

S
starlord 已提交
543
Status
G
groot 已提交
544
MySQLMetaImpl::DropTable(const std::string& table_id) {
S
starlord 已提交
545
    try {
Y
Yu Kun 已提交
546
        server::MetricCollector metric;
S
starlord 已提交
547
        {
S
starlord 已提交
548
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
549

S
starlord 已提交
550
            if (connectionPtr == nullptr) {
G
groot 已提交
551
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
S
starlord 已提交
552 553
            }

G
groot 已提交
554 555 556 557 558
            // soft delete table
            mysqlpp::Query deleteTableQuery = connectionPtr->query();
            //
            deleteTableQuery << "UPDATE " << META_TABLES << " SET state = " << std::to_string(TableSchema::TO_DELETE)
                             << " WHERE table_id = " << mysqlpp::quote << table_id << ";";
S
starlord 已提交
559

G
groot 已提交
560
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::DeleteTable: " << deleteTableQuery.str();
S
starlord 已提交
561

G
groot 已提交
562 563
            if (!deleteTableQuery.exec()) {
                return HandleException("QUERY ERROR WHEN DELETING TABLE", deleteTableQuery.error());
S
starlord 已提交
564
            }
S
starlord 已提交
565
        }  // Scoped Connection
G
groot 已提交
566 567 568 569 570 571

        if (mode_ == DBOptions::MODE::CLUSTER_WRITABLE) {
            DeleteTableFiles(table_id);
        }

        ENGINE_LOG_DEBUG << "Successfully delete table, table id = " << table_id;
S
starlord 已提交
572
    } catch (std::exception& e) {
G
groot 已提交
573
        return HandleException("GENERAL ERROR WHEN DELETING TABLE", e.what());
S
starlord 已提交
574 575 576 577 578
    }

    return Status::OK();
}

S
starlord 已提交
579
Status
G
groot 已提交
580
MySQLMetaImpl::DeleteTableFiles(const std::string& table_id) {
S
starlord 已提交
581
    try {
Y
Yu Kun 已提交
582
        server::MetricCollector metric;
583
        {
S
starlord 已提交
584
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
585

586
            if (connectionPtr == nullptr) {
G
groot 已提交
587
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
588 589
            }

G
groot 已提交
590 591 592 593 594 595 596 597
            // soft delete table files
            mysqlpp::Query deleteTableFilesQuery = connectionPtr->query();
            //
            deleteTableFilesQuery << "UPDATE " << META_TABLEFILES
                                  << " SET file_type = " << std::to_string(TableFileSchema::TO_DELETE)
                                  << " ,updated_time = " << std::to_string(utils::GetMicroSecTimeStamp())
                                  << " WHERE table_id = " << mysqlpp::quote << table_id << " AND file_type <> "
                                  << std::to_string(TableFileSchema::TO_DELETE) << ";";
598

G
groot 已提交
599
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::DeleteTableFiles: " << deleteTableFilesQuery.str();
600

G
groot 已提交
601 602
            if (!deleteTableFilesQuery.exec()) {
                return HandleException("QUERY ERROR WHEN DELETING TABLE FILES", deleteTableFilesQuery.error());
S
starlord 已提交
603
            }
S
starlord 已提交
604
        }  // Scoped Connection
S
starlord 已提交
605

G
groot 已提交
606
        ENGINE_LOG_DEBUG << "Successfully delete table files, table id = " << table_id;
S
starlord 已提交
607
    } catch (std::exception& e) {
G
groot 已提交
608
        return HandleException("GENERAL ERROR WHEN DELETING TABLE FILES", e.what());
S
starlord 已提交
609
    }
610

S
starlord 已提交
611 612
    return Status::OK();
}
Z
update  
zhiru 已提交
613

S
starlord 已提交
614
Status
G
groot 已提交
615 616 617 618 619 620 621 622 623 624
MySQLMetaImpl::CreateTableFile(TableFileSchema& file_schema) {
    if (file_schema.date_ == EmptyDate) {
        file_schema.date_ = utils::GetDate();
    }
    TableSchema table_schema;
    table_schema.table_id_ = file_schema.table_id_;
    auto status = DescribeTable(table_schema);
    if (!status.ok()) {
        return status;
    }
Z
zhiru 已提交
625

G
groot 已提交
626 627
    try {
        server::MetricCollector metric;
Z
update  
zhiru 已提交
628

G
groot 已提交
629 630 631 632 633 634 635 636 637 638
        NextFileId(file_schema.file_id_);
        file_schema.dimension_ = table_schema.dimension_;
        file_schema.file_size_ = 0;
        file_schema.row_count_ = 0;
        file_schema.created_on_ = utils::GetMicroSecTimeStamp();
        file_schema.updated_time_ = file_schema.created_on_;
        file_schema.index_file_size_ = table_schema.index_file_size_;
        file_schema.engine_type_ = table_schema.engine_type_;
        file_schema.nlist_ = table_schema.nlist_;
        file_schema.metric_type_ = table_schema.metric_type_;
639

G
groot 已提交
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
        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 file_size = std::to_string(file_schema.file_size_);
        std::string row_count = std::to_string(file_schema.row_count_);
        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_);

        {
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);

            if (connectionPtr == nullptr) {
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
656
            }
Z
zhiru 已提交
657

G
groot 已提交
658
            mysqlpp::Query createTableFileQuery = connectionPtr->query();
Z
update  
zhiru 已提交
659

G
groot 已提交
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677
            createTableFileQuery << "INSERT INTO " << META_TABLEFILES << " VALUES(" << id << ", " << mysqlpp::quote
                                 << table_id << ", " << engine_type << ", " << mysqlpp::quote << file_id << ", "
                                 << file_type << ", " << file_size << ", " << row_count << ", " << updated_time << ", "
                                 << created_on << ", " << date << ");";

            ENGINE_LOG_DEBUG << "MySQLMetaImpl::CreateTableFile: " << createTableFileQuery.str();

            if (mysqlpp::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
            } else {
                return HandleException("QUERY ERROR WHEN CREATING TABLE FILE", createTableFileQuery.error());
            }
        }  // Scoped Connection

        ENGINE_LOG_DEBUG << "Successfully create table file, file id = " << file_schema.file_id_;
        return utils::CreateTableFilePath(options_, file_schema);
S
starlord 已提交
678
    } catch (std::exception& e) {
G
groot 已提交
679
        return HandleException("GENERAL ERROR WHEN CREATING TABLE FILE", e.what());
680 681
    }
}
Z
update  
zhiru 已提交
682

G
groot 已提交
683
// TODO(myh): Delete single vecotor by id
S
starlord 已提交
684
Status
G
groot 已提交
685 686 687 688 689 690 691 692 693 694 695 696
MySQLMetaImpl::DropDataByDate(const std::string& table_id, const DatesT& dates) {
    if (dates.empty()) {
        return Status::OK();
    }

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

697
    try {
G
groot 已提交
698 699 700 701 702 703 704
        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 ", "

705
        {
S
starlord 已提交
706
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
707 708

            if (connectionPtr == nullptr) {
G
groot 已提交
709
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
710
            }
711

G
groot 已提交
712
            mysqlpp::Query dropPartitionsByDatesQuery = connectionPtr->query();
713

G
groot 已提交
714 715 716 717 718
            dropPartitionsByDatesQuery << "UPDATE " << META_TABLEFILES
                                       << " SET file_type = " << std::to_string(TableFileSchema::TO_DELETE)
                                       << " ,updated_time = " << utils::GetMicroSecTimeStamp()
                                       << " WHERE table_id = " << mysqlpp::quote << table_id << " AND date in ("
                                       << dateListStr << ");";
719

G
groot 已提交
720 721 722 723 724
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::DropDataByDate: " << dropPartitionsByDatesQuery.str();

            if (!dropPartitionsByDatesQuery.exec()) {
                return HandleException("QUERY ERROR WHEN DROPPING PARTITIONS BY DATES",
                                       dropPartitionsByDatesQuery.error());
725
            }
S
starlord 已提交
726
        }  // Scoped Connection
727

G
groot 已提交
728
        ENGINE_LOG_DEBUG << "Successfully drop data by date, table id = " << table_schema.table_id_;
S
starlord 已提交
729
    } catch (std::exception& e) {
G
groot 已提交
730
        return HandleException("GENERAL ERROR WHEN DROPPING PARTITIONS BY DATES", e.what());
Z
update  
zhiru 已提交
731
    }
732 733
    return Status::OK();
}
Z
zhiru 已提交
734

S
starlord 已提交
735
Status
G
groot 已提交
736 737 738 739 740 741 742 743 744 745 746 747 748
MySQLMetaImpl::GetTableFiles(const std::string& table_id, const std::vector<size_t>& ids,
                             TableFilesSchema& table_files) {
    if (ids.empty()) {
        return Status::OK();
    }

    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 "

749
    try {
S
starlord 已提交
750
        mysqlpp::StoreQueryResult res;
751
        {
S
starlord 已提交
752
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
753

754
            if (connectionPtr == nullptr) {
G
groot 已提交
755
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
756
            }
Z
zhiru 已提交
757

G
groot 已提交
758 759 760 761 762
            mysqlpp::Query getTableFileQuery = connectionPtr->query();
            getTableFileQuery << "SELECT id, engine_type, file_id, file_type, file_size, row_count, date, created_on"
                              << " FROM " << META_TABLEFILES << " WHERE table_id = " << mysqlpp::quote << table_id
                              << " AND (" << idStr << ")"
                              << " AND file_type <> " << std::to_string(TableFileSchema::TO_DELETE) << ";";
763

G
groot 已提交
764
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::GetTableFiles: " << getTableFileQuery.str();
Z
update  
zhiru 已提交
765

G
groot 已提交
766
            res = getTableFileQuery.store();
S
starlord 已提交
767
        }  // Scoped Connection
768

G
groot 已提交
769 770 771
        TableSchema table_schema;
        table_schema.table_id_ = table_id;
        DescribeTable(table_schema);
S
starlord 已提交
772

G
groot 已提交
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
        Status ret;
        for (auto& resRow : res) {
            TableFileSchema file_schema;
            file_schema.id_ = resRow["id"];
            file_schema.table_id_ = table_id;
            file_schema.index_file_size_ = table_schema.index_file_size_;
            file_schema.engine_type_ = resRow["engine_type"];
            file_schema.nlist_ = table_schema.nlist_;
            file_schema.metric_type_ = table_schema.metric_type_;
            resRow["file_id"].to_string(file_schema.file_id_);
            file_schema.file_type_ = resRow["file_type"];
            file_schema.file_size_ = resRow["file_size"];
            file_schema.row_count_ = resRow["row_count"];
            file_schema.date_ = resRow["date"];
            file_schema.created_on_ = resRow["created_on"];
            file_schema.dimension_ = table_schema.dimension_;
S
starlord 已提交
789

G
groot 已提交
790 791
            utils::GetTableFilePath(options_, file_schema);
            table_files.emplace_back(file_schema);
792
        }
G
groot 已提交
793 794 795

        ENGINE_LOG_DEBUG << "Get table files by id";
        return ret;
S
starlord 已提交
796
    } catch (std::exception& e) {
G
groot 已提交
797
        return HandleException("GENERAL ERROR WHEN RETRIEVING TABLE FILES", e.what());
Z
update  
zhiru 已提交
798
    }
799
}
Z
zhiru 已提交
800

S
starlord 已提交
801
Status
G
groot 已提交
802
MySQLMetaImpl::UpdateTableIndex(const std::string& table_id, const TableIndex& index) {
803
    try {
Y
Yu Kun 已提交
804
        server::MetricCollector metric;
G
groot 已提交
805

806
        {
S
starlord 已提交
807
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
Z
update  
zhiru 已提交
808

809
            if (connectionPtr == nullptr) {
G
groot 已提交
810
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
811
            }
Z
update  
zhiru 已提交
812

G
groot 已提交
813 814 815 816
            mysqlpp::Query updateTableIndexParamQuery = connectionPtr->query();
            updateTableIndexParamQuery << "SELECT id, state, dimension, created_on"
                                       << " FROM " << META_TABLES << " WHERE table_id = " << mysqlpp::quote << table_id
                                       << " AND state <> " << std::to_string(TableSchema::TO_DELETE) << ";";
Z
update  
zhiru 已提交
817

G
groot 已提交
818
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::UpdateTableIndex: " << updateTableIndexParamQuery.str();
819

G
groot 已提交
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
            mysqlpp::StoreQueryResult res = updateTableIndexParamQuery.store();

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

                size_t id = resRow["id"];
                int32_t state = resRow["state"];
                uint16_t dimension = resRow["dimension"];
                int64_t created_on = resRow["created_on"];

                updateTableIndexParamQuery << "UPDATE " << META_TABLES << " SET id = " << id << " ,state = " << state
                                           << " ,dimension = " << dimension << " ,created_on = " << created_on
                                           << " ,engine_type = " << index.engine_type_ << " ,nlist = " << index.nlist_
                                           << " ,metric_type = " << index.metric_type_
                                           << " WHERE table_id = " << mysqlpp::quote << table_id << ";";

                ENGINE_LOG_DEBUG << "MySQLMetaImpl::UpdateTableIndex: " << updateTableIndexParamQuery.str();

                if (!updateTableIndexParamQuery.exec()) {
                    return HandleException("QUERY ERROR WHEN UPDATING TABLE INDEX PARAM",
                                           updateTableIndexParamQuery.error());
                }
            } else {
                return Status(DB_NOT_FOUND, "Table " + table_id + " not found");
            }
S
starlord 已提交
845
        }  // Scoped Connection
846

G
groot 已提交
847
        ENGINE_LOG_DEBUG << "Successfully update table index, table id = " << table_id;
S
starlord 已提交
848
    } catch (std::exception& e) {
G
groot 已提交
849
        return HandleException("GENERAL ERROR WHEN UPDATING TABLE INDEX PARAM", e.what());
850
    }
851

852 853
    return Status::OK();
}
854

S
starlord 已提交
855
Status
G
groot 已提交
856
MySQLMetaImpl::UpdateTableFlag(const std::string& table_id, int64_t flag) {
857
    try {
Y
Yu Kun 已提交
858
        server::MetricCollector metric;
G
groot 已提交
859

860
        {
S
starlord 已提交
861
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
862

863
            if (connectionPtr == nullptr) {
G
groot 已提交
864
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
865
            }
Z
update  
zhiru 已提交
866

G
groot 已提交
867 868 869
            mysqlpp::Query updateTableFlagQuery = connectionPtr->query();
            updateTableFlagQuery << "UPDATE " << META_TABLES << " SET flag = " << flag
                                 << " WHERE table_id = " << mysqlpp::quote << table_id << ";";
Z
zhiru 已提交
870

G
groot 已提交
871
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::UpdateTableFlag: " << updateTableFlagQuery.str();
Z
zhiru 已提交
872

G
groot 已提交
873 874 875
            if (!updateTableFlagQuery.exec()) {
                return HandleException("QUERY ERROR WHEN UPDATING TABLE FLAG", updateTableFlagQuery.error());
            }
S
starlord 已提交
876
        }  // Scoped Connection
877

G
groot 已提交
878
        ENGINE_LOG_DEBUG << "Successfully update table flag, table id = " << table_id;
S
starlord 已提交
879
    } catch (std::exception& e) {
G
groot 已提交
880
        return HandleException("GENERAL ERROR WHEN UPDATING TABLE FLAG", e.what());
881
    }
Z
update  
zhiru 已提交
882

883 884
    return Status::OK();
}
885

G
groot 已提交
886
// ZR: this function assumes all fields in file_schema have value
S
starlord 已提交
887
Status
G
groot 已提交
888 889
MySQLMetaImpl::UpdateTableFile(TableFileSchema& file_schema) {
    file_schema.updated_time_ = utils::GetMicroSecTimeStamp();
890

891
    try {
Y
Yu Kun 已提交
892
        server::MetricCollector metric;
G
groot 已提交
893 894
        {
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
Z
update  
zhiru 已提交
895

896
            if (connectionPtr == nullptr) {
G
groot 已提交
897
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
898
            }
Z
update  
zhiru 已提交
899

G
groot 已提交
900
            mysqlpp::Query updateTableFileQuery = connectionPtr->query();
901

G
groot 已提交
902 903 904 905
            // 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_TABLES << " WHERE table_id = " << mysqlpp::quote
                                 << file_schema.table_id_ << ";";
906

G
groot 已提交
907
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::UpdateTableFile: " << updateTableFileQuery.str();
908

G
groot 已提交
909
            mysqlpp::StoreQueryResult res = updateTableFileQuery.store();
910

G
groot 已提交
911 912 913 914 915
            if (res.num_rows() == 1) {
                int state = res[0]["state"];
                if (state == TableSchema::TO_DELETE) {
                    file_schema.file_type_ = TableFileSchema::TO_DELETE;
                }
916
            } else {
G
groot 已提交
917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
                file_schema.file_type_ = TableFileSchema::TO_DELETE;
            }

            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 file_size = std::to_string(file_schema.file_size_);
            std::string row_count = std::to_string(file_schema.row_count_);
            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 " << META_TABLEFILES << " SET table_id = " << mysqlpp::quote << table_id
                                 << " ,engine_type = " << engine_type << " ,file_id = " << mysqlpp::quote << file_id
                                 << " ,file_type = " << file_type << " ,file_size = " << file_size
                                 << " ,row_count = " << row_count << " ,updated_time = " << updated_time
                                 << " ,created_on = " << created_on << " ,date = " << date << " WHERE id = " << id
                                 << ";";

            ENGINE_LOG_DEBUG << "MySQLMetaImpl::UpdateTableFile: " << updateTableFileQuery.str();

            if (!updateTableFileQuery.exec()) {
                ENGINE_LOG_DEBUG << "table_id= " << file_schema.table_id_ << " file_id=" << file_schema.file_id_;
                return HandleException("QUERY ERROR WHEN UPDATING TABLE FILE", updateTableFileQuery.error());
943
            }
S
starlord 已提交
944
        }  // Scoped Connection
945

G
groot 已提交
946
        ENGINE_LOG_DEBUG << "Update single table file, file id = " << file_schema.file_id_;
S
starlord 已提交
947
    } catch (std::exception& e) {
G
groot 已提交
948
        return HandleException("GENERAL ERROR WHEN UPDATING TABLE FILE", e.what());
949
    }
G
groot 已提交
950 951

    return Status::OK();
952
}
953

S
starlord 已提交
954
Status
G
groot 已提交
955 956 957 958 959 960 961 962 963 964 965 966 967
MySQLMetaImpl::UpdateTableFilesToIndex(const std::string& table_id) {
    try {
        mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);

        if (connectionPtr == nullptr) {
            return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
        }

        mysqlpp::Query updateTableFilesToIndexQuery = connectionPtr->query();

        updateTableFilesToIndexQuery << "UPDATE " << META_TABLEFILES
                                     << " SET file_type = " << std::to_string(TableFileSchema::TO_INDEX)
                                     << " WHERE table_id = " << mysqlpp::quote << table_id
G
groot 已提交
968
                                     << " AND row_count >= " << std::to_string(meta::BUILD_INDEX_THRESHOLD)
G
groot 已提交
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
                                     << " AND file_type = " << std::to_string(TableFileSchema::RAW) << ";";

        ENGINE_LOG_DEBUG << "MySQLMetaImpl::UpdateTableFilesToIndex: " << updateTableFilesToIndexQuery.str();

        if (!updateTableFilesToIndexQuery.exec()) {
            return HandleException("QUERY ERROR WHEN UPDATING TABLE FILE TO INDEX",
                                   updateTableFilesToIndexQuery.error());
        }

        ENGINE_LOG_DEBUG << "Update files to to_index, table id = " << table_id;
    } catch (std::exception& e) {
        return HandleException("GENERAL ERROR WHEN UPDATING TABLE FILES TO INDEX", e.what());
    }

    return Status::OK();
}
985

G
groot 已提交
986 987
Status
MySQLMetaImpl::UpdateTableFiles(TableFilesSchema& files) {
988
    try {
Y
Yu Kun 已提交
989
        server::MetricCollector metric;
990
        {
S
starlord 已提交
991
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
992 993

            if (connectionPtr == nullptr) {
G
groot 已提交
994
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
995
            }
996

G
groot 已提交
997
            mysqlpp::Query updateTableFilesQuery = connectionPtr->query();
998

G
groot 已提交
999 1000 1001 1002 1003
            std::map<std::string, bool> has_tables;
            for (auto& file_schema : files) {
                if (has_tables.find(file_schema.table_id_) != has_tables.end()) {
                    continue;
                }
1004

G
groot 已提交
1005 1006 1007 1008 1009 1010
                updateTableFilesQuery << "SELECT EXISTS"
                                      << " (SELECT 1 FROM " << META_TABLES << " WHERE table_id = " << mysqlpp::quote
                                      << file_schema.table_id_ << " AND state <> "
                                      << std::to_string(TableSchema::TO_DELETE) << ")"
                                      << " AS " << mysqlpp::quote << "check"
                                      << ";";
1011

G
groot 已提交
1012
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::UpdateTableFiles: " << updateTableFilesQuery.str();
1013

G
groot 已提交
1014
                mysqlpp::StoreQueryResult res = updateTableFilesQuery.store();
1015

G
groot 已提交
1016 1017 1018
                int check = res[0]["check"];
                has_tables[file_schema.table_id_] = (check == 1);
            }
1019

G
groot 已提交
1020 1021 1022 1023 1024
            for (auto& file_schema : files) {
                if (!has_tables[file_schema.table_id_]) {
                    file_schema.file_type_ = TableFileSchema::TO_DELETE;
                }
                file_schema.updated_time_ = utils::GetMicroSecTimeStamp();
S
starlord 已提交
1025

G
groot 已提交
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
                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 file_size = std::to_string(file_schema.file_size_);
                std::string row_count = std::to_string(file_schema.row_count_);
                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_);
1036

G
groot 已提交
1037 1038 1039 1040 1041 1042
                updateTableFilesQuery << "UPDATE " << META_TABLEFILES << " SET table_id = " << mysqlpp::quote
                                      << table_id << " ,engine_type = " << engine_type
                                      << " ,file_id = " << mysqlpp::quote << file_id << " ,file_type = " << file_type
                                      << " ,file_size = " << file_size << " ,row_count = " << row_count
                                      << " ,updated_time = " << updated_time << " ,created_on = " << created_on
                                      << " ,date = " << date << " WHERE id = " << id << ";";
1043

G
groot 已提交
1044
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::UpdateTableFiles: " << updateTableFilesQuery.str();
S
starlord 已提交
1045

G
groot 已提交
1046 1047
                if (!updateTableFilesQuery.exec()) {
                    return HandleException("QUERY ERROR WHEN UPDATING TABLE FILES", updateTableFilesQuery.error());
1048
                }
S
starlord 已提交
1049
            }
G
groot 已提交
1050
        }  // Scoped Connection
1051

G
groot 已提交
1052
        ENGINE_LOG_DEBUG << "Update " << files.size() << " table files";
S
starlord 已提交
1053
    } catch (std::exception& e) {
G
groot 已提交
1054
        return HandleException("GENERAL ERROR WHEN UPDATING TABLE FILES", e.what());
Z
update  
zhiru 已提交
1055
    }
G
groot 已提交
1056 1057

    return Status::OK();
1058 1059
}

S
starlord 已提交
1060
Status
G
groot 已提交
1061
MySQLMetaImpl::DescribeTableIndex(const std::string& table_id, TableIndex& index) {
X
xj.lin 已提交
1062
    try {
Y
Yu Kun 已提交
1063
        server::MetricCollector metric;
G
groot 已提交
1064

X
xj.lin 已提交
1065
        {
S
starlord 已提交
1066
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
X
xj.lin 已提交
1067 1068

            if (connectionPtr == nullptr) {
G
groot 已提交
1069
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
X
xj.lin 已提交
1070 1071
            }

G
groot 已提交
1072 1073 1074 1075
            mysqlpp::Query describeTableIndexQuery = connectionPtr->query();
            describeTableIndexQuery << "SELECT engine_type, nlist, index_file_size, metric_type"
                                    << " FROM " << META_TABLES << " WHERE table_id = " << mysqlpp::quote << table_id
                                    << " AND state <> " << std::to_string(TableSchema::TO_DELETE) << ";";
X
xj.lin 已提交
1076

G
groot 已提交
1077
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::DescribeTableIndex: " << describeTableIndexQuery.str();
X
xj.lin 已提交
1078

G
groot 已提交
1079
            mysqlpp::StoreQueryResult res = describeTableIndexQuery.store();
X
xj.lin 已提交
1080

G
groot 已提交
1081 1082
            if (res.num_rows() == 1) {
                const mysqlpp::Row& resRow = res[0];
X
xj.lin 已提交
1083

G
groot 已提交
1084 1085 1086 1087 1088
                index.engine_type_ = resRow["engine_type"];
                index.nlist_ = resRow["nlist"];
                index.metric_type_ = resRow["metric_type"];
            } else {
                return Status(DB_NOT_FOUND, "Table " + table_id + " not found");
X
xj.lin 已提交
1089
            }
S
starlord 已提交
1090
        }  // Scoped Connection
G
groot 已提交
1091 1092 1093
    } catch (std::exception& e) {
        return HandleException("GENERAL ERROR WHEN UPDATING TABLE FLAG", e.what());
    }
X
xj.lin 已提交
1094

G
groot 已提交
1095 1096
    return Status::OK();
}
X
xj.lin 已提交
1097

G
groot 已提交
1098 1099 1100 1101
Status
MySQLMetaImpl::DropTableIndex(const std::string& table_id) {
    try {
        server::MetricCollector metric;
X
xj.lin 已提交
1102

G
groot 已提交
1103 1104
        {
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
X
xj.lin 已提交
1105

G
groot 已提交
1106 1107 1108
            if (connectionPtr == nullptr) {
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
            }
1109

G
groot 已提交
1110
            mysqlpp::Query dropTableIndexQuery = connectionPtr->query();
X
xj.lin 已提交
1111

G
groot 已提交
1112 1113 1114 1115 1116 1117
            // soft delete index files
            dropTableIndexQuery << "UPDATE " << META_TABLEFILES
                                << " SET file_type = " << std::to_string(TableFileSchema::TO_DELETE)
                                << " ,updated_time = " << utils::GetMicroSecTimeStamp()
                                << " WHERE table_id = " << mysqlpp::quote << table_id
                                << " AND file_type = " << std::to_string(TableFileSchema::INDEX) << ";";
S
starlord 已提交
1118

G
groot 已提交
1119
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::DropTableIndex: " << dropTableIndexQuery.str();
S
starlord 已提交
1120

G
groot 已提交
1121 1122 1123
            if (!dropTableIndexQuery.exec()) {
                return HandleException("QUERY ERROR WHEN DROPPING TABLE INDEX", dropTableIndexQuery.error());
            }
X
xj.lin 已提交
1124

G
groot 已提交
1125 1126 1127 1128 1129 1130
            // set all backup file to raw
            dropTableIndexQuery << "UPDATE " << META_TABLEFILES
                                << " SET file_type = " << std::to_string(TableFileSchema::RAW)
                                << " ,updated_time = " << utils::GetMicroSecTimeStamp()
                                << " WHERE table_id = " << mysqlpp::quote << table_id
                                << " AND file_type = " << std::to_string(TableFileSchema::BACKUP) << ";";
X
xj.lin 已提交
1131

G
groot 已提交
1132
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::DropTableIndex: " << dropTableIndexQuery.str();
S
starlord 已提交
1133

G
groot 已提交
1134 1135 1136
            if (!dropTableIndexQuery.exec()) {
                return HandleException("QUERY ERROR WHEN DROPPING TABLE INDEX", dropTableIndexQuery.error());
            }
X
xj.lin 已提交
1137

G
groot 已提交
1138 1139 1140
            // set table index type to raw
            dropTableIndexQuery << "UPDATE " << META_TABLES
                                << " SET engine_type = " << std::to_string(DEFAULT_ENGINE_TYPE)
1141
                                << " ,nlist = " << std::to_string(DEFAULT_NLIST)
G
groot 已提交
1142
                                << " WHERE table_id = " << mysqlpp::quote << table_id << ";";
X
xj.lin 已提交
1143

G
groot 已提交
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::DropTableIndex: " << dropTableIndexQuery.str();

            if (!dropTableIndexQuery.exec()) {
                return HandleException("QUERY ERROR WHEN DROPPING TABLE INDEX", dropTableIndexQuery.error());
            }
        }  // Scoped Connection

        ENGINE_LOG_DEBUG << "Successfully drop table index, table id = " << table_id;
    } catch (std::exception& e) {
        return HandleException("GENERAL ERROR WHEN DROPPING TABLE INDEX", e.what());
    }

    return Status::OK();
}

Status
MySQLMetaImpl::CreatePartition(const std::string& table_id, const std::string& partition_name, const std::string& tag) {
    server::MetricCollector metric;

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

    // not allow create partition under partition
    if (!table_schema.owner_table_.empty()) {
G
groot 已提交
1172
        return Status(DB_ERROR, "Nested partition is not allowed");
G
groot 已提交
1173 1174
    }

1175 1176 1177 1178
    // trim side-blank of tag, only compare valid characters
    // for example: " ab cd " is treated as "ab cd"
    std::string valid_tag = tag;
    server::StringHelpFunctions::TrimStringBlank(valid_tag);
G
groot 已提交
1179

1180 1181 1182 1183
    // not allow duplicated partition
    std::string exist_partition;
    GetPartitionName(table_id, valid_tag, exist_partition);
    if (!exist_partition.empty()) {
G
groot 已提交
1184
        return Status(DB_ERROR, "Duplicate partition is not allowed");
1185 1186 1187 1188
    }

    if (partition_name == "") {
        // generate unique partition name
G
groot 已提交
1189 1190 1191 1192 1193 1194 1195 1196 1197
        NextTableId(table_schema.table_id_);
    } else {
        table_schema.table_id_ = partition_name;
    }

    table_schema.id_ = -1;
    table_schema.flag_ = 0;
    table_schema.created_on_ = utils::GetMicroSecTimeStamp();
    table_schema.owner_table_ = table_id;
1198
    table_schema.partition_tag_ = valid_tag;
G
groot 已提交
1199

1200 1201 1202 1203 1204 1205
    status = CreateTable(table_schema);
    if (status.code() == DB_ALREADY_EXIST) {
        return Status(DB_ALREADY_EXIST, "Partition already exists");
    }

    return status;
G
groot 已提交
1206 1207 1208 1209 1210 1211 1212 1213
}

Status
MySQLMetaImpl::DropPartition(const std::string& partition_name) {
    return DropTable(partition_name);
}

Status
G
groot 已提交
1214
MySQLMetaImpl::ShowPartitions(const std::string& table_id, std::vector<meta::TableSchema>& partition_schema_array) {
G
groot 已提交
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
    try {
        server::MetricCollector metric;
        mysqlpp::StoreQueryResult res;
        {
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);

            if (connectionPtr == nullptr) {
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
            }

            mysqlpp::Query allPartitionsQuery = connectionPtr->query();
            allPartitionsQuery << "SELECT table_id FROM " << META_TABLES << " WHERE owner_table = " << mysqlpp::quote
                               << table_id << " AND state <> " << std::to_string(TableSchema::TO_DELETE) << ";";

            ENGINE_LOG_DEBUG << "MySQLMetaImpl::AllTables: " << allPartitionsQuery.str();

            res = allPartitionsQuery.store();
        }  // Scoped Connection

        for (auto& resRow : res) {
            meta::TableSchema partition_schema;
            resRow["table_id"].to_string(partition_schema.table_id_);
            DescribeTable(partition_schema);
G
groot 已提交
1238
            partition_schema_array.emplace_back(partition_schema);
G
groot 已提交
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
        }
    } catch (std::exception& e) {
        return HandleException("GENERAL ERROR WHEN SHOW PARTITIONS", e.what());
    }

    return Status::OK();
}

Status
MySQLMetaImpl::GetPartitionName(const std::string& table_id, const std::string& tag, std::string& partition_name) {
    try {
        server::MetricCollector metric;
        mysqlpp::StoreQueryResult res;
1252 1253 1254 1255 1256 1257

        // trim side-blank of tag, only compare valid characters
        // for example: " ab cd " is treated as "ab cd"
        std::string valid_tag = tag;
        server::StringHelpFunctions::TrimStringBlank(valid_tag);

G
groot 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266
        {
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);

            if (connectionPtr == nullptr) {
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
            }

            mysqlpp::Query allPartitionsQuery = connectionPtr->query();
            allPartitionsQuery << "SELECT table_id FROM " << META_TABLES << " WHERE owner_table = " << mysqlpp::quote
1267
                               << table_id << " AND partition_tag = " << mysqlpp::quote << valid_tag << " AND state <> "
G
groot 已提交
1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278
                               << std::to_string(TableSchema::TO_DELETE) << ";";

            ENGINE_LOG_DEBUG << "MySQLMetaImpl::AllTables: " << allPartitionsQuery.str();

            res = allPartitionsQuery.store();
        }  // Scoped Connection

        if (res.num_rows() > 0) {
            const mysqlpp::Row& resRow = res[0];
            resRow["table_id"].to_string(partition_name);
        } else {
1279
            return Status(DB_NOT_FOUND, "Partition " + valid_tag + " of table " + table_id + " not found");
G
groot 已提交
1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
        }
    } catch (std::exception& e) {
        return HandleException("GENERAL ERROR WHEN GET PARTITION NAME", e.what());
    }

    return Status::OK();
}

Status
MySQLMetaImpl::FilesToSearch(const std::string& table_id, const std::vector<size_t>& ids, const DatesT& dates,
                             DatePartionedTableFilesSchema& files) {
    files.clear();

    try {
        server::MetricCollector metric;
        mysqlpp::StoreQueryResult res;
        {
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);

            if (connectionPtr == nullptr) {
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
            }

            mysqlpp::Query filesToSearchQuery = connectionPtr->query();
            filesToSearchQuery << "SELECT id, table_id, engine_type, file_id, file_type, file_size, row_count, date"
                               << " FROM " << META_TABLEFILES << " WHERE table_id = " << mysqlpp::quote << table_id;

            if (!dates.empty()) {
                std::stringstream partitionListSS;
                for (auto& date : dates) {
                    partitionListSS << std::to_string(date) << ", ";
                }
                std::string partitionListStr = partitionListSS.str();

                partitionListStr = partitionListStr.substr(0, partitionListStr.size() - 2);  // remove the last ", "
                filesToSearchQuery << " AND date IN (" << partitionListStr << ")";
            }

            if (!ids.empty()) {
                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 "

                filesToSearchQuery << " AND (" << idStr << ")";
            }
            // End
            filesToSearchQuery << " 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) << ");";

            ENGINE_LOG_DEBUG << "MySQLMetaImpl::FilesToSearch: " << filesToSearchQuery.str();

            res = filesToSearchQuery.store();
        }  // Scoped Connection

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

        Status ret;
        TableFileSchema table_file;
        for (auto& resRow : res) {
            table_file.id_ = resRow["id"];  // implicit conversion
            resRow["table_id"].to_string(table_file.table_id_);
            table_file.index_file_size_ = table_schema.index_file_size_;
            table_file.engine_type_ = resRow["engine_type"];
            table_file.nlist_ = table_schema.nlist_;
            table_file.metric_type_ = table_schema.metric_type_;
            resRow["file_id"].to_string(table_file.file_id_);
            table_file.file_type_ = resRow["file_type"];
            table_file.file_size_ = resRow["file_size"];
            table_file.row_count_ = resRow["row_count"];
            table_file.date_ = resRow["date"];
            table_file.dimension_ = table_schema.dimension_;
X
xj.lin 已提交
1361

S
starlord 已提交
1362
            auto status = utils::GetTableFilePath(options_, table_file);
S
starlord 已提交
1363
            if (!status.ok()) {
S
starlord 已提交
1364
                ret = status;
S
starlord 已提交
1365
            }
1366

1367 1368 1369
            auto dateItr = files.find(table_file.date_);
            if (dateItr == files.end()) {
                files[table_file.date_] = TableFilesSchema();
1370 1371
            }

1372
            files[table_file.date_].push_back(table_file);
1373
        }
S
starlord 已提交
1374

S
starlord 已提交
1375
        if (res.size() > 0) {
1376 1377
            ENGINE_LOG_DEBUG << "Collect " << res.size() << " to-search files";
        }
S
starlord 已提交
1378
        return ret;
S
starlord 已提交
1379
    } catch (std::exception& e) {
S
starlord 已提交
1380
        return HandleException("GENERAL ERROR WHEN FINDING TABLE FILES TO SEARCH", e.what());
Z
update  
zhiru 已提交
1381
    }
1382
}
Z
update  
zhiru 已提交
1383

S
starlord 已提交
1384
Status
S
starlord 已提交
1385
MySQLMetaImpl::FilesToMerge(const std::string& table_id, DatePartionedTableFilesSchema& files) {
1386
    files.clear();
Z
update  
zhiru 已提交
1387

1388
    try {
Y
Yu Kun 已提交
1389
        server::MetricCollector metric;
S
starlord 已提交
1390

S
starlord 已提交
1391
        // check table existence
S
starlord 已提交
1392 1393 1394 1395 1396 1397 1398
        TableSchema table_schema;
        table_schema.table_id_ = table_id;
        auto status = DescribeTable(table_schema);
        if (!status.ok()) {
            return status;
        }

S
starlord 已提交
1399
        mysqlpp::StoreQueryResult res;
1400
        {
S
starlord 已提交
1401
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
Z
update  
zhiru 已提交
1402

1403
            if (connectionPtr == nullptr) {
G
groot 已提交
1404
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
1405
            }
Z
update  
zhiru 已提交
1406

S
starlord 已提交
1407 1408
            mysqlpp::Query filesToMergeQuery = connectionPtr->query();
            filesToMergeQuery
G
groot 已提交
1409 1410 1411
                << "SELECT id, table_id, file_id, file_type, file_size, row_count, date, engine_type, created_on"
                << " FROM " << META_TABLEFILES << " WHERE table_id = " << mysqlpp::quote << table_id
                << " AND file_type = " << std::to_string(TableFileSchema::RAW) << " ORDER BY row_count DESC;";
Z
update  
zhiru 已提交
1412

1413
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::FilesToMerge: " << filesToMergeQuery.str();
1414

1415
            res = filesToMergeQuery.store();
S
starlord 已提交
1416
        }  // Scoped Connection
1417

S
starlord 已提交
1418
        Status ret;
1419
        int64_t to_merge_files = 0;
S
starlord 已提交
1420
        for (auto& resRow : res) {
S
starlord 已提交
1421 1422
            TableFileSchema table_file;
            table_file.file_size_ = resRow["file_size"];
S
starlord 已提交
1423
            if (table_file.file_size_ >= table_schema.index_file_size_) {
S
starlord 已提交
1424
                continue;  // skip large file
S
starlord 已提交
1425
            }
Z
update  
zhiru 已提交
1426

S
starlord 已提交
1427
            table_file.id_ = resRow["id"];  // implicit conversion
G
groot 已提交
1428 1429
            resRow["table_id"].to_string(table_file.table_id_);
            resRow["file_id"].to_string(table_file.file_id_);
1430
            table_file.file_type_ = resRow["file_type"];
S
starlord 已提交
1431
            table_file.row_count_ = resRow["row_count"];
1432
            table_file.date_ = resRow["date"];
1433
            table_file.index_file_size_ = table_schema.index_file_size_;
S
starlord 已提交
1434
            table_file.engine_type_ = resRow["engine_type"];
S
starlord 已提交
1435
            table_file.nlist_ = table_schema.nlist_;
S
starlord 已提交
1436
            table_file.metric_type_ = table_schema.metric_type_;
S
starlord 已提交
1437
            table_file.created_on_ = resRow["created_on"];
1438
            table_file.dimension_ = table_schema.dimension_;
Z
update  
zhiru 已提交
1439

S
starlord 已提交
1440
            auto status = utils::GetTableFilePath(options_, table_file);
S
starlord 已提交
1441
            if (!status.ok()) {
S
starlord 已提交
1442
                ret = status;
S
starlord 已提交
1443
            }
Z
update  
zhiru 已提交
1444

1445 1446 1447
            auto dateItr = files.find(table_file.date_);
            if (dateItr == files.end()) {
                files[table_file.date_] = TableFilesSchema();
1448
                to_merge_files++;
1449
            }
1450 1451

            files[table_file.date_].push_back(table_file);
1452
        }
Z
update  
zhiru 已提交
1453

1454 1455
        if (to_merge_files > 0) {
            ENGINE_LOG_TRACE << "Collect " << to_merge_files << " to-merge files";
1456
        }
S
starlord 已提交
1457
        return ret;
S
starlord 已提交
1458
    } catch (std::exception& e) {
S
starlord 已提交
1459
        return HandleException("GENERAL ERROR WHEN FINDING TABLE FILES TO MERGE", e.what());
1460 1461 1462
    }
}

S
starlord 已提交
1463
Status
G
groot 已提交
1464 1465
MySQLMetaImpl::FilesToIndex(TableFilesSchema& files) {
    files.clear();
Z
zhiru 已提交
1466

1467
    try {
G
groot 已提交
1468
        server::MetricCollector metric;
S
starlord 已提交
1469
        mysqlpp::StoreQueryResult res;
1470
        {
S
starlord 已提交
1471
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
1472 1473

            if (connectionPtr == nullptr) {
G
groot 已提交
1474
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
1475 1476
            }

G
groot 已提交
1477 1478 1479 1480 1481
            mysqlpp::Query filesToIndexQuery = connectionPtr->query();
            filesToIndexQuery
                << "SELECT id, table_id, engine_type, file_id, file_type, file_size, row_count, date, created_on"
                << " FROM " << META_TABLEFILES << " WHERE file_type = " << std::to_string(TableFileSchema::TO_INDEX)
                << ";";
1482

G
groot 已提交
1483
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::FilesToIndex: " << filesToIndexQuery.str();
1484

G
groot 已提交
1485
            res = filesToIndexQuery.store();
S
starlord 已提交
1486
        }  // Scoped Connection
1487

S
starlord 已提交
1488
        Status ret;
G
groot 已提交
1489 1490
        std::map<std::string, TableSchema> groups;
        TableFileSchema table_file;
S
starlord 已提交
1491
        for (auto& resRow : res) {
G
groot 已提交
1492 1493 1494 1495 1496 1497 1498 1499 1500
            table_file.id_ = resRow["id"];  // implicit conversion
            resRow["table_id"].to_string(table_file.table_id_);
            table_file.engine_type_ = resRow["engine_type"];
            resRow["file_id"].to_string(table_file.file_id_);
            table_file.file_type_ = resRow["file_type"];
            table_file.file_size_ = resRow["file_size"];
            table_file.row_count_ = resRow["row_count"];
            table_file.date_ = resRow["date"];
            table_file.created_on_ = resRow["created_on"];
Z
update  
zhiru 已提交
1501

G
groot 已提交
1502 1503 1504 1505 1506 1507 1508
            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;
1509
                }
G
groot 已提交
1510
                groups[table_file.table_id_] = table_schema;
Z
zhiru 已提交
1511
            }
G
groot 已提交
1512 1513 1514 1515
            table_file.dimension_ = groups[table_file.table_id_].dimension_;
            table_file.index_file_size_ = groups[table_file.table_id_].index_file_size_;
            table_file.nlist_ = groups[table_file.table_id_].nlist_;
            table_file.metric_type_ = groups[table_file.table_id_].metric_type_;
1516

G
groot 已提交
1517 1518 1519
            auto status = utils::GetTableFilePath(options_, table_file);
            if (!status.ok()) {
                ret = status;
1520
            }
Z
zhiru 已提交
1521

G
groot 已提交
1522 1523
            files.push_back(table_file);
        }
Z
update  
zhiru 已提交
1524

G
groot 已提交
1525 1526
        if (res.size() > 0) {
            ENGINE_LOG_DEBUG << "Collect " << res.size() << " to-index files";
1527
        }
G
groot 已提交
1528
        return ret;
S
starlord 已提交
1529
    } catch (std::exception& e) {
G
groot 已提交
1530
        return HandleException("GENERAL ERROR WHEN FINDING TABLE FILES TO INDEX", e.what());
1531 1532
    }
}
1533

S
starlord 已提交
1534
Status
G
groot 已提交
1535
MySQLMetaImpl::FilesByType(const std::string& table_id, const std::vector<int>& file_types,
G
groot 已提交
1536
                           TableFilesSchema& table_files) {
G
groot 已提交
1537 1538
    if (file_types.empty()) {
        return Status(DB_ERROR, "file types array is empty");
Z
update  
zhiru 已提交
1539 1540
    }

1541
    try {
G
groot 已提交
1542
        table_files.clear();
G
groot 已提交
1543 1544

        mysqlpp::StoreQueryResult res;
1545
        {
S
starlord 已提交
1546
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
1547

1548
            if (connectionPtr == nullptr) {
G
groot 已提交
1549
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
1550
            }
Z
zhiru 已提交
1551

G
groot 已提交
1552 1553 1554 1555
            std::string types;
            for (auto type : file_types) {
                if (!types.empty()) {
                    types += ",";
Z
update  
zhiru 已提交
1556
                }
G
groot 已提交
1557
                types += std::to_string(type);
1558
            }
Z
update  
zhiru 已提交
1559

G
groot 已提交
1560 1561
            mysqlpp::Query hasNonIndexFilesQuery = connectionPtr->query();
            // since table_id is a unique column we just need to check whether it exists or not
G
groot 已提交
1562 1563 1564 1565
            hasNonIndexFilesQuery
                << "SELECT id, engine_type, file_id, file_type, file_size, row_count, date, created_on"
                << " FROM " << META_TABLEFILES << " WHERE table_id = " << mysqlpp::quote << table_id
                << " AND file_type in (" << types << ");";
1566

G
groot 已提交
1567
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::FilesByType: " << hasNonIndexFilesQuery.str();
Z
update  
zhiru 已提交
1568

G
groot 已提交
1569
            res = hasNonIndexFilesQuery.store();
S
starlord 已提交
1570
        }  // Scoped Connection
1571

G
groot 已提交
1572 1573 1574 1575
        if (res.num_rows() > 0) {
            int raw_count = 0, new_count = 0, new_merge_count = 0, new_index_count = 0;
            int to_index_count = 0, index_count = 0, backup_count = 0;
            for (auto& resRow : res) {
G
groot 已提交
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
                TableFileSchema file_schema;
                file_schema.id_ = resRow["id"];
                file_schema.table_id_ = table_id;
                file_schema.engine_type_ = resRow["engine_type"];
                resRow["file_id"].to_string(file_schema.file_id_);
                file_schema.file_type_ = resRow["file_type"];
                file_schema.file_size_ = resRow["file_size"];
                file_schema.row_count_ = resRow["row_count"];
                file_schema.date_ = resRow["date"];
                file_schema.created_on_ = resRow["created_on"];

                table_files.emplace_back(file_schema);
1588

G
groot 已提交
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
                int32_t file_type = resRow["file_type"];
                switch (file_type) {
                    case (int)TableFileSchema::RAW:
                        raw_count++;
                        break;
                    case (int)TableFileSchema::NEW:
                        new_count++;
                        break;
                    case (int)TableFileSchema::NEW_MERGE:
                        new_merge_count++;
                        break;
                    case (int)TableFileSchema::NEW_INDEX:
                        new_index_count++;
                        break;
                    case (int)TableFileSchema::TO_INDEX:
                        to_index_count++;
                        break;
                    case (int)TableFileSchema::INDEX:
                        index_count++;
                        break;
                    case (int)TableFileSchema::BACKUP:
                        backup_count++;
                        break;
                    default:
                        break;
Z
update  
zhiru 已提交
1614
                }
1615 1616
            }

G
groot 已提交
1617
            std::string msg = "Get table files by type.";
G
groot 已提交
1618 1619 1620
            for (int file_type : file_types) {
                switch (file_type) {
                    case (int)TableFileSchema::RAW:
G
groot 已提交
1621
                        msg = msg + " raw files:" + std::to_string(raw_count);
G
groot 已提交
1622 1623
                        break;
                    case (int)TableFileSchema::NEW:
G
groot 已提交
1624
                        msg = msg + " new files:" + std::to_string(new_count);
G
groot 已提交
1625 1626
                        break;
                    case (int)TableFileSchema::NEW_MERGE:
G
groot 已提交
1627
                        msg = msg + " new_merge files:" + std::to_string(new_merge_count);
G
groot 已提交
1628 1629
                        break;
                    case (int)TableFileSchema::NEW_INDEX:
G
groot 已提交
1630
                        msg = msg + " new_index files:" + std::to_string(new_index_count);
G
groot 已提交
1631 1632
                        break;
                    case (int)TableFileSchema::TO_INDEX:
G
groot 已提交
1633
                        msg = msg + " to_index files:" + std::to_string(to_index_count);
G
groot 已提交
1634 1635
                        break;
                    case (int)TableFileSchema::INDEX:
G
groot 已提交
1636
                        msg = msg + " index files:" + std::to_string(index_count);
G
groot 已提交
1637 1638
                        break;
                    case (int)TableFileSchema::BACKUP:
G
groot 已提交
1639
                        msg = msg + " backup files:" + std::to_string(backup_count);
G
groot 已提交
1640
                        break;
1641 1642
                    default:
                        break;
G
groot 已提交
1643 1644 1645
                }
            }
            ENGINE_LOG_DEBUG << msg;
G
groot 已提交
1646
        }
S
starlord 已提交
1647
    } catch (std::exception& e) {
G
groot 已提交
1648
        return HandleException("GENERAL ERROR WHEN GET FILE BY TYPE", e.what());
1649
    }
S
starlord 已提交
1650

1651 1652
    return Status::OK();
}
1653

G
groot 已提交
1654
// TODO(myh): Support swap to cloud storage
S
starlord 已提交
1655
Status
G
groot 已提交
1656 1657 1658 1659 1660
MySQLMetaImpl::Archive() {
    auto& criterias = options_.archive_conf_.GetCriterias();
    if (criterias.empty()) {
        return Status::OK();
    }
1661

G
groot 已提交
1662 1663 1664 1665
    for (auto& kv : criterias) {
        auto& criteria = kv.first;
        auto& limit = kv.second;
        if (criteria == engine::ARCHIVE_CONF_DAYS) {
1666
            size_t usecs = limit * DAY * US_PS;
G
groot 已提交
1667
            int64_t now = utils::GetMicroSecTimeStamp();
Z
update  
zhiru 已提交
1668

G
groot 已提交
1669 1670
            try {
                mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
Z
zhiru 已提交
1671

G
groot 已提交
1672 1673 1674
                if (connectionPtr == nullptr) {
                    return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
                }
1675

G
groot 已提交
1676 1677 1678 1679 1680
                mysqlpp::Query archiveQuery = connectionPtr->query();
                archiveQuery << "UPDATE " << META_TABLEFILES
                             << " SET file_type = " << std::to_string(TableFileSchema::TO_DELETE)
                             << " WHERE created_on < " << std::to_string(now - usecs) << " AND file_type <> "
                             << std::to_string(TableFileSchema::TO_DELETE) << ";";
Z
update  
zhiru 已提交
1681

G
groot 已提交
1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::Archive: " << archiveQuery.str();

                if (!archiveQuery.exec()) {
                    return HandleException("QUERY ERROR DURING ARCHIVE", archiveQuery.error());
                }

                ENGINE_LOG_DEBUG << "Archive old files";
            } catch (std::exception& e) {
                return HandleException("GENERAL ERROR WHEN DURING ARCHIVE", e.what());
            }
Z
fix  
zhiru 已提交
1692
        }
G
groot 已提交
1693 1694 1695
        if (criteria == engine::ARCHIVE_CONF_DISK) {
            uint64_t sum = 0;
            Size(sum);
Z
fix  
zhiru 已提交
1696

G
groot 已提交
1697 1698 1699 1700 1701
            auto to_delete = (sum - limit * G);
            DiscardFiles(to_delete);

            ENGINE_LOG_DEBUG << "Archive files to free disk";
        }
1702
    }
Z
update  
zhiru 已提交
1703

1704 1705
    return Status::OK();
}
Z
zhiru 已提交
1706

S
starlord 已提交
1707
Status
G
groot 已提交
1708 1709 1710
MySQLMetaImpl::Size(uint64_t& result) {
    result = 0;

1711
    try {
G
groot 已提交
1712
        mysqlpp::StoreQueryResult res;
1713
        {
S
starlord 已提交
1714
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
1715 1716

            if (connectionPtr == nullptr) {
G
groot 已提交
1717
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
1718
            }
Z
update  
zhiru 已提交
1719

G
groot 已提交
1720 1721 1722 1723
            mysqlpp::Query getSizeQuery = connectionPtr->query();
            getSizeQuery << "SELECT IFNULL(SUM(file_size),0) AS sum"
                         << " FROM " << META_TABLEFILES << " WHERE file_type <> "
                         << std::to_string(TableFileSchema::TO_DELETE) << ";";
1724

G
groot 已提交
1725
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::Size: " << getSizeQuery.str();
1726

G
groot 已提交
1727 1728
            res = getSizeQuery.store();
        }  // Scoped Connection
1729

G
groot 已提交
1730 1731 1732 1733 1734 1735 1736 1737
        if (res.empty()) {
            result = 0;
        } else {
            result = res[0]["sum"];
        }
    } catch (std::exception& e) {
        return HandleException("GENERAL ERROR WHEN RETRIEVING SIZE", e.what());
    }
1738

G
groot 已提交
1739 1740
    return Status::OK();
}
1741

G
groot 已提交
1742
Status
1743
MySQLMetaImpl::CleanUpShadowFiles() {
G
groot 已提交
1744 1745
    try {
        mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
1746

G
groot 已提交
1747 1748 1749
        if (connectionPtr == nullptr) {
            return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
        }
1750

G
groot 已提交
1751 1752 1753 1754 1755
        mysqlpp::Query cleanUpQuery = connectionPtr->query();
        cleanUpQuery << "SELECT table_name"
                     << " FROM information_schema.tables"
                     << " WHERE table_schema = " << mysqlpp::quote << mysql_connection_pool_->getDB()
                     << " AND table_name = " << mysqlpp::quote << META_TABLEFILES << ";";
Z
fix  
zhiru 已提交
1756

G
groot 已提交
1757
        ENGINE_LOG_DEBUG << "MySQLMetaImpl::CleanUp: " << cleanUpQuery.str();
1758

G
groot 已提交
1759
        mysqlpp::StoreQueryResult res = cleanUpQuery.store();
1760

G
groot 已提交
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
        if (!res.empty()) {
            ENGINE_LOG_DEBUG << "Remove table file type as NEW";
            cleanUpQuery << "DELETE FROM " << META_TABLEFILES << " WHERE file_type IN ("
                         << std::to_string(TableFileSchema::NEW) << "," << std::to_string(TableFileSchema::NEW_MERGE)
                         << "," << std::to_string(TableFileSchema::NEW_INDEX) << ");";

            ENGINE_LOG_DEBUG << "MySQLMetaImpl::CleanUp: " << cleanUpQuery.str();

            if (!cleanUpQuery.exec()) {
                return HandleException("QUERY ERROR WHEN CLEANING UP FILES", cleanUpQuery.error());
1771
            }
G
groot 已提交
1772
        }
1773

G
groot 已提交
1774 1775 1776
        if (res.size() > 0) {
            ENGINE_LOG_DEBUG << "Clean " << res.size() << " files";
        }
S
starlord 已提交
1777
    } catch (std::exception& e) {
G
groot 已提交
1778
        return HandleException("GENERAL ERROR WHEN CLEANING UP FILES", e.what());
1779
    }
S
starlord 已提交
1780

1781 1782
    return Status::OK();
}
Z
fix  
zhiru 已提交
1783

1784
Status
G
groot 已提交
1785
MySQLMetaImpl::CleanUpFilesWithTTL(uint64_t seconds, CleanUpFilter* filter) {
1786
    auto now = utils::GetMicroSecTimeStamp();
S
starlord 已提交
1787 1788
    std::set<std::string> table_ids;

S
starlord 已提交
1789
    // remove to_delete files
1790
    try {
Y
Yu Kun 已提交
1791
        server::MetricCollector metric;
1792

1793
        {
S
starlord 已提交
1794
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
Z
update  
zhiru 已提交
1795

1796
            if (connectionPtr == nullptr) {
G
groot 已提交
1797
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
1798
            }
Z
zhiru 已提交
1799

1800
            mysqlpp::Query query = connectionPtr->query();
G
groot 已提交
1801
            query << "SELECT id, table_id, file_id, file_type, date"
G
groot 已提交
1802
                  << " FROM " << META_TABLEFILES << " WHERE file_type IN ("
G
groot 已提交
1803
                  << std::to_string(TableFileSchema::TO_DELETE) << "," << std::to_string(TableFileSchema::BACKUP) << ")"
1804
                  << " AND updated_time < " << std::to_string(now - seconds * US_PS) << ";";
Z
update  
zhiru 已提交
1805

1806
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::CleanUpFilesWithTTL: " << query.str();
Z
update  
zhiru 已提交
1807

1808
            mysqlpp::StoreQueryResult res = query.store();
Z
update  
zhiru 已提交
1809

1810 1811
            TableFileSchema table_file;
            std::vector<std::string> idsToDelete;
1812

G
groot 已提交
1813
            int64_t clean_files = 0;
S
starlord 已提交
1814 1815
            for (auto& resRow : res) {
                table_file.id_ = resRow["id"];  // implicit conversion
G
groot 已提交
1816 1817
                resRow["table_id"].to_string(table_file.table_id_);
                resRow["file_id"].to_string(table_file.file_id_);
1818
                table_file.date_ = resRow["date"];
G
groot 已提交
1819
                table_file.file_type_ = resRow["file_type"];
Z
update  
zhiru 已提交
1820

G
groot 已提交
1821
                // check if the file can be deleted
G
groot 已提交
1822 1823 1824 1825
                if (filter && filter->IsIgnored(table_file)) {
                    ENGINE_LOG_DEBUG << "File:" << table_file.file_id_
                                     << " currently is in use, not able to delete now";
                    continue;  // ignore this file, don't delete it
G
groot 已提交
1826
                }
1827

G
groot 已提交
1828
                // erase file data from cache
G
groot 已提交
1829 1830
                // because GetTableFilePath won't able to generate file path after the file is deleted
                utils::GetTableFilePath(options_, table_file);
G
groot 已提交
1831 1832
                server::CommonUtil::EraseFromCache(table_file.location_);

G
groot 已提交
1833 1834 1835
                if (table_file.file_type_ == (int)TableFileSchema::TO_DELETE) {
                    // delete file from disk storage
                    utils::DeleteTableFilePath(options_, table_file);
G
groot 已提交
1836
                    ENGINE_LOG_DEBUG << "Remove file id:" << table_file.id_ << " location:" << table_file.location_;
G
groot 已提交
1837 1838 1839 1840

                    idsToDelete.emplace_back(std::to_string(table_file.id_));
                    table_ids.insert(table_file.table_id_);

G
typo  
groot 已提交
1841 1842
                    clean_files++;
                }
1843 1844
            }

G
groot 已提交
1845
            // delete file from meta
1846 1847
            if (!idsToDelete.empty()) {
                std::stringstream idsToDeleteSS;
S
starlord 已提交
1848
                for (auto& id : idsToDelete) {
1849
                    idsToDeleteSS << "id = " << id << " OR ";
1850
                }
1851

1852
                std::string idsToDeleteStr = idsToDeleteSS.str();
S
starlord 已提交
1853
                idsToDeleteStr = idsToDeleteStr.substr(0, idsToDeleteStr.size() - 4);  // remove the last " OR "
1854
                query << "DELETE FROM " << META_TABLEFILES << " WHERE " << idsToDeleteStr << ";";
1855

1856
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::CleanUpFilesWithTTL: " << query.str();
1857

1858 1859
                if (!query.exec()) {
                    return HandleException("QUERY ERROR WHEN CLEANING UP FILES WITH TTL", query.error());
1860 1861
                }
            }
1862

G
groot 已提交
1863
            if (clean_files > 0) {
G
groot 已提交
1864
                ENGINE_LOG_DEBUG << "Clean " << clean_files << " files expired in " << seconds << " seconds";
1865
            }
S
starlord 已提交
1866 1867
        }  // Scoped Connection
    } catch (std::exception& e) {
S
starlord 已提交
1868
        return HandleException("GENERAL ERROR WHEN CLEANING UP FILES WITH TTL", e.what());
Z
update  
zhiru 已提交
1869
    }
1870

S
starlord 已提交
1871
    // remove to_delete tables
1872
    try {
Y
Yu Kun 已提交
1873
        server::MetricCollector metric;
1874 1875

        {
S
starlord 已提交
1876
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
Z
zhiru 已提交
1877

Z
update  
zhiru 已提交
1878
            if (connectionPtr == nullptr) {
G
groot 已提交
1879
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
Z
update  
zhiru 已提交
1880 1881
            }

1882 1883 1884
            mysqlpp::Query query = connectionPtr->query();
            query << "SELECT id, table_id"
                  << " FROM " << META_TABLES << " WHERE state = " << std::to_string(TableSchema::TO_DELETE) << ";";
1885

1886
            ENGINE_LOG_DEBUG << "MySQLMetaImpl::CleanUpFilesWithTTL: " << query.str();
1887

1888
            mysqlpp::StoreQueryResult res = query.store();
Z
update  
zhiru 已提交
1889

1890
            int64_t remove_tables = 0;
Z
update  
zhiru 已提交
1891
            if (!res.empty()) {
1892
                std::stringstream idsToDeleteSS;
S
starlord 已提交
1893
                for (auto& resRow : res) {
1894 1895 1896
                    size_t id = resRow["id"];
                    std::string table_id;
                    resRow["table_id"].to_string(table_id);
Z
update  
zhiru 已提交
1897

S
starlord 已提交
1898
                    utils::DeleteTablePath(options_, table_id, false);  // only delete empty folder
1899
                    remove_tables++;
1900
                    idsToDeleteSS << "id = " << std::to_string(id) << " OR ";
Z
update  
zhiru 已提交
1901
                }
1902
                std::string idsToDeleteStr = idsToDeleteSS.str();
S
starlord 已提交
1903
                idsToDeleteStr = idsToDeleteStr.substr(0, idsToDeleteStr.size() - 4);  // remove the last " OR "
1904
                query << "DELETE FROM " << META_TABLES << " WHERE " << idsToDeleteStr << ";";
1905

1906
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::CleanUpFilesWithTTL: " << query.str();
Z
update  
zhiru 已提交
1907

1908 1909
                if (!query.exec()) {
                    return HandleException("QUERY ERROR WHEN CLEANING UP TABLES WITH TTL", query.error());
1910 1911
                }
            }
1912

1913 1914
            if (remove_tables > 0) {
                ENGINE_LOG_DEBUG << "Remove " << remove_tables << " tables from meta";
1915
            }
S
starlord 已提交
1916 1917
        }  // Scoped Connection
    } catch (std::exception& e) {
S
starlord 已提交
1918
        return HandleException("GENERAL ERROR WHEN CLEANING UP TABLES WITH TTL", e.what());
Z
update  
zhiru 已提交
1919 1920
    }

S
starlord 已提交
1921 1922
    // remove deleted table folder
    // don't remove table folder until all its files has been deleted
S
starlord 已提交
1923
    try {
Y
Yu Kun 已提交
1924
        server::MetricCollector metric;
S
starlord 已提交
1925 1926

        {
S
starlord 已提交
1927
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
S
starlord 已提交
1928 1929

            if (connectionPtr == nullptr) {
G
groot 已提交
1930
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
S
starlord 已提交
1931 1932
            }

S
starlord 已提交
1933
            for (auto& table_id : table_ids) {
1934 1935 1936
                mysqlpp::Query query = connectionPtr->query();
                query << "SELECT file_id"
                      << " FROM " << META_TABLEFILES << " WHERE table_id = " << mysqlpp::quote << table_id << ";";
S
starlord 已提交
1937

1938
                ENGINE_LOG_DEBUG << "MySQLMetaImpl::CleanUpFilesWithTTL: " << query.str();
S
starlord 已提交
1939

1940
                mysqlpp::StoreQueryResult res = query.store();
S
starlord 已提交
1941 1942 1943 1944 1945

                if (res.empty()) {
                    utils::DeleteTablePath(options_, table_id);
                }
            }
1946

S
starlord 已提交
1947
            if (table_ids.size() > 0) {
1948 1949
                ENGINE_LOG_DEBUG << "Remove " << table_ids.size() << " tables folder";
            }
S
starlord 已提交
1950
        }
S
starlord 已提交
1951
    } catch (std::exception& e) {
S
starlord 已提交
1952
        return HandleException("GENERAL ERROR WHEN CLEANING UP TABLES WITH TTL", e.what());
S
starlord 已提交
1953 1954
    }

1955 1956
    return Status::OK();
}
1957

S
starlord 已提交
1958
Status
S
starlord 已提交
1959
MySQLMetaImpl::Count(const std::string& table_id, uint64_t& result) {
1960
    try {
Y
Yu Kun 已提交
1961
        server::MetricCollector metric;
1962 1963 1964 1965 1966 1967 1968

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

        if (!status.ok()) {
            return status;
1969
        }
Z
zhiru 已提交
1970

S
starlord 已提交
1971
        mysqlpp::StoreQueryResult res;
1972
        {
S
starlord 已提交
1973
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
Z
zhiru 已提交
1974

Z
update  
zhiru 已提交
1975
            if (connectionPtr == nullptr) {
G
groot 已提交
1976
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
Z
update  
zhiru 已提交
1977 1978
            }

S
starlord 已提交
1979
            mysqlpp::Query countQuery = connectionPtr->query();
G
groot 已提交
1980 1981 1982 1983 1984
            countQuery << "SELECT row_count"
                       << " FROM " << META_TABLEFILES << " WHERE table_id = " << mysqlpp::quote << table_id
                       << " AND (file_type = " << std::to_string(TableFileSchema::RAW)
                       << " OR file_type = " << std::to_string(TableFileSchema::TO_INDEX)
                       << " OR file_type = " << std::to_string(TableFileSchema::INDEX) << ");";
Z
update  
zhiru 已提交
1985

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

1988
            res = countQuery.store();
S
starlord 已提交
1989
        }  // Scoped Connection
1990 1991

        result = 0;
S
starlord 已提交
1992
        for (auto& resRow : res) {
S
starlord 已提交
1993
            size_t size = resRow["row_count"];
1994
            result += size;
1995
        }
S
starlord 已提交
1996
    } catch (std::exception& e) {
S
starlord 已提交
1997
        return HandleException("GENERAL ERROR WHEN RETRIEVING COUNT", e.what());
Z
update  
zhiru 已提交
1998
    }
S
starlord 已提交
1999

2000 2001 2002
    return Status::OK();
}

S
starlord 已提交
2003 2004
Status
MySQLMetaImpl::DropAll() {
2005
    try {
S
starlord 已提交
2006
        ENGINE_LOG_DEBUG << "Drop all mysql meta";
S
starlord 已提交
2007
        mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);
2008 2009

        if (connectionPtr == nullptr) {
G
groot 已提交
2010
            return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
Z
zhiru 已提交
2011
        }
2012

S
starlord 已提交
2013
        mysqlpp::Query dropTableQuery = connectionPtr->query();
2014
        dropTableQuery << "DROP TABLE IF EXISTS " << TABLES_SCHEMA.name() << ", " << TABLEFILES_SCHEMA.name() << ";";
2015 2016 2017 2018 2019 2020

        ENGINE_LOG_DEBUG << "MySQLMetaImpl::DropAll: " << dropTableQuery.str();

        if (dropTableQuery.exec()) {
            return Status::OK();
        }
S
starlord 已提交
2021
        return HandleException("QUERY ERROR WHEN DROPPING ALL", dropTableQuery.error());
S
starlord 已提交
2022
    } catch (std::exception& e) {
S
starlord 已提交
2023
        return HandleException("GENERAL ERROR WHEN DROPPING ALL", e.what());
2024 2025 2026
    }
}

G
groot 已提交
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092
Status
MySQLMetaImpl::DiscardFiles(int64_t to_discard_size) {
    if (to_discard_size <= 0) {
        return Status::OK();
    }
    ENGINE_LOG_DEBUG << "About to discard size=" << to_discard_size;

    try {
        server::MetricCollector metric;
        bool status;
        {
            mysqlpp::ScopedConnection connectionPtr(*mysql_connection_pool_, safe_grab_);

            if (connectionPtr == nullptr) {
                return Status(DB_ERROR, "Failed to connect to meta server(mysql)");
            }

            mysqlpp::Query discardFilesQuery = connectionPtr->query();
            discardFilesQuery << "SELECT id, file_size"
                              << " FROM " << META_TABLEFILES << " WHERE file_type <> "
                              << std::to_string(TableFileSchema::TO_DELETE) << " ORDER BY id ASC "
                              << " LIMIT 10;";

            ENGINE_LOG_DEBUG << "MySQLMetaImpl::DiscardFiles: " << discardFilesQuery.str();

            mysqlpp::StoreQueryResult res = discardFilesQuery.store();
            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.file_size_ = resRow["file_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.file_size_;
                to_discard_size -= table_file.file_size_;
            }

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

            discardFilesQuery << "UPDATE " << META_TABLEFILES
                              << " SET file_type = " << std::to_string(TableFileSchema::TO_DELETE)
                              << " ,updated_time = " << std::to_string(utils::GetMicroSecTimeStamp()) << " WHERE "
                              << idsToDiscardStr << ";";

            ENGINE_LOG_DEBUG << "MySQLMetaImpl::DiscardFiles: " << discardFilesQuery.str();

            status = discardFilesQuery.exec();
            if (!status) {
                return HandleException("QUERY ERROR WHEN DISCARDING FILES", discardFilesQuery.error());
            }
        }  // Scoped Connection

        return DiscardFiles(to_discard_size);
    } catch (std::exception& e) {
        return HandleException("GENERAL ERROR WHEN DISCARDING FILES", e.what());
    }
}

S
starlord 已提交
2093 2094 2095
}  // namespace meta
}  // namespace engine
}  // namespace milvus