SqliteMetaImpl.cpp 52.4 KB
Newer Older
X
Xu Peng 已提交
1 2 3 4 5
/*******************************************************************************
 * Copyright 上海赜睿信息科技有限公司(Zilliz) - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited.
 * Proprietary and confidential.
 ******************************************************************************/
S
starlord 已提交
6 7 8 9
#include "SqliteMetaImpl.h"
#include "db/IDGenerator.h"
#include "db/Utils.h"
#include "db/Log.h"
X
Xu Peng 已提交
10
#include "MetaConsts.h"
S
starlord 已提交
11
#include "db/Factories.h"
12
#include "metrics/Metrics.h"
X
Xu Peng 已提交
13

X
Xu Peng 已提交
14
#include <unistd.h>
X
Xu Peng 已提交
15 16
#include <sstream>
#include <iostream>
X
Xu Peng 已提交
17
#include <boost/filesystem.hpp>
18
#include <chrono>
X
Xu Peng 已提交
19
#include <fstream>
20
#include <sqlite_orm.h>
X
Xu Peng 已提交
21

X
Xu Peng 已提交
22 23

namespace zilliz {
J
jinhai 已提交
24
namespace milvus {
X
Xu Peng 已提交
25
namespace engine {
26
namespace meta {
X
Xu Peng 已提交
27

X
Xu Peng 已提交
28 29
using namespace sqlite_orm;

G
groot 已提交
30 31
namespace {

G
groot 已提交
32 33 34
Status HandleException(const std::string& desc, std::exception &e) {
    ENGINE_LOG_ERROR << desc << ": " << e.what();
    return Status::DBTransactionError(desc, e.what());
G
groot 已提交
35 36
}

G
groot 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
class MetricCollector {
public:
    MetricCollector() {
        server::Metrics::GetInstance().MetaAccessTotalIncrement();
        start_time_ = METRICS_NOW_TIME;
    }

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

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

G
groot 已提交
55 56
}

57
inline auto StoragePrototype(const std::string &path) {
X
Xu Peng 已提交
58
    return make_storage(path,
G
groot 已提交
59
                        make_table("Tables",
G
groot 已提交
60 61
                                   make_column("id", &TableSchema::id_, primary_key()),
                                   make_column("table_id", &TableSchema::table_id_, unique()),
G
groot 已提交
62
                                   make_column("state", &TableSchema::state_),
G
groot 已提交
63 64
                                   make_column("dimension", &TableSchema::dimension_),
                                   make_column("created_on", &TableSchema::created_on_),
S
starlord 已提交
65
                                   make_column("flag", &TableSchema::flag_, default_value(0)),
G
groot 已提交
66
                                   make_column("engine_type", &TableSchema::engine_type_),
67 68 69
                                   make_column("nlist", &TableSchema::nlist_),
                                   make_column("index_file_size", &TableSchema::index_file_size_),
                                   make_column("metric_type", &TableSchema::metric_type_)),
G
groot 已提交
70
                        make_table("TableFiles",
G
groot 已提交
71 72
                                   make_column("id", &TableFileSchema::id_, primary_key()),
                                   make_column("table_id", &TableFileSchema::table_id_),
G
groot 已提交
73
                                   make_column("engine_type", &TableFileSchema::engine_type_),
G
groot 已提交
74 75
                                   make_column("file_id", &TableFileSchema::file_id_),
                                   make_column("file_type", &TableFileSchema::file_type_),
76 77
                                   make_column("file_size", &TableFileSchema::file_size_, default_value(0)),
                                   make_column("row_count", &TableFileSchema::row_count_, default_value(0)),
G
groot 已提交
78 79 80
                                   make_column("updated_time", &TableFileSchema::updated_time_),
                                   make_column("created_on", &TableFileSchema::created_on_),
                                   make_column("date", &TableFileSchema::date_))
81
    );
X
Xu Peng 已提交
82 83 84

}

X
Xu Peng 已提交
85
using ConnectorT = decltype(StoragePrototype(""));
X
Xu Peng 已提交
86
static std::unique_ptr<ConnectorT> ConnectorPtr;
G
groot 已提交
87
using ConditionT = decltype(c(&TableFileSchema::id_) == 1UL);
X
Xu Peng 已提交
88

S
starlord 已提交
89
Status SqliteMetaImpl::NextTableId(std::string &table_id) {
90 91
    std::stringstream ss;
    SimpleIDGenerator g;
92
    ss << g.GetNextIDNumber();
93
    table_id = ss.str();
94 95 96
    return Status::OK();
}

S
starlord 已提交
97
Status SqliteMetaImpl::NextFileId(std::string &file_id) {
X
Xu Peng 已提交
98 99
    std::stringstream ss;
    SimpleIDGenerator g;
100
    ss << g.GetNextIDNumber();
X
Xu Peng 已提交
101 102 103 104
    file_id = ss.str();
    return Status::OK();
}

S
starlord 已提交
105
SqliteMetaImpl::SqliteMetaImpl(const DBMetaOptions &options_)
X
Xu Peng 已提交
106 107
    : options_(options_) {
    Initialize();
X
Xu Peng 已提交
108 109
}

S
starlord 已提交
110
Status SqliteMetaImpl::Initialize() {
X
Xu Peng 已提交
111 112
    if (!boost::filesystem::is_directory(options_.path)) {
        auto ret = boost::filesystem::create_directory(options_.path);
113
        if (!ret) {
G
groot 已提交
114
            ENGINE_LOG_ERROR << "Failed to create db directory " << options_.path;
115
            return Status::InvalidDBPath("Failed to create db directory", options_.path);
116
        }
X
Xu Peng 已提交
117
    }
X
Xu Peng 已提交
118

119
    ConnectorPtr = std::make_unique<ConnectorT>(StoragePrototype(options_.path + "/meta.sqlite"));
X
Xu Peng 已提交
120

X
Xu Peng 已提交
121
    ConnectorPtr->sync_schema();
122
    ConnectorPtr->open_forever(); // thread safe option
123
    ConnectorPtr->pragma.journal_mode(journal_mode::WAL); // WAL => write ahead log
X
Xu Peng 已提交
124

125
    CleanUp();
X
Xu Peng 已提交
126

X
Xu Peng 已提交
127
    return Status::OK();
X
Xu Peng 已提交
128 129
}

X
Xu Peng 已提交
130
// PXU TODO: Temp solution. Will fix later
S
starlord 已提交
131
Status SqliteMetaImpl::DropPartitionsByDates(const std::string &table_id,
132
                                         const DatesT &dates) {
X
Xu Peng 已提交
133 134 135 136
    if (dates.size() == 0) {
        return Status::OK();
    }

137
    TableSchema table_schema;
G
groot 已提交
138
    table_schema.table_id_ = table_id;
X
Xu Peng 已提交
139
    auto status = DescribeTable(table_schema);
X
Xu Peng 已提交
140 141 142 143
    if (!status.ok()) {
        return status;
    }

G
groot 已提交
144 145
    try {
        auto yesterday = GetDateWithDelta(-1);
X
Xu Peng 已提交
146

G
groot 已提交
147 148 149 150
        for (auto &date : dates) {
            if (date >= yesterday) {
                return Status::Error("Could not delete partitions with 2 days");
            }
X
Xu Peng 已提交
151 152
        }

153 154 155
        //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
        std::lock_guard<std::mutex> meta_lock(meta_mutex_);

X
Xu Peng 已提交
156
        ConnectorPtr->update_all(
157
            set(
G
groot 已提交
158
                c(&TableFileSchema::file_type_) = (int) TableFileSchema::TO_DELETE
159 160
            ),
            where(
G
groot 已提交
161 162
                c(&TableFileSchema::table_id_) == table_id and
                    in(&TableFileSchema::date_, dates)
163 164
            ));
    } catch (std::exception &e) {
G
groot 已提交
165
        return HandleException("Encounter exception when drop partition", e);
X
Xu Peng 已提交
166
    }
G
groot 已提交
167

X
Xu Peng 已提交
168 169 170
    return Status::OK();
}

S
starlord 已提交
171
Status SqliteMetaImpl::CreateTable(TableSchema &table_schema) {
Z
zhiru 已提交
172

G
groot 已提交
173 174 175
    try {
        MetricCollector metric;

176 177 178
        //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
        std::lock_guard<std::mutex> meta_lock(meta_mutex_);

G
groot 已提交
179 180
        if (table_schema.table_id_ == "") {
            NextTableId(table_schema.table_id_);
G
groot 已提交
181 182 183 184
        } else {
            auto table = ConnectorPtr->select(columns(&TableSchema::state_),
                                               where(c(&TableSchema::table_id_) == table_schema.table_id_));
            if (table.size() == 1) {
G
groot 已提交
185 186 187
                if(TableSchema::TO_DELETE == std::get<0>(table[0])) {
                    return Status::Error("Table already exists and it is in delete state, please wait a second");
                } else {
188 189
                    // Change from no error to already exist.
                    return Status::AlreadyExist("Table already exists");
G
groot 已提交
190
                }
G
groot 已提交
191
            }
G
groot 已提交
192
        }
G
groot 已提交
193

G
groot 已提交
194 195 196
        table_schema.id_ = -1;
        table_schema.created_on_ = utils::GetMicroSecTimeStamp();

X
Xu Peng 已提交
197
        try {
198
            auto id = ConnectorPtr->insert(table_schema);
G
groot 已提交
199
            table_schema.id_ = id;
X
Xu Peng 已提交
200
        } catch (...) {
201
            ENGINE_LOG_ERROR << "sqlite transaction failed";
X
Xu Peng 已提交
202
            return Status::DBTransactionError("Add Table Error");
X
Xu Peng 已提交
203
        }
204

S
starlord 已提交
205
        return utils::CreateTablePath(options_, table_schema.table_id_);
G
groot 已提交
206 207 208

    } catch (std::exception &e) {
        return HandleException("Encounter exception when create table", e);
209 210
    }

X
Xu Peng 已提交
211
    return Status::OK();
X
Xu Peng 已提交
212 213
}

S
starlord 已提交
214
Status SqliteMetaImpl::DeleteTable(const std::string& table_id) {
G
groot 已提交
215
    try {
G
groot 已提交
216 217
        MetricCollector metric;

218 219 220
        //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
        std::lock_guard<std::mutex> meta_lock(meta_mutex_);

G
groot 已提交
221
        //soft delete table
S
starlord 已提交
222 223 224 225 226 227 228 229
        ConnectorPtr->update_all(
                set(
                        c(&TableSchema::state_) = (int) TableSchema::TO_DELETE
                ),
                where(
                        c(&TableSchema::table_id_) == table_id and
                        c(&TableSchema::state_) != (int) TableSchema::TO_DELETE
                ));
G
groot 已提交
230

G
groot 已提交
231
    } catch (std::exception &e) {
G
groot 已提交
232
        return HandleException("Encounter exception when delete table", e);
G
groot 已提交
233 234 235 236 237
    }

    return Status::OK();
}

S
starlord 已提交
238
Status SqliteMetaImpl::DeleteTableFiles(const std::string& table_id) {
G
groot 已提交
239 240 241
    try {
        MetricCollector metric;

242 243 244
        //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
        std::lock_guard<std::mutex> meta_lock(meta_mutex_);

G
groot 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257
        //soft delete table files
        ConnectorPtr->update_all(
                set(
                        c(&TableFileSchema::file_type_) = (int) TableFileSchema::TO_DELETE,
                        c(&TableFileSchema::updated_time_) = utils::GetMicroSecTimeStamp()
                ),
                where(
                        c(&TableFileSchema::table_id_) == table_id and
                        c(&TableFileSchema::file_type_) != (int) TableFileSchema::TO_DELETE
                ));

    } catch (std::exception &e) {
        return HandleException("Encounter exception when delete table files", e);
G
groot 已提交
258 259 260 261 262
    }

    return Status::OK();
}

S
starlord 已提交
263
Status SqliteMetaImpl::DescribeTable(TableSchema &table_schema) {
264
    try {
G
groot 已提交
265 266
        MetricCollector metric;

G
groot 已提交
267
        auto groups = ConnectorPtr->select(columns(&TableSchema::id_,
S
starlord 已提交
268
                                                   &TableSchema::state_,
G
groot 已提交
269
                                                   &TableSchema::dimension_,
S
starlord 已提交
270
                                                   &TableSchema::created_on_,
S
starlord 已提交
271
                                                   &TableSchema::flag_,
S
starlord 已提交
272 273 274 275
                                                   &TableSchema::engine_type_,
                                                   &TableSchema::nlist_,
                                                   &TableSchema::index_file_size_,
                                                   &TableSchema::metric_type_),
G
groot 已提交
276 277 278
                                           where(c(&TableSchema::table_id_) == table_schema.table_id_
                                                 and c(&TableSchema::state_) != (int)TableSchema::TO_DELETE));

279
        if (groups.size() == 1) {
G
groot 已提交
280
            table_schema.id_ = std::get<0>(groups[0]);
S
starlord 已提交
281 282 283
            table_schema.state_ = std::get<1>(groups[0]);
            table_schema.dimension_ = std::get<2>(groups[0]);
            table_schema.created_on_ = std::get<3>(groups[0]);
S
starlord 已提交
284 285 286 287 288
            table_schema.flag_ = std::get<4>(groups[0]);
            table_schema.engine_type_ = std::get<5>(groups[0]);
            table_schema.nlist_ = std::get<6>(groups[0]);
            table_schema.index_file_size_ = std::get<7>(groups[0]);
            table_schema.metric_type_ = std::get<8>(groups[0]);
289
        } else {
G
groot 已提交
290
            return Status::NotFound("Table " + table_schema.table_id_ + " not found");
291
        }
G
groot 已提交
292

293
    } catch (std::exception &e) {
G
groot 已提交
294
        return HandleException("Encounter exception when describe table", e);
X
Xu Peng 已提交
295
    }
X
Xu Peng 已提交
296

X
Xu Peng 已提交
297
    return Status::OK();
X
Xu Peng 已提交
298 299
}

S
starlord 已提交
300
Status SqliteMetaImpl::HasNonIndexFiles(const std::string& table_id, bool& has) {
P
peng.xu 已提交
301 302
    has = false;
    try {
303 304 305 306 307 308 309
        std::vector<int> file_types = {
                (int) TableFileSchema::RAW,
                (int) TableFileSchema::NEW,
                (int) TableFileSchema::NEW_MERGE,
                (int) TableFileSchema::NEW_INDEX,
                (int) TableFileSchema::TO_INDEX,
        };
310 311
        auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                     &TableFileSchema::file_type_),
312
                                             where(in(&TableFileSchema::file_type_, file_types)
P
peng.xu 已提交
313 314 315 316 317
                                                   and c(&TableFileSchema::table_id_) == table_id
                                             ));

        if (selected.size() >= 1) {
            has = true;
318 319

            int raw_count = 0, new_count = 0, new_merge_count = 0, new_index_count = 0, to_index_count = 0;
S
starlord 已提交
320
            std::vector<std::string> file_ids;
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
            for (auto &file : selected) {
                switch (std::get<1>(file)) {
                    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;
                    default:
                        break;
                }
            }

            ENGINE_LOG_DEBUG << "Table " << table_id << " currently has raw files:" << raw_count
                << " new files:" << new_count << " new_merge files:" << new_merge_count
                << " new_index files:" << new_index_count << " to_index files:" << to_index_count;
P
peng.xu 已提交
346 347 348 349 350 351 352 353
        }

    } catch (std::exception &e) {
        return HandleException("Encounter exception when check non index files", e);
    }
    return Status::OK();
}

354 355 356 357 358 359 360 361 362 363
Status SqliteMetaImpl::UpdateTableIndexParam(const std::string &table_id, const TableIndex& index) {
    try {
        MetricCollector metric;

        //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
        std::lock_guard<std::mutex> meta_lock(meta_mutex_);

        auto tables = ConnectorPtr->select(columns(&TableSchema::id_,
                                                   &TableSchema::state_,
                                                   &TableSchema::dimension_,
S
starlord 已提交
364 365
                                                   &TableSchema::created_on_,
                                                   &TableSchema::flag_),
366 367 368 369 370 371 372 373 374 375
                                           where(c(&TableSchema::table_id_) == table_id
                                                 and c(&TableSchema::state_) != (int) TableSchema::TO_DELETE));

        if(tables.size() > 0) {
            meta::TableSchema table_schema;
            table_schema.id_ = std::get<0>(tables[0]);
            table_schema.table_id_ = table_id;
            table_schema.state_ = std::get<1>(tables[0]);
            table_schema.dimension_ = std::get<2>(tables[0]);
            table_schema.created_on_ = std::get<3>(tables[0]);
S
starlord 已提交
376
            table_schema.flag_ = std::get<4>(tables[0]);
377
            table_schema.engine_type_ = index.engine_type_;
S
starlord 已提交
378
            table_schema.nlist_ = index.nlist_;
S
starlord 已提交
379
            table_schema.index_file_size_ = index.index_file_size_*ONE_MB;
S
starlord 已提交
380
            table_schema.metric_type_ = index.metric_type_;
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401

            ConnectorPtr->update(table_schema);
        } else {
            return Status::NotFound("Table " + table_id + " not found");
        }

        //set all backup file to raw
        ConnectorPtr->update_all(
                set(
                        c(&TableFileSchema::file_type_) = (int) TableFileSchema::RAW,
                        c(&TableFileSchema::updated_time_) = utils::GetMicroSecTimeStamp()
                ),
                where(
                        c(&TableFileSchema::table_id_) == table_id and
                        c(&TableFileSchema::file_type_) == (int) TableFileSchema::BACKUP
                ));

    } catch (std::exception &e) {
        std::string msg = "Encounter exception when update table index: table_id = " + table_id;
        return HandleException(msg, e);
    }
S
starlord 已提交
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423

    return Status::OK();
}

Status SqliteMetaImpl::UpdateTableFlag(const std::string &table_id, int64_t flag) {
    try {
        MetricCollector metric;

        //set all backup file to raw
        ConnectorPtr->update_all(
                set(
                        c(&TableSchema::flag_) = flag
                ),
                where(
                        c(&TableSchema::table_id_) == table_id
                ));

    } catch (std::exception &e) {
        std::string msg = "Encounter exception when update table flag: table_id = " + table_id;
        return HandleException(msg, e);
    }

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
    return Status::OK();
}

Status SqliteMetaImpl::DescribeTableIndex(const std::string &table_id, TableIndex& index) {
    try {
        MetricCollector metric;

        auto groups = ConnectorPtr->select(columns(&TableSchema::engine_type_,
                                                   &TableSchema::nlist_,
                                                   &TableSchema::index_file_size_,
                                                   &TableSchema::metric_type_),
                                           where(c(&TableSchema::table_id_) == table_id
                                                 and c(&TableSchema::state_) != (int)TableSchema::TO_DELETE));

        if (groups.size() == 1) {
            index.engine_type_ = std::get<0>(groups[0]);
S
starlord 已提交
440
            index.nlist_ = std::get<1>(groups[0]);
S
starlord 已提交
441
            index.index_file_size_ = std::get<2>(groups[0])/ONE_MB;
S
starlord 已提交
442
            index.metric_type_ = std::get<3>(groups[0]);
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
        } else {
            return Status::NotFound("Table " + table_id + " not found");
        }

    } catch (std::exception &e) {
        return HandleException("Encounter exception when describe index", e);
    }

    return Status::OK();
}

Status SqliteMetaImpl::DropTableIndex(const std::string &table_id) {
    try {
        MetricCollector metric;

        //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
        std::lock_guard<std::mutex> meta_lock(meta_mutex_);

        //soft delete index files
        ConnectorPtr->update_all(
                set(
                        c(&TableFileSchema::file_type_) = (int) TableFileSchema::TO_DELETE,
                        c(&TableFileSchema::updated_time_) = utils::GetMicroSecTimeStamp()
                ),
                where(
                        c(&TableFileSchema::table_id_) == table_id and
                        c(&TableFileSchema::file_type_) == (int) TableFileSchema::INDEX
                ));

        //set all backup file to raw
        ConnectorPtr->update_all(
                set(
                        c(&TableFileSchema::file_type_) = (int) TableFileSchema::RAW,
                        c(&TableFileSchema::updated_time_) = utils::GetMicroSecTimeStamp()
                ),
                where(
                        c(&TableFileSchema::table_id_) == table_id and
                        c(&TableFileSchema::file_type_) == (int) TableFileSchema::BACKUP
                ));

    } catch (std::exception &e) {
        return HandleException("Encounter exception when delete table index files", e);
    }

    return Status::OK();
}

S
starlord 已提交
490
Status SqliteMetaImpl::HasTable(const std::string &table_id, bool &has_or_not) {
G
groot 已提交
491
    has_or_not = false;
492

G
groot 已提交
493 494
    try {
        MetricCollector metric;
G
groot 已提交
495
        auto tables = ConnectorPtr->select(columns(&TableSchema::id_),
G
groot 已提交
496 497
                                           where(c(&TableSchema::table_id_) == table_id
                                           and c(&TableSchema::state_) != (int)TableSchema::TO_DELETE));
498
        if (tables.size() == 1) {
499 500 501 502
            has_or_not = true;
        } else {
            has_or_not = false;
        }
G
groot 已提交
503

504
    } catch (std::exception &e) {
G
groot 已提交
505
        return HandleException("Encounter exception when lookup table", e);
G
groot 已提交
506
    }
G
groot 已提交
507

G
groot 已提交
508 509 510
    return Status::OK();
}

S
starlord 已提交
511
Status SqliteMetaImpl::AllTables(std::vector<TableSchema>& table_schema_array) {
G
groot 已提交
512
    try {
G
groot 已提交
513 514
        MetricCollector metric;

G
groot 已提交
515
        auto selected = ConnectorPtr->select(columns(&TableSchema::id_,
S
starlord 已提交
516 517 518
                                                     &TableSchema::table_id_,
                                                     &TableSchema::dimension_,
                                                     &TableSchema::created_on_,
S
starlord 已提交
519
                                                     &TableSchema::flag_,
S
starlord 已提交
520 521 522 523
                                                     &TableSchema::engine_type_,
                                                     &TableSchema::nlist_,
                                                     &TableSchema::index_file_size_,
                                                     &TableSchema::metric_type_),
G
groot 已提交
524
                                             where(c(&TableSchema::state_) != (int)TableSchema::TO_DELETE));
G
groot 已提交
525 526 527 528
        for (auto &table : selected) {
            TableSchema schema;
            schema.id_ = std::get<0>(table);
            schema.table_id_ = std::get<1>(table);
S
starlord 已提交
529 530 531 532 533 534 535
            schema.dimension_ = std::get<2>(table);
            schema.created_on_ = std::get<3>(table);
            schema.flag_ = std::get<4>(table);
            schema.engine_type_ = std::get<5>(table);
            schema.nlist_ = std::get<6>(table);
            schema.index_file_size_ = std::get<7>(table);
            schema.metric_type_ = std::get<8>(table);
G
groot 已提交
536 537 538

            table_schema_array.emplace_back(schema);
        }
G
groot 已提交
539

G
groot 已提交
540
    } catch (std::exception &e) {
G
groot 已提交
541
        return HandleException("Encounter exception when lookup all tables", e);
X
Xu Peng 已提交
542
    }
G
groot 已提交
543

X
Xu Peng 已提交
544
    return Status::OK();
X
Xu Peng 已提交
545 546
}

S
starlord 已提交
547
Status SqliteMetaImpl::CreateTableFile(TableFileSchema &file_schema) {
G
groot 已提交
548 549
    if (file_schema.date_ == EmptyDate) {
        file_schema.date_ = Meta::GetDate();
X
Xu Peng 已提交
550
    }
551
    TableSchema table_schema;
G
groot 已提交
552
    table_schema.table_id_ = file_schema.table_id_;
X
Xu Peng 已提交
553
    auto status = DescribeTable(table_schema);
X
Xu Peng 已提交
554 555 556
    if (!status.ok()) {
        return status;
    }
557

G
groot 已提交
558 559 560 561 562
    try {
        MetricCollector metric;

        NextFileId(file_schema.file_id_);
        file_schema.dimension_ = table_schema.dimension_;
563 564
        file_schema.file_size_ = 0;
        file_schema.row_count_ = 0;
G
groot 已提交
565 566 567
        file_schema.created_on_ = utils::GetMicroSecTimeStamp();
        file_schema.updated_time_ = file_schema.created_on_;
        file_schema.engine_type_ = table_schema.engine_type_;
S
starlord 已提交
568 569
        file_schema.nlist_ = table_schema.nlist_;
        file_schema.metric_type_ = table_schema.metric_type_;
G
groot 已提交
570

571 572 573
        //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
        std::lock_guard<std::mutex> meta_lock(meta_mutex_);

G
groot 已提交
574 575 576
        auto id = ConnectorPtr->insert(file_schema);
        file_schema.id_ = id;

S
starlord 已提交
577
        return utils::CreateTableFilePath(options_, file_schema);
578

G
groot 已提交
579 580
    } catch (std::exception& ex) {
        return HandleException("Encounter exception when create table file", ex);
581 582
    }

X
Xu Peng 已提交
583
    return Status::OK();
X
Xu Peng 已提交
584 585
}

S
starlord 已提交
586
Status SqliteMetaImpl::FilesToIndex(TableFilesSchema &files) {
X
Xu Peng 已提交
587
    files.clear();
X
Xu Peng 已提交
588

589
    try {
G
groot 已提交
590 591
        MetricCollector metric;

G
groot 已提交
592 593 594 595
        auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                     &TableFileSchema::table_id_,
                                                     &TableFileSchema::file_id_,
                                                     &TableFileSchema::file_type_,
S
starlord 已提交
596
                                                     &TableFileSchema::file_size_,
597
                                                     &TableFileSchema::row_count_,
G
groot 已提交
598
                                                     &TableFileSchema::date_,
S
starlord 已提交
599 600
                                                     &TableFileSchema::engine_type_,
                                                     &TableFileSchema::created_on_),
G
groot 已提交
601
                                             where(c(&TableFileSchema::file_type_)
602
                                                       == (int) TableFileSchema::TO_INDEX));
603

604
        std::map<std::string, TableSchema> groups;
X
Xu Peng 已提交
605
        TableFileSchema table_file;
606

607
        for (auto &file : selected) {
G
groot 已提交
608 609 610 611
            table_file.id_ = std::get<0>(file);
            table_file.table_id_ = std::get<1>(file);
            table_file.file_id_ = std::get<2>(file);
            table_file.file_type_ = std::get<3>(file);
S
starlord 已提交
612 613 614 615 616
            table_file.file_size_ = std::get<4>(file);
            table_file.row_count_ = std::get<5>(file);
            table_file.date_ = std::get<6>(file);
            table_file.engine_type_ = std::get<7>(file);
            table_file.created_on_ = std::get<8>(file);
G
groot 已提交
617

S
starlord 已提交
618
            utils::GetTableFilePath(options_, table_file);
G
groot 已提交
619
            auto groupItr = groups.find(table_file.table_id_);
620
            if (groupItr == groups.end()) {
621
                TableSchema table_schema;
G
groot 已提交
622
                table_schema.table_id_ = table_file.table_id_;
X
Xu Peng 已提交
623
                auto status = DescribeTable(table_schema);
624 625 626
                if (!status.ok()) {
                    return status;
                }
G
groot 已提交
627
                groups[table_file.table_id_] = table_schema;
X
Xu Peng 已提交
628
            }
S
starlord 已提交
629 630
            table_file.metric_type_ = groups[table_file.table_id_].metric_type_;
            table_file.nlist_ = groups[table_file.table_id_].nlist_;
G
groot 已提交
631
            table_file.dimension_ = groups[table_file.table_id_].dimension_;
X
Xu Peng 已提交
632
            files.push_back(table_file);
X
Xu Peng 已提交
633
        }
G
groot 已提交
634

635
    } catch (std::exception &e) {
G
groot 已提交
636
        return HandleException("Encounter exception when iterate raw files", e);
X
Xu Peng 已提交
637
    }
X
Xu Peng 已提交
638

X
Xu Peng 已提交
639 640 641
    return Status::OK();
}

S
starlord 已提交
642
Status SqliteMetaImpl::FilesToSearch(const std::string &table_id,
643 644
                                 const DatesT &partition,
                                 DatePartionedTableFilesSchema &files) {
X
xj.lin 已提交
645
    files.clear();
X
Xu Peng 已提交
646

647
    try {
G
groot 已提交
648 649
        MetricCollector metric;

X
Xu Peng 已提交
650
        if (partition.empty()) {
651
            std::vector<int> file_type = {(int) TableFileSchema::RAW, (int) TableFileSchema::TO_INDEX, (int) TableFileSchema::INDEX};
G
groot 已提交
652 653 654 655
            auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                         &TableFileSchema::table_id_,
                                                         &TableFileSchema::file_id_,
                                                         &TableFileSchema::file_type_,
S
starlord 已提交
656
                                                         &TableFileSchema::file_size_,
657
                                                         &TableFileSchema::row_count_,
G
groot 已提交
658 659 660
                                                         &TableFileSchema::date_,
                                                         &TableFileSchema::engine_type_),
                                                 where(c(&TableFileSchema::table_id_) == table_id and
661
                                                       in(&TableFileSchema::file_type_, file_type)));
G
groot 已提交
662

X
Xu Peng 已提交
663
            TableSchema table_schema;
G
groot 已提交
664
            table_schema.table_id_ = table_id;
X
Xu Peng 已提交
665 666 667 668
            auto status = DescribeTable(table_schema);
            if (!status.ok()) {
                return status;
            }
X
xj.lin 已提交
669

X
Xu Peng 已提交
670 671 672
            TableFileSchema table_file;

            for (auto &file : selected) {
G
groot 已提交
673 674 675 676
                table_file.id_ = std::get<0>(file);
                table_file.table_id_ = std::get<1>(file);
                table_file.file_id_ = std::get<2>(file);
                table_file.file_type_ = std::get<3>(file);
S
starlord 已提交
677 678 679 680
                table_file.file_size_ = std::get<4>(file);
                table_file.row_count_ = std::get<5>(file);
                table_file.date_ = std::get<6>(file);
                table_file.engine_type_ = std::get<7>(file);
S
starlord 已提交
681 682
                table_file.metric_type_ = table_schema.metric_type_;
                table_file.nlist_ = table_schema.nlist_;
G
groot 已提交
683
                table_file.dimension_ = table_schema.dimension_;
S
starlord 已提交
684
                utils::GetTableFilePath(options_, table_file);
G
groot 已提交
685
                auto dateItr = files.find(table_file.date_);
X
Xu Peng 已提交
686
                if (dateItr == files.end()) {
G
groot 已提交
687
                    files[table_file.date_] = TableFilesSchema();
X
Xu Peng 已提交
688
                }
G
groot 已提交
689
                files[table_file.date_].push_back(table_file);
X
Xu Peng 已提交
690 691 692
            }
        }
        else {
693
            std::vector<int> file_type = {(int) TableFileSchema::RAW, (int) TableFileSchema::TO_INDEX, (int) TableFileSchema::INDEX};
G
groot 已提交
694 695 696 697
            auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                         &TableFileSchema::table_id_,
                                                         &TableFileSchema::file_id_,
                                                         &TableFileSchema::file_type_,
S
starlord 已提交
698
                                                         &TableFileSchema::file_size_,
699
                                                         &TableFileSchema::row_count_,
G
groot 已提交
700 701
                                                         &TableFileSchema::date_,
                                                         &TableFileSchema::engine_type_),
G
groot 已提交
702
                                                 where(c(&TableFileSchema::table_id_) == table_id and
703 704
                                                       in(&TableFileSchema::date_, partition) and
                                                       in(&TableFileSchema::file_type_, file_type)));
G
groot 已提交
705

X
Xu Peng 已提交
706
            TableSchema table_schema;
G
groot 已提交
707
            table_schema.table_id_ = table_id;
X
Xu Peng 已提交
708 709 710 711
            auto status = DescribeTable(table_schema);
            if (!status.ok()) {
                return status;
            }
X
Xu Peng 已提交
712

X
Xu Peng 已提交
713 714 715
            TableFileSchema table_file;

            for (auto &file : selected) {
G
groot 已提交
716 717 718 719
                table_file.id_ = std::get<0>(file);
                table_file.table_id_ = std::get<1>(file);
                table_file.file_id_ = std::get<2>(file);
                table_file.file_type_ = std::get<3>(file);
S
starlord 已提交
720 721 722 723
                table_file.file_size_ = std::get<4>(file);
                table_file.row_count_ = std::get<5>(file);
                table_file.date_ = std::get<6>(file);
                table_file.engine_type_ = std::get<7>(file);
S
starlord 已提交
724 725
                table_file.metric_type_ = table_schema.metric_type_;
                table_file.nlist_ = table_schema.nlist_;
G
groot 已提交
726
                table_file.dimension_ = table_schema.dimension_;
S
starlord 已提交
727
                utils::GetTableFilePath(options_, table_file);
G
groot 已提交
728
                auto dateItr = files.find(table_file.date_);
X
Xu Peng 已提交
729
                if (dateItr == files.end()) {
G
groot 已提交
730
                    files[table_file.date_] = TableFilesSchema();
X
Xu Peng 已提交
731
                }
G
groot 已提交
732
                files[table_file.date_].push_back(table_file);
733
            }
X
Xu Peng 已提交
734

X
xj.lin 已提交
735
        }
736
    } catch (std::exception &e) {
G
groot 已提交
737
        return HandleException("Encounter exception when iterate index files", e);
X
xj.lin 已提交
738 739 740 741 742
    }

    return Status::OK();
}

S
starlord 已提交
743
Status SqliteMetaImpl::FilesToSearch(const std::string &table_id,
X
xj.lin 已提交
744 745 746 747 748 749 750 751 752 753 754
                                 const std::vector<size_t> &ids,
                                 const DatesT &partition,
                                 DatePartionedTableFilesSchema &files) {
    files.clear();
    MetricCollector metric;

    try {
        auto select_columns = columns(&TableFileSchema::id_,
                                      &TableFileSchema::table_id_,
                                      &TableFileSchema::file_id_,
                                      &TableFileSchema::file_type_,
S
starlord 已提交
755
                                      &TableFileSchema::file_size_,
756
                                      &TableFileSchema::row_count_,
X
xj.lin 已提交
757 758 759 760
                                      &TableFileSchema::date_,
                                      &TableFileSchema::engine_type_);

        auto match_tableid = c(&TableFileSchema::table_id_) == table_id;
X
xj.lin 已提交
761 762 763

        std::vector<int> file_type = {(int) TableFileSchema::RAW, (int) TableFileSchema::TO_INDEX, (int) TableFileSchema::INDEX};
        auto match_type = in(&TableFileSchema::file_type_, file_type);
X
xj.lin 已提交
764 765 766 767 768 769 770 771

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

        decltype(ConnectorPtr->select(select_columns)) result;
        if (partition.empty() && ids.empty()) {
X
xj.lin 已提交
772
            auto filter = where(match_tableid and match_type);
X
xj.lin 已提交
773 774 775 776
            result = ConnectorPtr->select(select_columns, filter);
        }
        else if (partition.empty() && !ids.empty()) {
            auto match_fileid = in(&TableFileSchema::id_, ids);
X
xj.lin 已提交
777
            auto filter = where(match_tableid and match_fileid and match_type);
X
xj.lin 已提交
778 779 780 781
            result = ConnectorPtr->select(select_columns, filter);
        }
        else if (!partition.empty() && ids.empty()) {
            auto match_date = in(&TableFileSchema::date_, partition);
X
xj.lin 已提交
782
            auto filter = where(match_tableid and match_date and match_type);
X
xj.lin 已提交
783 784 785 786 787
            result = ConnectorPtr->select(select_columns, filter);
        }
        else if (!partition.empty() && !ids.empty()) {
            auto match_fileid = in(&TableFileSchema::id_, ids);
            auto match_date = in(&TableFileSchema::date_, partition);
X
xj.lin 已提交
788
            auto filter = where(match_tableid and match_fileid and match_date and match_type);
X
xj.lin 已提交
789 790 791 792 793 794 795 796 797
            result = ConnectorPtr->select(select_columns, filter);
        }

        TableFileSchema table_file;
        for (auto &file : result) {
            table_file.id_ = std::get<0>(file);
            table_file.table_id_ = std::get<1>(file);
            table_file.file_id_ = std::get<2>(file);
            table_file.file_type_ = std::get<3>(file);
S
starlord 已提交
798 799 800 801
            table_file.file_size_ = std::get<4>(file);
            table_file.row_count_ = std::get<5>(file);
            table_file.date_ = std::get<6>(file);
            table_file.engine_type_ = std::get<7>(file);
X
xj.lin 已提交
802
            table_file.dimension_ = table_schema.dimension_;
S
starlord 已提交
803 804
            table_file.metric_type_ = table_schema.metric_type_;
            table_file.nlist_ = table_schema.nlist_;
X
xj.lin 已提交
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
            utils::GetTableFilePath(options_, table_file);
            auto dateItr = files.find(table_file.date_);
            if (dateItr == files.end()) {
                files[table_file.date_] = TableFilesSchema();
            }
            files[table_file.date_].push_back(table_file);
        }

    } catch (std::exception &e) {
        return HandleException("Encounter exception when iterate index files", e);
    }

    return Status::OK();
}

S
starlord 已提交
820
Status SqliteMetaImpl::FilesToMerge(const std::string &table_id,
821
                                DatePartionedTableFilesSchema &files) {
X
Xu Peng 已提交
822
    files.clear();
X
Xu Peng 已提交
823

824
    try {
G
groot 已提交
825 826
        MetricCollector metric;

S
starlord 已提交
827 828 829 830 831 832 833 834 835
        //check table existence
        TableSchema table_schema;
        table_schema.table_id_ = table_id;
        auto status = DescribeTable(table_schema);
        if (!status.ok()) {
            return status;
        }

        //get files to merge
G
groot 已提交
836 837 838 839
        auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                     &TableFileSchema::table_id_,
                                                     &TableFileSchema::file_id_,
                                                     &TableFileSchema::file_type_,
840
                                                     &TableFileSchema::file_size_,
S
starlord 已提交
841 842 843
                                                     &TableFileSchema::row_count_,
                                                     &TableFileSchema::date_,
                                                     &TableFileSchema::created_on_),
G
groot 已提交
844
                                             where(c(&TableFileSchema::file_type_) == (int) TableFileSchema::RAW and
G
groot 已提交
845
                                                 c(&TableFileSchema::table_id_) == table_id),
846
                                             order_by(&TableFileSchema::file_size_).desc());
G
groot 已提交
847

848
        for (auto &file : selected) {
S
starlord 已提交
849 850 851 852 853 854
            TableFileSchema table_file;
            table_file.file_size_ = std::get<4>(file);
            if(table_file.file_size_ >= table_schema.index_file_size_) {
                continue;//skip large file
            }

G
groot 已提交
855 856 857 858
            table_file.id_ = std::get<0>(file);
            table_file.table_id_ = std::get<1>(file);
            table_file.file_id_ = std::get<2>(file);
            table_file.file_type_ = std::get<3>(file);
S
starlord 已提交
859 860 861
            table_file.row_count_ = std::get<5>(file);
            table_file.date_ = std::get<6>(file);
            table_file.created_on_ = std::get<7>(file);
G
groot 已提交
862
            table_file.dimension_ = table_schema.dimension_;
S
starlord 已提交
863 864
            table_file.metric_type_ = table_schema.metric_type_;
            table_file.nlist_ = table_schema.nlist_;
S
starlord 已提交
865
            utils::GetTableFilePath(options_, table_file);
G
groot 已提交
866
            auto dateItr = files.find(table_file.date_);
867
            if (dateItr == files.end()) {
G
groot 已提交
868
                files[table_file.date_] = TableFilesSchema();
869
            }
G
groot 已提交
870
            files[table_file.date_].push_back(table_file);
X
Xu Peng 已提交
871
        }
872
    } catch (std::exception &e) {
G
groot 已提交
873
        return HandleException("Encounter exception when iterate merge files", e);
X
Xu Peng 已提交
874 875 876
    }

    return Status::OK();
X
Xu Peng 已提交
877 878
}

S
starlord 已提交
879
Status SqliteMetaImpl::GetTableFiles(const std::string& table_id,
880 881
                                 const std::vector<size_t>& ids,
                                 TableFilesSchema& table_files) {
X
Xu Peng 已提交
882
    try {
883
        table_files.clear();
Y
yu yunfeng 已提交
884 885
        auto files = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                  &TableFileSchema::file_id_,
G
groot 已提交
886
                                                  &TableFileSchema::file_type_,
887 888
                                                  &TableFileSchema::file_size_,
                                                  &TableFileSchema::row_count_,
889
                                                  &TableFileSchema::date_,
S
starlord 已提交
890 891
                                                  &TableFileSchema::engine_type_,
                                                  &TableFileSchema::created_on_),
892 893
                                          where(c(&TableFileSchema::table_id_) == table_id and
                                                  in(&TableFileSchema::id_, ids)
X
Xu Peng 已提交
894
                                          ));
895 896 897 898 899 900 901 902 903 904

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

        for (auto &file : files) {
            TableFileSchema file_schema;
G
groot 已提交
905
            file_schema.table_id_ = table_id;
Y
yu yunfeng 已提交
906 907 908
            file_schema.id_ = std::get<0>(file);
            file_schema.file_id_ = std::get<1>(file);
            file_schema.file_type_ = std::get<2>(file);
909 910 911 912
            file_schema.file_size_ = std::get<3>(file);
            file_schema.row_count_ = std::get<4>(file);
            file_schema.date_ = std::get<5>(file);
            file_schema.engine_type_ = std::get<6>(file);
S
starlord 已提交
913 914
            file_schema.metric_type_ = table_schema.metric_type_;
            file_schema.nlist_ = table_schema.nlist_;
S
starlord 已提交
915
            file_schema.created_on_ = std::get<7>(file);
916
            file_schema.dimension_ = table_schema.dimension_;
S
starlord 已提交
917

S
starlord 已提交
918
            utils::GetTableFilePath(options_, file_schema);
919 920

            table_files.emplace_back(file_schema);
X
Xu Peng 已提交
921 922
        }
    } catch (std::exception &e) {
923
        return HandleException("Encounter exception when lookup table files", e);
X
Xu Peng 已提交
924 925
    }

X
Xu Peng 已提交
926
    return Status::OK();
X
Xu Peng 已提交
927 928
}

X
Xu Peng 已提交
929
// PXU TODO: Support Swap
S
starlord 已提交
930
Status SqliteMetaImpl::Archive() {
931
    auto &criterias = options_.archive_conf.GetCriterias();
X
Xu Peng 已提交
932 933 934 935 936
    if (criterias.size() == 0) {
        return Status::OK();
    }

    for (auto kv : criterias) {
937 938
        auto &criteria = kv.first;
        auto &limit = kv.second;
G
groot 已提交
939
        if (criteria == engine::ARCHIVE_CONF_DAYS) {
X
Xu Peng 已提交
940
            long usecs = limit * D_SEC * US_PS;
941
            long now = utils::GetMicroSecTimeStamp();
942
            try {
943 944 945
                //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
                std::lock_guard<std::mutex> meta_lock(meta_mutex_);

X
Xu Peng 已提交
946
                ConnectorPtr->update_all(
947
                    set(
G
groot 已提交
948
                        c(&TableFileSchema::file_type_) = (int) TableFileSchema::TO_DELETE
949 950
                    ),
                    where(
G
groot 已提交
951 952
                        c(&TableFileSchema::created_on_) < (long) (now - usecs) and
                            c(&TableFileSchema::file_type_) != (int) TableFileSchema::TO_DELETE
953 954
                    ));
            } catch (std::exception &e) {
G
groot 已提交
955
                return HandleException("Encounter exception when update table files", e);
X
Xu Peng 已提交
956 957
            }
        }
G
groot 已提交
958
        if (criteria == engine::ARCHIVE_CONF_DISK) {
G
groot 已提交
959
            uint64_t sum = 0;
X
Xu Peng 已提交
960
            Size(sum);
X
Xu Peng 已提交
961

G
groot 已提交
962
            int64_t to_delete = (int64_t)sum - limit * G;
X
Xu Peng 已提交
963
            DiscardFiles(to_delete);
X
Xu Peng 已提交
964 965 966 967 968 969
        }
    }

    return Status::OK();
}

S
starlord 已提交
970
Status SqliteMetaImpl::Size(uint64_t &result) {
X
Xu Peng 已提交
971
    result = 0;
X
Xu Peng 已提交
972
    try {
973
        auto selected = ConnectorPtr->select(columns(sum(&TableFileSchema::file_size_)),
S
starlord 已提交
974 975 976
                                          where(
                                                  c(&TableFileSchema::file_type_) != (int) TableFileSchema::TO_DELETE
                                          ));
977 978 979
        for (auto &total_size : selected) {
            if (!std::get<0>(total_size)) {
                continue;
X
Xu Peng 已提交
980
            }
981
            result += (uint64_t) (*std::get<0>(total_size));
X
Xu Peng 已提交
982
        }
983

984
    } catch (std::exception &e) {
G
groot 已提交
985
        return HandleException("Encounter exception when calculte db size", e);
X
Xu Peng 已提交
986 987 988 989 990
    }

    return Status::OK();
}

S
starlord 已提交
991
Status SqliteMetaImpl::DiscardFiles(long to_discard_size) {
X
Xu Peng 已提交
992 993 994
    if (to_discard_size <= 0) {
        return Status::OK();
    }
G
groot 已提交
995

G
groot 已提交
996
    ENGINE_LOG_DEBUG << "About to discard size=" << to_discard_size;
G
groot 已提交
997

X
Xu Peng 已提交
998
    try {
G
groot 已提交
999 1000
        MetricCollector metric;

1001 1002 1003
        //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
        std::lock_guard<std::mutex> meta_lock(meta_mutex_);

G
groot 已提交
1004 1005
        auto commited = ConnectorPtr->transaction([&]() mutable {
            auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
1006
                                                         &TableFileSchema::file_size_),
G
groot 已提交
1007
                                                 where(c(&TableFileSchema::file_type_)
1008
                                                       != (int) TableFileSchema::TO_DELETE),
G
groot 已提交
1009 1010
                                                 order_by(&TableFileSchema::id_),
                                                 limit(10));
X
Xu Peng 已提交
1011

G
groot 已提交
1012 1013
            std::vector<int> ids;
            TableFileSchema table_file;
1014

G
groot 已提交
1015 1016 1017
            for (auto &file : selected) {
                if (to_discard_size <= 0) break;
                table_file.id_ = std::get<0>(file);
1018
                table_file.file_size_ = std::get<1>(file);
G
groot 已提交
1019 1020
                ids.push_back(table_file.id_);
                ENGINE_LOG_DEBUG << "Discard table_file.id=" << table_file.file_id_
1021 1022
                                 << " table_file.size=" << table_file.file_size_;
                to_discard_size -= table_file.file_size_;
G
groot 已提交
1023
            }
1024

G
groot 已提交
1025 1026 1027
            if (ids.size() == 0) {
                return true;
            }
1028

G
groot 已提交
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
            ConnectorPtr->update_all(
                    set(
                            c(&TableFileSchema::file_type_) = (int) TableFileSchema::TO_DELETE,
                            c(&TableFileSchema::updated_time_) = utils::GetMicroSecTimeStamp()
                    ),
                    where(
                            in(&TableFileSchema::id_, ids)
                    ));

            return true;
        });

        if (!commited) {
1042
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
1043 1044
            return Status::DBTransactionError("Update table file error");
        }
X
Xu Peng 已提交
1045

1046
    } catch (std::exception &e) {
G
groot 已提交
1047
        return HandleException("Encounter exception when discard table file", e);
X
Xu Peng 已提交
1048 1049
    }

X
Xu Peng 已提交
1050
    return DiscardFiles(to_discard_size);
X
Xu Peng 已提交
1051 1052
}

S
starlord 已提交
1053
Status SqliteMetaImpl::UpdateTableFile(TableFileSchema &file_schema) {
G
groot 已提交
1054
    file_schema.updated_time_ = utils::GetMicroSecTimeStamp();
1055
    try {
G
groot 已提交
1056 1057
        MetricCollector metric;

1058 1059 1060
        //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
        std::lock_guard<std::mutex> meta_lock(meta_mutex_);

G
groot 已提交
1061 1062 1063 1064 1065 1066 1067 1068 1069
        auto tables = ConnectorPtr->select(columns(&TableSchema::state_),
                                           where(c(&TableSchema::table_id_) == file_schema.table_id_));

        //if the table has been deleted, just mark the table file as TO_DELETE
        //clean thread will delete the file later
        if(tables.size() < 1 || std::get<0>(tables[0]) == (int)TableSchema::TO_DELETE) {
            file_schema.file_type_ = TableFileSchema::TO_DELETE;
        }

X
Xu Peng 已提交
1070
        ConnectorPtr->update(file_schema);
G
groot 已提交
1071

1072
    } catch (std::exception &e) {
G
groot 已提交
1073 1074 1075
        std::string msg = "Exception update table file: table_id = " + file_schema.table_id_
            + " file_id = " + file_schema.file_id_;
        return HandleException(msg, e);
X
Xu Peng 已提交
1076
    }
X
Xu Peng 已提交
1077
    return Status::OK();
X
Xu Peng 已提交
1078 1079
}

S
starlord 已提交
1080
Status SqliteMetaImpl::UpdateTableFilesToIndex(const std::string& table_id) {
P
peng.xu 已提交
1081
    try {
1082 1083 1084 1085 1086
        MetricCollector metric;

        //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
        std::lock_guard<std::mutex> meta_lock(meta_mutex_);

P
peng.xu 已提交
1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
        ConnectorPtr->update_all(
            set(
                c(&TableFileSchema::file_type_) = (int) TableFileSchema::TO_INDEX
            ),
            where(
                c(&TableFileSchema::table_id_) == table_id and
                c(&TableFileSchema::file_type_) == (int) TableFileSchema::RAW
            ));
    } catch (std::exception &e) {
        return HandleException("Encounter exception when update table files to to_index", e);
    }

    return Status::OK();
}

S
starlord 已提交
1102
Status SqliteMetaImpl::UpdateTableFiles(TableFilesSchema &files) {
1103
    try {
G
groot 已提交
1104 1105
        MetricCollector metric;

1106 1107 1108
        //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
        std::lock_guard<std::mutex> meta_lock(meta_mutex_);

G
groot 已提交
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123
        std::map<std::string, bool> has_tables;
        for (auto &file : files) {
            if(has_tables.find(file.table_id_) != has_tables.end()) {
                continue;
            }
            auto tables = ConnectorPtr->select(columns(&TableSchema::id_),
                                               where(c(&TableSchema::table_id_) == file.table_id_
                                                     and c(&TableSchema::state_) != (int) TableSchema::TO_DELETE));
            if(tables.size() >= 1) {
                has_tables[file.table_id_] = true;
            } else {
                has_tables[file.table_id_] = false;
            }
        }

1124 1125
        auto commited = ConnectorPtr->transaction([&]() mutable {
            for (auto &file : files) {
G
groot 已提交
1126 1127 1128 1129
                if(!has_tables[file.table_id_]) {
                    file.file_type_ = TableFileSchema::TO_DELETE;
                }

G
groot 已提交
1130
                file.updated_time_ = utils::GetMicroSecTimeStamp();
1131 1132 1133 1134
                ConnectorPtr->update(file);
            }
            return true;
        });
G
groot 已提交
1135

1136
        if (!commited) {
1137
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
1138
            return Status::DBTransactionError("Update table files error");
X
Xu Peng 已提交
1139
        }
G
groot 已提交
1140

1141
    } catch (std::exception &e) {
G
groot 已提交
1142
        return HandleException("Encounter exception when update table files", e);
X
Xu Peng 已提交
1143
    }
1144 1145 1146
    return Status::OK();
}

S
starlord 已提交
1147
Status SqliteMetaImpl::CleanUpFilesWithTTL(uint16_t seconds) {
X
Xu Peng 已提交
1148
    auto now = utils::GetMicroSecTimeStamp();
S
starlord 已提交
1149 1150 1151
    std::set<std::string> table_ids;

    //remove to_delete files
1152
    try {
G
groot 已提交
1153
        MetricCollector metric;
1154

1155 1156 1157
        //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
        std::lock_guard<std::mutex> meta_lock(meta_mutex_);

G
groot 已提交
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
        auto files = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                  &TableFileSchema::table_id_,
                                                  &TableFileSchema::file_id_,
                                                  &TableFileSchema::date_),
                                          where(
                                                  c(&TableFileSchema::file_type_) ==
                                                  (int) TableFileSchema::TO_DELETE
                                                  and
                                                  c(&TableFileSchema::updated_time_)
                                                  < now - seconds * US_PS));
1168

G
groot 已提交
1169 1170 1171 1172 1173 1174 1175 1176
        auto commited = ConnectorPtr->transaction([&]() mutable {
            TableFileSchema table_file;
            for (auto &file : files) {
                table_file.id_ = std::get<0>(file);
                table_file.table_id_ = std::get<1>(file);
                table_file.file_id_ = std::get<2>(file);
                table_file.date_ = std::get<3>(file);

S
starlord 已提交
1177
                utils::DeleteTableFilePath(options_, table_file);
1178
                ENGINE_LOG_DEBUG << "Removing file id:" << table_file.file_id_ << " location:" << table_file.location_;
G
groot 已提交
1179 1180
                ConnectorPtr->remove<TableFileSchema>(table_file.id_);

S
starlord 已提交
1181
                table_ids.insert(table_file.table_id_);
1182
            }
G
groot 已提交
1183 1184 1185 1186
            return true;
        });

        if (!commited) {
1187
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
1188 1189 1190 1191 1192 1193 1194
            return Status::DBTransactionError("Clean files error");
        }

    } catch (std::exception &e) {
        return HandleException("Encounter exception when clean table files", e);
    }

S
starlord 已提交
1195
    //remove to_delete tables
G
groot 已提交
1196 1197 1198
    try {
        MetricCollector metric;

1199 1200 1201
        //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
        std::lock_guard<std::mutex> meta_lock(meta_mutex_);

G
groot 已提交
1202 1203 1204 1205 1206 1207
        auto tables = ConnectorPtr->select(columns(&TableSchema::id_,
                                                   &TableSchema::table_id_),
                                           where(c(&TableSchema::state_) == (int) TableSchema::TO_DELETE));

        auto commited = ConnectorPtr->transaction([&]() mutable {
            for (auto &table : tables) {
S
starlord 已提交
1208
                utils::DeleteTablePath(options_, std::get<1>(table), false);//only delete empty folder
G
groot 已提交
1209
                ConnectorPtr->remove<TableSchema>(std::get<0>(table));
1210
            }
G
groot 已提交
1211 1212 1213 1214 1215

            return true;
        });

        if (!commited) {
1216
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
1217
            return Status::DBTransactionError("Clean files error");
X
Xu Peng 已提交
1218
        }
G
groot 已提交
1219

1220
    } catch (std::exception &e) {
G
groot 已提交
1221
        return HandleException("Encounter exception when clean table files", e);
X
Xu Peng 已提交
1222 1223
    }

S
starlord 已提交
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
    //remove deleted table folder
    //don't remove table folder until all its files has been deleted
    try {
        MetricCollector metric;

        for(auto& table_id : table_ids) {
            auto selected = ConnectorPtr->select(columns(&TableFileSchema::file_id_),
                                                 where(c(&TableFileSchema::table_id_) == table_id));
            if(selected.size() == 0) {
                utils::DeleteTablePath(options_, table_id);
            }
        }

    } catch (std::exception &e) {
        return HandleException("Encounter exception when delete table folder", e);
    }

X
Xu Peng 已提交
1241 1242 1243
    return Status::OK();
}

S
starlord 已提交
1244
Status SqliteMetaImpl::CleanUp() {
1245
    try {
1246 1247 1248 1249 1250
        MetricCollector metric;

        //multi-threads call sqlite update may get exception('bad logic', etc), so we add a lock here
        std::lock_guard<std::mutex> meta_lock(meta_mutex_);

1251 1252
        std::vector<int> file_type = {(int) TableFileSchema::NEW, (int) TableFileSchema::NEW_INDEX, (int) TableFileSchema::NEW_MERGE};
        auto files = ConnectorPtr->select(columns(&TableFileSchema::id_), where(in(&TableFileSchema::file_type_, file_type)));
1253

G
groot 已提交
1254 1255 1256 1257
        auto commited = ConnectorPtr->transaction([&]() mutable {
            for (auto &file : files) {
                ENGINE_LOG_DEBUG << "Remove table file type as NEW";
                ConnectorPtr->remove<TableFileSchema>(std::get<0>(file));
1258
            }
G
groot 已提交
1259 1260 1261 1262
            return true;
        });

        if (!commited) {
1263
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
1264
            return Status::DBTransactionError("Clean files error");
X
Xu Peng 已提交
1265
        }
G
groot 已提交
1266

1267
    } catch (std::exception &e) {
G
groot 已提交
1268
        return HandleException("Encounter exception when clean table file", e);
X
Xu Peng 已提交
1269 1270 1271 1272 1273
    }

    return Status::OK();
}

S
starlord 已提交
1274
Status SqliteMetaImpl::Count(const std::string &table_id, uint64_t &result) {
X
Xu Peng 已提交
1275

1276
    try {
G
groot 已提交
1277
        MetricCollector metric;
1278

1279 1280 1281
        std::vector<int> file_type = {(int) TableFileSchema::RAW, (int) TableFileSchema::TO_INDEX, (int) TableFileSchema::INDEX};
        auto selected = ConnectorPtr->select(columns(&TableFileSchema::row_count_),
                                             where(in(&TableFileSchema::file_type_, file_type)
G
groot 已提交
1282
                                                   and c(&TableFileSchema::table_id_) == table_id));
1283

1284
        TableSchema table_schema;
G
groot 已提交
1285
        table_schema.table_id_ = table_id;
X
Xu Peng 已提交
1286
        auto status = DescribeTable(table_schema);
1287

1288 1289 1290 1291 1292
        if (!status.ok()) {
            return status;
        }

        result = 0;
1293
        for (auto &file : selected) {
1294 1295
            result += std::get<0>(file);
        }
X
Xu Peng 已提交
1296

1297
    } catch (std::exception &e) {
G
groot 已提交
1298
        return HandleException("Encounter exception when calculate table file size", e);
X
Xu Peng 已提交
1299 1300 1301 1302
    }
    return Status::OK();
}

S
starlord 已提交
1303
Status SqliteMetaImpl::DropAll() {
X
Xu Peng 已提交
1304 1305
    if (boost::filesystem::is_directory(options_.path)) {
        boost::filesystem::remove_all(options_.path);
X
Xu Peng 已提交
1306 1307 1308 1309
    }
    return Status::OK();
}

S
starlord 已提交
1310
SqliteMetaImpl::~SqliteMetaImpl() {
1311
    CleanUp();
X
Xu Peng 已提交
1312 1313
}

1314
} // namespace meta
X
Xu Peng 已提交
1315
} // namespace engine
J
jinhai 已提交
1316
} // namespace milvus
X
Xu Peng 已提交
1317
} // namespace zilliz