SqliteMetaImpl.cpp 50.5 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 65
                                   make_column("dimension", &TableSchema::dimension_),
                                   make_column("created_on", &TableSchema::created_on_),
                                   make_column("engine_type", &TableSchema::engine_type_),
66 67 68
                                   make_column("nlist", &TableSchema::nlist_),
                                   make_column("index_file_size", &TableSchema::index_file_size_),
                                   make_column("metric_type", &TableSchema::metric_type_)),
G
groot 已提交
69
                        make_table("TableFiles",
G
groot 已提交
70 71
                                   make_column("id", &TableFileSchema::id_, primary_key()),
                                   make_column("table_id", &TableFileSchema::table_id_),
G
groot 已提交
72
                                   make_column("engine_type", &TableFileSchema::engine_type_),
G
groot 已提交
73 74
                                   make_column("file_id", &TableFileSchema::file_id_),
                                   make_column("file_type", &TableFileSchema::file_type_),
75 76
                                   make_column("file_size", &TableFileSchema::file_size_, default_value(0)),
                                   make_column("row_count", &TableFileSchema::row_count_, default_value(0)),
G
groot 已提交
77 78 79
                                   make_column("updated_time", &TableFileSchema::updated_time_),
                                   make_column("created_on", &TableFileSchema::created_on_),
                                   make_column("date", &TableFileSchema::date_))
80
    );
X
Xu Peng 已提交
81 82 83

}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

175 176 177
        //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 已提交
178 179
        if (table_schema.table_id_ == "") {
            NextTableId(table_schema.table_id_);
G
groot 已提交
180 181 182 183
        } else {
            auto table = ConnectorPtr->select(columns(&TableSchema::state_),
                                               where(c(&TableSchema::table_id_) == table_schema.table_id_));
            if (table.size() == 1) {
G
groot 已提交
184 185 186
                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 {
187 188
                    // Change from no error to already exist.
                    return Status::AlreadyExist("Table already exists");
G
groot 已提交
189
                }
G
groot 已提交
190
            }
G
groot 已提交
191
        }
G
groot 已提交
192

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

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

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

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

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

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

217 218 219
        //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 已提交
220 221 222 223 224
        //soft delete table
        auto tables = ConnectorPtr->select(columns(&TableSchema::id_,
                                                   &TableSchema::dimension_,
                                                   &TableSchema::engine_type_,
                                                   &TableSchema::created_on_),
G
groot 已提交
225 226
                                           where(c(&TableSchema::table_id_) == table_id));
        for (auto &table : tables) {
G
groot 已提交
227 228 229 230
            TableSchema table_schema;
            table_schema.table_id_ = table_id;
            table_schema.state_ = (int)TableSchema::TO_DELETE;
            table_schema.id_ = std::get<0>(table);
231 232 233
            table_schema.dimension_ = std::get<1>(table);
            table_schema.engine_type_ = std::get<2>(table);
            table_schema.created_on_ = std::get<3>(table);
G
groot 已提交
234 235

            ConnectorPtr->update<TableSchema>(table_schema);
G
groot 已提交
236 237
        }
    } catch (std::exception &e) {
G
groot 已提交
238
        return HandleException("Encounter exception when delete table", e);
G
groot 已提交
239 240 241 242 243
    }

    return Status::OK();
}

S
starlord 已提交
244
Status SqliteMetaImpl::DeleteTableFiles(const std::string& table_id) {
G
groot 已提交
245 246 247
    try {
        MetricCollector metric;

248 249 250
        //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 已提交
251 252 253 254 255 256 257 258 259 260 261 262 263
        //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 已提交
264 265 266 267 268
    }

    return Status::OK();
}

S
starlord 已提交
269
Status SqliteMetaImpl::DescribeTable(TableSchema &table_schema) {
270
    try {
G
groot 已提交
271 272
        MetricCollector metric;

G
groot 已提交
273
        auto groups = ConnectorPtr->select(columns(&TableSchema::id_,
S
starlord 已提交
274
                                                   &TableSchema::state_,
G
groot 已提交
275
                                                   &TableSchema::dimension_,
S
starlord 已提交
276 277 278 279 280
                                                   &TableSchema::created_on_,
                                                   &TableSchema::engine_type_,
                                                   &TableSchema::nlist_,
                                                   &TableSchema::index_file_size_,
                                                   &TableSchema::metric_type_),
G
groot 已提交
281 282 283
                                           where(c(&TableSchema::table_id_) == table_schema.table_id_
                                                 and c(&TableSchema::state_) != (int)TableSchema::TO_DELETE));

284
        if (groups.size() == 1) {
G
groot 已提交
285
            table_schema.id_ = std::get<0>(groups[0]);
S
starlord 已提交
286 287 288 289 290 291 292
            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]);
            table_schema.engine_type_ = std::get<4>(groups[0]);
            table_schema.nlist_ = std::get<5>(groups[0]);
            table_schema.index_file_size_ = std::get<6>(groups[0]);
            table_schema.metric_type_ = std::get<7>(groups[0]);
293
        } else {
G
groot 已提交
294
            return Status::NotFound("Table " + table_schema.table_id_ + " not found");
295
        }
G
groot 已提交
296

297
    } catch (std::exception &e) {
G
groot 已提交
298
        return HandleException("Encounter exception when describe table", e);
X
Xu Peng 已提交
299
    }
X
Xu Peng 已提交
300

X
Xu Peng 已提交
301
    return Status::OK();
X
Xu Peng 已提交
302 303
}

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

        if (selected.size() >= 1) {
            has = true;
322 323

            int raw_count = 0, new_count = 0, new_merge_count = 0, new_index_count = 0, to_index_count = 0;
S
starlord 已提交
324
            std::vector<std::string> file_ids;
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
            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 已提交
350 351 352 353 354 355 356 357
        }

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

358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
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_,
                                                   &TableSchema::created_on_),
                                           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]);
            table_schema.engine_type_ = index.engine_type_;
S
starlord 已提交
380
            table_schema.nlist_ = index.nlist_;
S
starlord 已提交
381
            table_schema.index_file_size_ = index.index_file_size_*ONE_MB;
S
starlord 已提交
382
            table_schema.metric_type_ = index.metric_type_;
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419

            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);
    }
    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 已提交
420
            index.nlist_ = std::get<1>(groups[0]);
S
starlord 已提交
421
            index.index_file_size_ = std::get<2>(groups[0])/ONE_MB;
S
starlord 已提交
422
            index.metric_type_ = std::get<3>(groups[0]);
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
        } 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 已提交
470
Status SqliteMetaImpl::HasTable(const std::string &table_id, bool &has_or_not) {
G
groot 已提交
471
    has_or_not = false;
472

G
groot 已提交
473 474
    try {
        MetricCollector metric;
G
groot 已提交
475
        auto tables = ConnectorPtr->select(columns(&TableSchema::id_),
G
groot 已提交
476 477
                                           where(c(&TableSchema::table_id_) == table_id
                                           and c(&TableSchema::state_) != (int)TableSchema::TO_DELETE));
478
        if (tables.size() == 1) {
479 480 481 482
            has_or_not = true;
        } else {
            has_or_not = false;
        }
G
groot 已提交
483

484
    } catch (std::exception &e) {
G
groot 已提交
485
        return HandleException("Encounter exception when lookup table", e);
G
groot 已提交
486
    }
G
groot 已提交
487

G
groot 已提交
488 489 490
    return Status::OK();
}

S
starlord 已提交
491
Status SqliteMetaImpl::AllTables(std::vector<TableSchema>& table_schema_array) {
G
groot 已提交
492
    try {
G
groot 已提交
493 494
        MetricCollector metric;

G
groot 已提交
495 496 497
        auto selected = ConnectorPtr->select(columns(&TableSchema::id_,
                                                   &TableSchema::table_id_,
                                                   &TableSchema::dimension_,
498
                                                   &TableSchema::engine_type_),
G
groot 已提交
499
                                             where(c(&TableSchema::state_) != (int)TableSchema::TO_DELETE));
G
groot 已提交
500 501 502 503
        for (auto &table : selected) {
            TableSchema schema;
            schema.id_ = std::get<0>(table);
            schema.table_id_ = std::get<1>(table);
504 505
            schema.dimension_ = std::get<2>(table);
            schema.engine_type_ = std::get<3>(table);
G
groot 已提交
506 507 508

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

G
groot 已提交
510
    } catch (std::exception &e) {
G
groot 已提交
511
        return HandleException("Encounter exception when lookup all tables", e);
X
Xu Peng 已提交
512
    }
G
groot 已提交
513

X
Xu Peng 已提交
514
    return Status::OK();
X
Xu Peng 已提交
515 516
}

S
starlord 已提交
517
Status SqliteMetaImpl::CreateTableFile(TableFileSchema &file_schema) {
G
groot 已提交
518 519
    if (file_schema.date_ == EmptyDate) {
        file_schema.date_ = Meta::GetDate();
X
Xu Peng 已提交
520
    }
521
    TableSchema table_schema;
G
groot 已提交
522
    table_schema.table_id_ = file_schema.table_id_;
X
Xu Peng 已提交
523
    auto status = DescribeTable(table_schema);
X
Xu Peng 已提交
524 525 526
    if (!status.ok()) {
        return status;
    }
527

G
groot 已提交
528 529 530 531 532
    try {
        MetricCollector metric;

        NextFileId(file_schema.file_id_);
        file_schema.dimension_ = table_schema.dimension_;
533 534
        file_schema.file_size_ = 0;
        file_schema.row_count_ = 0;
G
groot 已提交
535 536 537 538
        file_schema.created_on_ = utils::GetMicroSecTimeStamp();
        file_schema.updated_time_ = file_schema.created_on_;
        file_schema.engine_type_ = table_schema.engine_type_;

539 540 541
        //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 已提交
542 543 544
        auto id = ConnectorPtr->insert(file_schema);
        file_schema.id_ = id;

S
starlord 已提交
545
        return utils::CreateTableFilePath(options_, file_schema);
546

G
groot 已提交
547 548
    } catch (std::exception& ex) {
        return HandleException("Encounter exception when create table file", ex);
549 550
    }

X
Xu Peng 已提交
551
    return Status::OK();
X
Xu Peng 已提交
552 553
}

S
starlord 已提交
554
Status SqliteMetaImpl::FilesToIndex(TableFilesSchema &files) {
X
Xu Peng 已提交
555
    files.clear();
X
Xu Peng 已提交
556

557
    try {
G
groot 已提交
558 559
        MetricCollector metric;

G
groot 已提交
560 561 562 563
        auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                     &TableFileSchema::table_id_,
                                                     &TableFileSchema::file_id_,
                                                     &TableFileSchema::file_type_,
S
starlord 已提交
564
                                                     &TableFileSchema::file_size_,
565
                                                     &TableFileSchema::row_count_,
G
groot 已提交
566
                                                     &TableFileSchema::date_,
S
starlord 已提交
567 568
                                                     &TableFileSchema::engine_type_,
                                                     &TableFileSchema::created_on_),
G
groot 已提交
569
                                             where(c(&TableFileSchema::file_type_)
570
                                                       == (int) TableFileSchema::TO_INDEX));
571

572
        std::map<std::string, TableSchema> groups;
X
Xu Peng 已提交
573
        TableFileSchema table_file;
574

575
        for (auto &file : selected) {
G
groot 已提交
576 577 578 579
            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 已提交
580 581 582 583 584
            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 已提交
585

S
starlord 已提交
586
            utils::GetTableFilePath(options_, table_file);
G
groot 已提交
587
            auto groupItr = groups.find(table_file.table_id_);
588
            if (groupItr == groups.end()) {
589
                TableSchema table_schema;
G
groot 已提交
590
                table_schema.table_id_ = table_file.table_id_;
X
Xu Peng 已提交
591
                auto status = DescribeTable(table_schema);
592 593 594
                if (!status.ok()) {
                    return status;
                }
G
groot 已提交
595
                groups[table_file.table_id_] = table_schema;
X
Xu Peng 已提交
596
            }
G
groot 已提交
597
            table_file.dimension_ = groups[table_file.table_id_].dimension_;
X
Xu Peng 已提交
598
            files.push_back(table_file);
X
Xu Peng 已提交
599
        }
G
groot 已提交
600

601
    } catch (std::exception &e) {
G
groot 已提交
602
        return HandleException("Encounter exception when iterate raw files", e);
X
Xu Peng 已提交
603
    }
X
Xu Peng 已提交
604

X
Xu Peng 已提交
605 606 607
    return Status::OK();
}

S
starlord 已提交
608
Status SqliteMetaImpl::FilesToSearch(const std::string &table_id,
609 610
                                 const DatesT &partition,
                                 DatePartionedTableFilesSchema &files) {
X
xj.lin 已提交
611
    files.clear();
X
Xu Peng 已提交
612

613
    try {
G
groot 已提交
614 615
        MetricCollector metric;

X
Xu Peng 已提交
616
        if (partition.empty()) {
617
            std::vector<int> file_type = {(int) TableFileSchema::RAW, (int) TableFileSchema::TO_INDEX, (int) TableFileSchema::INDEX};
G
groot 已提交
618 619 620 621
            auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                         &TableFileSchema::table_id_,
                                                         &TableFileSchema::file_id_,
                                                         &TableFileSchema::file_type_,
S
starlord 已提交
622
                                                         &TableFileSchema::file_size_,
623
                                                         &TableFileSchema::row_count_,
G
groot 已提交
624 625 626
                                                         &TableFileSchema::date_,
                                                         &TableFileSchema::engine_type_),
                                                 where(c(&TableFileSchema::table_id_) == table_id and
627
                                                       in(&TableFileSchema::file_type_, file_type)));
G
groot 已提交
628

X
Xu Peng 已提交
629
            TableSchema table_schema;
G
groot 已提交
630
            table_schema.table_id_ = table_id;
X
Xu Peng 已提交
631 632 633 634
            auto status = DescribeTable(table_schema);
            if (!status.ok()) {
                return status;
            }
X
xj.lin 已提交
635

X
Xu Peng 已提交
636 637 638
            TableFileSchema table_file;

            for (auto &file : selected) {
G
groot 已提交
639 640 641 642
                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 已提交
643 644 645 646
                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);
G
groot 已提交
647
                table_file.dimension_ = table_schema.dimension_;
S
starlord 已提交
648
                utils::GetTableFilePath(options_, table_file);
G
groot 已提交
649
                auto dateItr = files.find(table_file.date_);
X
Xu Peng 已提交
650
                if (dateItr == files.end()) {
G
groot 已提交
651
                    files[table_file.date_] = TableFilesSchema();
X
Xu Peng 已提交
652
                }
G
groot 已提交
653
                files[table_file.date_].push_back(table_file);
X
Xu Peng 已提交
654 655 656
            }
        }
        else {
657
            std::vector<int> file_type = {(int) TableFileSchema::RAW, (int) TableFileSchema::TO_INDEX, (int) TableFileSchema::INDEX};
G
groot 已提交
658 659 660 661
            auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                         &TableFileSchema::table_id_,
                                                         &TableFileSchema::file_id_,
                                                         &TableFileSchema::file_type_,
S
starlord 已提交
662
                                                         &TableFileSchema::file_size_,
663
                                                         &TableFileSchema::row_count_,
G
groot 已提交
664 665
                                                         &TableFileSchema::date_,
                                                         &TableFileSchema::engine_type_),
G
groot 已提交
666
                                                 where(c(&TableFileSchema::table_id_) == table_id and
667 668
                                                       in(&TableFileSchema::date_, partition) and
                                                       in(&TableFileSchema::file_type_, file_type)));
G
groot 已提交
669

X
Xu Peng 已提交
670
            TableSchema table_schema;
G
groot 已提交
671
            table_schema.table_id_ = table_id;
X
Xu Peng 已提交
672 673 674 675
            auto status = DescribeTable(table_schema);
            if (!status.ok()) {
                return status;
            }
X
Xu Peng 已提交
676

X
Xu Peng 已提交
677 678 679
            TableFileSchema table_file;

            for (auto &file : selected) {
G
groot 已提交
680 681 682 683
                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 已提交
684 685 686 687
                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);
G
groot 已提交
688
                table_file.dimension_ = table_schema.dimension_;
S
starlord 已提交
689
                utils::GetTableFilePath(options_, table_file);
G
groot 已提交
690
                auto dateItr = files.find(table_file.date_);
X
Xu Peng 已提交
691
                if (dateItr == files.end()) {
G
groot 已提交
692
                    files[table_file.date_] = TableFilesSchema();
X
Xu Peng 已提交
693
                }
G
groot 已提交
694
                files[table_file.date_].push_back(table_file);
695
            }
X
Xu Peng 已提交
696

X
xj.lin 已提交
697
        }
698
    } catch (std::exception &e) {
G
groot 已提交
699
        return HandleException("Encounter exception when iterate index files", e);
X
xj.lin 已提交
700 701 702 703 704
    }

    return Status::OK();
}

S
starlord 已提交
705
Status SqliteMetaImpl::FilesToSearch(const std::string &table_id,
X
xj.lin 已提交
706 707 708 709 710 711 712 713 714 715 716
                                 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 已提交
717
                                      &TableFileSchema::file_size_,
718
                                      &TableFileSchema::row_count_,
X
xj.lin 已提交
719 720 721 722
                                      &TableFileSchema::date_,
                                      &TableFileSchema::engine_type_);

        auto match_tableid = c(&TableFileSchema::table_id_) == table_id;
X
xj.lin 已提交
723 724 725

        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 已提交
726 727 728 729 730 731 732 733

        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 已提交
734
            auto filter = where(match_tableid and match_type);
X
xj.lin 已提交
735 736 737 738
            result = ConnectorPtr->select(select_columns, filter);
        }
        else if (partition.empty() && !ids.empty()) {
            auto match_fileid = in(&TableFileSchema::id_, ids);
X
xj.lin 已提交
739
            auto filter = where(match_tableid and match_fileid and match_type);
X
xj.lin 已提交
740 741 742 743
            result = ConnectorPtr->select(select_columns, filter);
        }
        else if (!partition.empty() && ids.empty()) {
            auto match_date = in(&TableFileSchema::date_, partition);
X
xj.lin 已提交
744
            auto filter = where(match_tableid and match_date and match_type);
X
xj.lin 已提交
745 746 747 748 749
            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 已提交
750
            auto filter = where(match_tableid and match_fileid and match_date and match_type);
X
xj.lin 已提交
751 752 753 754 755 756 757 758 759
            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 已提交
760 761 762 763
            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 已提交
764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779
            table_file.dimension_ = table_schema.dimension_;
            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 已提交
780
Status SqliteMetaImpl::FilesToMerge(const std::string &table_id,
781
                                DatePartionedTableFilesSchema &files) {
X
Xu Peng 已提交
782
    files.clear();
X
Xu Peng 已提交
783

784
    try {
G
groot 已提交
785 786
        MetricCollector metric;

S
starlord 已提交
787 788 789 790 791 792 793 794 795
        //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 已提交
796 797 798 799
        auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                     &TableFileSchema::table_id_,
                                                     &TableFileSchema::file_id_,
                                                     &TableFileSchema::file_type_,
800
                                                     &TableFileSchema::file_size_,
S
starlord 已提交
801 802 803
                                                     &TableFileSchema::row_count_,
                                                     &TableFileSchema::date_,
                                                     &TableFileSchema::created_on_),
G
groot 已提交
804
                                             where(c(&TableFileSchema::file_type_) == (int) TableFileSchema::RAW and
G
groot 已提交
805
                                                 c(&TableFileSchema::table_id_) == table_id),
806
                                             order_by(&TableFileSchema::file_size_).desc());
G
groot 已提交
807

808
        for (auto &file : selected) {
S
starlord 已提交
809 810 811 812 813 814
            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 已提交
815 816 817 818
            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 已提交
819 820 821
            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 已提交
822
            table_file.dimension_ = table_schema.dimension_;
S
starlord 已提交
823
            utils::GetTableFilePath(options_, table_file);
G
groot 已提交
824
            auto dateItr = files.find(table_file.date_);
825
            if (dateItr == files.end()) {
G
groot 已提交
826
                files[table_file.date_] = TableFilesSchema();
827
            }
G
groot 已提交
828
            files[table_file.date_].push_back(table_file);
X
Xu Peng 已提交
829
        }
830
    } catch (std::exception &e) {
G
groot 已提交
831
        return HandleException("Encounter exception when iterate merge files", e);
X
Xu Peng 已提交
832 833 834
    }

    return Status::OK();
X
Xu Peng 已提交
835 836
}

S
starlord 已提交
837
Status SqliteMetaImpl::GetTableFiles(const std::string& table_id,
838 839
                                 const std::vector<size_t>& ids,
                                 TableFilesSchema& table_files) {
X
Xu Peng 已提交
840
    try {
841
        table_files.clear();
Y
yu yunfeng 已提交
842 843
        auto files = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                  &TableFileSchema::file_id_,
G
groot 已提交
844
                                                  &TableFileSchema::file_type_,
845 846
                                                  &TableFileSchema::file_size_,
                                                  &TableFileSchema::row_count_,
847
                                                  &TableFileSchema::date_,
S
starlord 已提交
848 849
                                                  &TableFileSchema::engine_type_,
                                                  &TableFileSchema::created_on_),
850 851
                                          where(c(&TableFileSchema::table_id_) == table_id and
                                                  in(&TableFileSchema::id_, ids)
X
Xu Peng 已提交
852
                                          ));
853 854 855 856 857 858 859 860 861 862

        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 已提交
863
            file_schema.table_id_ = table_id;
Y
yu yunfeng 已提交
864 865 866
            file_schema.id_ = std::get<0>(file);
            file_schema.file_id_ = std::get<1>(file);
            file_schema.file_type_ = std::get<2>(file);
867 868 869 870
            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 已提交
871
            file_schema.created_on_ = std::get<7>(file);
872
            file_schema.dimension_ = table_schema.dimension_;
S
starlord 已提交
873
            utils::GetTableFilePath(options_, file_schema);
874 875

            table_files.emplace_back(file_schema);
X
Xu Peng 已提交
876 877
        }
    } catch (std::exception &e) {
878
        return HandleException("Encounter exception when lookup table files", e);
X
Xu Peng 已提交
879 880
    }

X
Xu Peng 已提交
881
    return Status::OK();
X
Xu Peng 已提交
882 883
}

X
Xu Peng 已提交
884
// PXU TODO: Support Swap
S
starlord 已提交
885
Status SqliteMetaImpl::Archive() {
886
    auto &criterias = options_.archive_conf.GetCriterias();
X
Xu Peng 已提交
887 888 889 890 891
    if (criterias.size() == 0) {
        return Status::OK();
    }

    for (auto kv : criterias) {
892 893
        auto &criteria = kv.first;
        auto &limit = kv.second;
G
groot 已提交
894
        if (criteria == engine::ARCHIVE_CONF_DAYS) {
X
Xu Peng 已提交
895
            long usecs = limit * D_SEC * US_PS;
896
            long now = utils::GetMicroSecTimeStamp();
897
            try {
898 899 900
                //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 已提交
901
                ConnectorPtr->update_all(
902
                    set(
G
groot 已提交
903
                        c(&TableFileSchema::file_type_) = (int) TableFileSchema::TO_DELETE
904 905
                    ),
                    where(
G
groot 已提交
906 907
                        c(&TableFileSchema::created_on_) < (long) (now - usecs) and
                            c(&TableFileSchema::file_type_) != (int) TableFileSchema::TO_DELETE
908 909
                    ));
            } catch (std::exception &e) {
G
groot 已提交
910
                return HandleException("Encounter exception when update table files", e);
X
Xu Peng 已提交
911 912
            }
        }
G
groot 已提交
913
        if (criteria == engine::ARCHIVE_CONF_DISK) {
G
groot 已提交
914
            uint64_t sum = 0;
X
Xu Peng 已提交
915
            Size(sum);
X
Xu Peng 已提交
916

G
groot 已提交
917
            int64_t to_delete = (int64_t)sum - limit * G;
X
Xu Peng 已提交
918
            DiscardFiles(to_delete);
X
Xu Peng 已提交
919 920 921 922 923 924
        }
    }

    return Status::OK();
}

S
starlord 已提交
925
Status SqliteMetaImpl::Size(uint64_t &result) {
X
Xu Peng 已提交
926
    result = 0;
X
Xu Peng 已提交
927
    try {
928
        auto selected = ConnectorPtr->select(columns(sum(&TableFileSchema::file_size_)),
S
starlord 已提交
929 930 931
                                          where(
                                                  c(&TableFileSchema::file_type_) != (int) TableFileSchema::TO_DELETE
                                          ));
932 933 934
        for (auto &total_size : selected) {
            if (!std::get<0>(total_size)) {
                continue;
X
Xu Peng 已提交
935
            }
936
            result += (uint64_t) (*std::get<0>(total_size));
X
Xu Peng 已提交
937
        }
938

939
    } catch (std::exception &e) {
G
groot 已提交
940
        return HandleException("Encounter exception when calculte db size", e);
X
Xu Peng 已提交
941 942 943 944 945
    }

    return Status::OK();
}

S
starlord 已提交
946
Status SqliteMetaImpl::DiscardFiles(long to_discard_size) {
X
Xu Peng 已提交
947 948 949
    if (to_discard_size <= 0) {
        return Status::OK();
    }
G
groot 已提交
950

G
groot 已提交
951
    ENGINE_LOG_DEBUG << "About to discard size=" << to_discard_size;
G
groot 已提交
952

X
Xu Peng 已提交
953
    try {
G
groot 已提交
954 955
        MetricCollector metric;

956 957 958
        //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 已提交
959 960
        auto commited = ConnectorPtr->transaction([&]() mutable {
            auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
961
                                                         &TableFileSchema::file_size_),
G
groot 已提交
962
                                                 where(c(&TableFileSchema::file_type_)
963
                                                       != (int) TableFileSchema::TO_DELETE),
G
groot 已提交
964 965
                                                 order_by(&TableFileSchema::id_),
                                                 limit(10));
X
Xu Peng 已提交
966

G
groot 已提交
967 968
            std::vector<int> ids;
            TableFileSchema table_file;
969

G
groot 已提交
970 971 972
            for (auto &file : selected) {
                if (to_discard_size <= 0) break;
                table_file.id_ = std::get<0>(file);
973
                table_file.file_size_ = std::get<1>(file);
G
groot 已提交
974 975
                ids.push_back(table_file.id_);
                ENGINE_LOG_DEBUG << "Discard table_file.id=" << table_file.file_id_
976 977
                                 << " table_file.size=" << table_file.file_size_;
                to_discard_size -= table_file.file_size_;
G
groot 已提交
978
            }
979

G
groot 已提交
980 981 982
            if (ids.size() == 0) {
                return true;
            }
983

G
groot 已提交
984 985 986 987 988 989 990 991 992 993 994 995 996
            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) {
997
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
998 999
            return Status::DBTransactionError("Update table file error");
        }
X
Xu Peng 已提交
1000

1001
    } catch (std::exception &e) {
G
groot 已提交
1002
        return HandleException("Encounter exception when discard table file", e);
X
Xu Peng 已提交
1003 1004
    }

X
Xu Peng 已提交
1005
    return DiscardFiles(to_discard_size);
X
Xu Peng 已提交
1006 1007
}

S
starlord 已提交
1008
Status SqliteMetaImpl::UpdateTableFile(TableFileSchema &file_schema) {
G
groot 已提交
1009
    file_schema.updated_time_ = utils::GetMicroSecTimeStamp();
1010
    try {
G
groot 已提交
1011 1012
        MetricCollector metric;

1013 1014 1015
        //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 已提交
1016 1017 1018 1019 1020 1021 1022 1023 1024
        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 已提交
1025
        ConnectorPtr->update(file_schema);
G
groot 已提交
1026

1027
    } catch (std::exception &e) {
G
groot 已提交
1028 1029 1030
        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 已提交
1031
    }
X
Xu Peng 已提交
1032
    return Status::OK();
X
Xu Peng 已提交
1033 1034
}

S
starlord 已提交
1035
Status SqliteMetaImpl::UpdateTableFilesToIndex(const std::string& table_id) {
P
peng.xu 已提交
1036
    try {
1037 1038 1039 1040 1041
        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 已提交
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
        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 已提交
1057
Status SqliteMetaImpl::UpdateTableFiles(TableFilesSchema &files) {
1058
    try {
G
groot 已提交
1059 1060
        MetricCollector metric;

1061 1062 1063
        //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 已提交
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
        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;
            }
        }

1079 1080
        auto commited = ConnectorPtr->transaction([&]() mutable {
            for (auto &file : files) {
G
groot 已提交
1081 1082 1083 1084
                if(!has_tables[file.table_id_]) {
                    file.file_type_ = TableFileSchema::TO_DELETE;
                }

G
groot 已提交
1085
                file.updated_time_ = utils::GetMicroSecTimeStamp();
1086 1087 1088 1089
                ConnectorPtr->update(file);
            }
            return true;
        });
G
groot 已提交
1090

1091
        if (!commited) {
1092
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
1093
            return Status::DBTransactionError("Update table files error");
X
Xu Peng 已提交
1094
        }
G
groot 已提交
1095

1096
    } catch (std::exception &e) {
G
groot 已提交
1097
        return HandleException("Encounter exception when update table files", e);
X
Xu Peng 已提交
1098
    }
1099 1100 1101
    return Status::OK();
}

S
starlord 已提交
1102
Status SqliteMetaImpl::CleanUpFilesWithTTL(uint16_t seconds) {
X
Xu Peng 已提交
1103
    auto now = utils::GetMicroSecTimeStamp();
S
starlord 已提交
1104 1105 1106
    std::set<std::string> table_ids;

    //remove to_delete files
1107
    try {
G
groot 已提交
1108
        MetricCollector metric;
1109

1110 1111 1112
        //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 已提交
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
        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));
1123

G
groot 已提交
1124 1125 1126 1127 1128 1129 1130 1131
        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 已提交
1132
                utils::DeleteTableFilePath(options_, table_file);
1133
                ENGINE_LOG_DEBUG << "Removing file id:" << table_file.file_id_ << " location:" << table_file.location_;
G
groot 已提交
1134 1135
                ConnectorPtr->remove<TableFileSchema>(table_file.id_);

S
starlord 已提交
1136
                table_ids.insert(table_file.table_id_);
1137
            }
G
groot 已提交
1138 1139 1140 1141
            return true;
        });

        if (!commited) {
1142
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
1143 1144 1145 1146 1147 1148 1149
            return Status::DBTransactionError("Clean files error");
        }

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

S
starlord 已提交
1150
    //remove to_delete tables
G
groot 已提交
1151 1152 1153
    try {
        MetricCollector metric;

1154 1155 1156
        //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 已提交
1157 1158 1159 1160 1161 1162
        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 已提交
1163
                utils::DeleteTablePath(options_, std::get<1>(table), false);//only delete empty folder
G
groot 已提交
1164
                ConnectorPtr->remove<TableSchema>(std::get<0>(table));
1165
            }
G
groot 已提交
1166 1167 1168 1169 1170

            return true;
        });

        if (!commited) {
1171
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
1172
            return Status::DBTransactionError("Clean files error");
X
Xu Peng 已提交
1173
        }
G
groot 已提交
1174

1175
    } catch (std::exception &e) {
G
groot 已提交
1176
        return HandleException("Encounter exception when clean table files", e);
X
Xu Peng 已提交
1177 1178
    }

S
starlord 已提交
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
    //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 已提交
1196 1197 1198
    return Status::OK();
}

S
starlord 已提交
1199
Status SqliteMetaImpl::CleanUp() {
1200
    try {
1201 1202 1203 1204 1205
        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_);

1206 1207
        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)));
1208

G
groot 已提交
1209 1210 1211 1212
        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));
1213
            }
G
groot 已提交
1214 1215 1216 1217
            return true;
        });

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

1222
    } catch (std::exception &e) {
G
groot 已提交
1223
        return HandleException("Encounter exception when clean table file", e);
X
Xu Peng 已提交
1224 1225 1226 1227 1228
    }

    return Status::OK();
}

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

1231
    try {
G
groot 已提交
1232
        MetricCollector metric;
1233

1234 1235 1236
        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 已提交
1237
                                                   and c(&TableFileSchema::table_id_) == table_id));
1238

1239
        TableSchema table_schema;
G
groot 已提交
1240
        table_schema.table_id_ = table_id;
X
Xu Peng 已提交
1241
        auto status = DescribeTable(table_schema);
1242

1243 1244 1245 1246 1247
        if (!status.ok()) {
            return status;
        }

        result = 0;
1248
        for (auto &file : selected) {
1249 1250
            result += std::get<0>(file);
        }
X
Xu Peng 已提交
1251

1252
    } catch (std::exception &e) {
G
groot 已提交
1253
        return HandleException("Encounter exception when calculate table file size", e);
X
Xu Peng 已提交
1254 1255 1256 1257
    }
    return Status::OK();
}

S
starlord 已提交
1258
Status SqliteMetaImpl::DropAll() {
X
Xu Peng 已提交
1259 1260
    if (boost::filesystem::is_directory(options_.path)) {
        boost::filesystem::remove_all(options_.path);
X
Xu Peng 已提交
1261 1262 1263 1264
    }
    return Status::OK();
}

S
starlord 已提交
1265
SqliteMetaImpl::~SqliteMetaImpl() {
1266
    CleanUp();
X
Xu Peng 已提交
1267 1268
}

1269
} // namespace meta
X
Xu Peng 已提交
1270
} // namespace engine
J
jinhai 已提交
1271
} // namespace milvus
X
Xu Peng 已提交
1272
} // namespace zilliz