SqliteMetaImpl.cpp 48.0 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 37 38
}

}

39
inline auto StoragePrototype(const std::string &path) {
X
Xu Peng 已提交
40
    return make_storage(path,
G
groot 已提交
41
                        make_table("Tables",
G
groot 已提交
42 43
                                   make_column("id", &TableSchema::id_, primary_key()),
                                   make_column("table_id", &TableSchema::table_id_, unique()),
G
groot 已提交
44
                                   make_column("state", &TableSchema::state_),
G
groot 已提交
45 46
                                   make_column("dimension", &TableSchema::dimension_),
                                   make_column("created_on", &TableSchema::created_on_),
S
starlord 已提交
47
                                   make_column("flag", &TableSchema::flag_, default_value(0)),
48
                                   make_column("index_file_size", &TableSchema::index_file_size_),
G
groot 已提交
49
                                   make_column("engine_type", &TableSchema::engine_type_),
50 51
                                   make_column("nlist", &TableSchema::nlist_),
                                   make_column("metric_type", &TableSchema::metric_type_)),
G
groot 已提交
52
                        make_table("TableFiles",
G
groot 已提交
53 54
                                   make_column("id", &TableFileSchema::id_, primary_key()),
                                   make_column("table_id", &TableFileSchema::table_id_),
G
groot 已提交
55
                                   make_column("engine_type", &TableFileSchema::engine_type_),
G
groot 已提交
56 57
                                   make_column("file_id", &TableFileSchema::file_id_),
                                   make_column("file_type", &TableFileSchema::file_type_),
58 59
                                   make_column("file_size", &TableFileSchema::file_size_, default_value(0)),
                                   make_column("row_count", &TableFileSchema::row_count_, default_value(0)),
G
groot 已提交
60 61 62
                                   make_column("updated_time", &TableFileSchema::updated_time_),
                                   make_column("created_on", &TableFileSchema::created_on_),
                                   make_column("date", &TableFileSchema::date_))
63
    );
X
Xu Peng 已提交
64 65 66

}

X
Xu Peng 已提交
67
using ConnectorT = decltype(StoragePrototype(""));
X
Xu Peng 已提交
68
static std::unique_ptr<ConnectorT> ConnectorPtr;
G
groot 已提交
69
using ConditionT = decltype(c(&TableFileSchema::id_) == 1UL);
X
Xu Peng 已提交
70

71 72 73 74 75 76 77 78 79
SqliteMetaImpl::SqliteMetaImpl(const DBMetaOptions &options_)
    : options_(options_) {
    Initialize();
}

SqliteMetaImpl::~SqliteMetaImpl() {
    CleanUp();
}

S
starlord 已提交
80
Status SqliteMetaImpl::NextTableId(std::string &table_id) {
81 82
    std::stringstream ss;
    SimpleIDGenerator g;
83
    ss << g.GetNextIDNumber();
84
    table_id = ss.str();
85 86 87
    return Status::OK();
}

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

S
starlord 已提交
96
Status SqliteMetaImpl::Initialize() {
X
Xu Peng 已提交
97 98
    if (!boost::filesystem::is_directory(options_.path)) {
        auto ret = boost::filesystem::create_directory(options_.path);
99
        if (!ret) {
G
groot 已提交
100
            ENGINE_LOG_ERROR << "Failed to create db directory " << options_.path;
101
            return Status::InvalidDBPath("Failed to create db directory", options_.path);
102
        }
X
Xu Peng 已提交
103
    }
X
Xu Peng 已提交
104

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

X
Xu Peng 已提交
107
    ConnectorPtr->sync_schema();
108
    ConnectorPtr->open_forever(); // thread safe option
109
    ConnectorPtr->pragma.journal_mode(journal_mode::WAL); // WAL => write ahead log
X
Xu Peng 已提交
110

111
    CleanUp();
X
Xu Peng 已提交
112

X
Xu Peng 已提交
113
    return Status::OK();
X
Xu Peng 已提交
114 115
}

X
Xu Peng 已提交
116
// PXU TODO: Temp solution. Will fix later
S
starlord 已提交
117
Status SqliteMetaImpl::DropPartitionsByDates(const std::string &table_id,
118
                                             const DatesT &dates) {
X
Xu Peng 已提交
119 120 121 122
    if (dates.size() == 0) {
        return Status::OK();
    }

123
    TableSchema table_schema;
G
groot 已提交
124
    table_schema.table_id_ = table_id;
X
Xu Peng 已提交
125
    auto status = DescribeTable(table_schema);
X
Xu Peng 已提交
126 127 128 129
    if (!status.ok()) {
        return status;
    }

G
groot 已提交
130
    try {
131 132 133
        //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 已提交
134
        ConnectorPtr->update_all(
135
            set(
136 137
                c(&TableFileSchema::file_type_) = (int) TableFileSchema::TO_DELETE,
                c(&TableFileSchema::updated_time_) = utils::GetMicroSecTimeStamp()
138 139
            ),
            where(
G
groot 已提交
140 141
                c(&TableFileSchema::table_id_) == table_id and
                    in(&TableFileSchema::date_, dates)
142 143
            ));
    } catch (std::exception &e) {
G
groot 已提交
144
        return HandleException("Encounter exception when drop partition", e);
X
Xu Peng 已提交
145
    }
G
groot 已提交
146

X
Xu Peng 已提交
147 148 149
    return Status::OK();
}

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

G
groot 已提交
152
    try {
Y
Yu Kun 已提交
153
        server::MetricCollector metric;
G
groot 已提交
154

155 156 157
        //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 已提交
158 159
        if (table_schema.table_id_ == "") {
            NextTableId(table_schema.table_id_);
G
groot 已提交
160 161 162 163
        } else {
            auto table = ConnectorPtr->select(columns(&TableSchema::state_),
                                               where(c(&TableSchema::table_id_) == table_schema.table_id_));
            if (table.size() == 1) {
G
groot 已提交
164 165 166
                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 {
167 168
                    // Change from no error to already exist.
                    return Status::AlreadyExist("Table already exists");
G
groot 已提交
169
                }
G
groot 已提交
170
            }
G
groot 已提交
171
        }
G
groot 已提交
172

G
groot 已提交
173 174 175
        table_schema.id_ = -1;
        table_schema.created_on_ = utils::GetMicroSecTimeStamp();

X
Xu Peng 已提交
176
        try {
177
            auto id = ConnectorPtr->insert(table_schema);
G
groot 已提交
178
            table_schema.id_ = id;
X
Xu Peng 已提交
179
        } catch (...) {
180
            ENGINE_LOG_ERROR << "sqlite transaction failed";
X
Xu Peng 已提交
181
            return Status::DBTransactionError("Add Table Error");
X
Xu Peng 已提交
182
        }
183

S
starlord 已提交
184
        return utils::CreateTablePath(options_, table_schema.table_id_);
G
groot 已提交
185 186 187

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

X
Xu Peng 已提交
190
    return Status::OK();
X
Xu Peng 已提交
191 192
}

S
starlord 已提交
193
Status SqliteMetaImpl::DeleteTable(const std::string& table_id) {
G
groot 已提交
194
    try {
Y
Yu Kun 已提交
195
        server::MetricCollector metric;
G
groot 已提交
196

197 198 199
        //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 已提交
200
        //soft delete table
S
starlord 已提交
201 202 203 204 205 206 207 208
        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 已提交
209

G
groot 已提交
210
    } catch (std::exception &e) {
G
groot 已提交
211
        return HandleException("Encounter exception when delete table", e);
G
groot 已提交
212 213 214 215 216
    }

    return Status::OK();
}

S
starlord 已提交
217
Status SqliteMetaImpl::DeleteTableFiles(const std::string& table_id) {
G
groot 已提交
218
    try {
Y
Yu Kun 已提交
219
        server::MetricCollector metric;
G
groot 已提交
220

221 222 223
        //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 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236
        //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 已提交
237 238 239 240 241
    }

    return Status::OK();
}

S
starlord 已提交
242
Status SqliteMetaImpl::DescribeTable(TableSchema &table_schema) {
243
    try {
Y
Yu Kun 已提交
244
        server::MetricCollector metric;
G
groot 已提交
245

G
groot 已提交
246
        auto groups = ConnectorPtr->select(columns(&TableSchema::id_,
S
starlord 已提交
247
                                                   &TableSchema::state_,
G
groot 已提交
248
                                                   &TableSchema::dimension_,
S
starlord 已提交
249
                                                   &TableSchema::created_on_,
S
starlord 已提交
250
                                                   &TableSchema::flag_,
251
                                                   &TableSchema::index_file_size_,
S
starlord 已提交
252 253 254
                                                   &TableSchema::engine_type_,
                                                   &TableSchema::nlist_,
                                                   &TableSchema::metric_type_),
G
groot 已提交
255 256 257
                                           where(c(&TableSchema::table_id_) == table_schema.table_id_
                                                 and c(&TableSchema::state_) != (int)TableSchema::TO_DELETE));

258
        if (groups.size() == 1) {
G
groot 已提交
259
            table_schema.id_ = std::get<0>(groups[0]);
S
starlord 已提交
260 261 262
            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 已提交
263
            table_schema.flag_ = std::get<4>(groups[0]);
264 265 266
            table_schema.index_file_size_ = std::get<5>(groups[0]);
            table_schema.engine_type_ = std::get<6>(groups[0]);
            table_schema.nlist_ = std::get<7>(groups[0]);
S
starlord 已提交
267
            table_schema.metric_type_ = std::get<8>(groups[0]);
268
        } else {
G
groot 已提交
269
            return Status::NotFound("Table " + table_schema.table_id_ + " not found");
270
        }
G
groot 已提交
271

272
    } catch (std::exception &e) {
G
groot 已提交
273
        return HandleException("Encounter exception when describe table", e);
X
Xu Peng 已提交
274
    }
X
Xu Peng 已提交
275

X
Xu Peng 已提交
276
    return Status::OK();
X
Xu Peng 已提交
277 278
}

279 280 281 282 283 284 285
Status SqliteMetaImpl::FilesByType(const std::string& table_id,
        const std::vector<int>& file_types,
        std::vector<std::string>& file_ids) {
    if(file_types.empty()) {
        return Status::Error("file types array is empty");
    }

P
peng.xu 已提交
286
    try {
287 288
        file_ids.clear();
        auto selected = ConnectorPtr->select(columns(&TableFileSchema::file_id_,
289
                                                     &TableFileSchema::file_type_),
290
                                             where(in(&TableFileSchema::file_type_, file_types)
P
peng.xu 已提交
291 292 293 294
                                                   and c(&TableFileSchema::table_id_) == table_id
                                             ));

        if (selected.size() >= 1) {
295 296
            int raw_count = 0, new_count = 0, new_merge_count = 0, new_index_count = 0;
            int to_index_count = 0, index_count = 0, backup_count = 0;
297
            for (auto &file : selected) {
298
                file_ids.push_back(std::get<0>(file));
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
                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;
315 316 317 318 319 320
                    case (int) TableFileSchema::INDEX:
                        index_count++;
                        break;
                    case (int) TableFileSchema::BACKUP:
                        backup_count++;
                        break;
321 322 323 324 325 326
                    default:
                        break;
                }
            }

            ENGINE_LOG_DEBUG << "Table " << table_id << " currently has raw files:" << raw_count
327 328 329
                             << " new files:" << new_count << " new_merge files:" << new_merge_count
                             << " new_index files:" << new_index_count << " to_index files:" << to_index_count
                             << " index files:" << index_count << " backup files:" << backup_count;
P
peng.xu 已提交
330 331 332 333 334 335 336 337
        }

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

338 339
Status SqliteMetaImpl::UpdateTableIndexParam(const std::string &table_id, const TableIndex& index) {
    try {
Y
Yu Kun 已提交
340
        server::MetricCollector metric;
341 342 343 344 345 346 347

        //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 已提交
348
                                                   &TableSchema::created_on_,
349 350
                                                   &TableSchema::flag_,
                                                   &TableSchema::index_file_size_),
351 352 353 354 355 356 357 358 359 360
                                           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 已提交
361
            table_schema.flag_ = std::get<4>(tables[0]);
362
            table_schema.index_file_size_ = std::get<5>(tables[0]);
363
            table_schema.engine_type_ = index.engine_type_;
S
starlord 已提交
364 365
            table_schema.nlist_ = index.nlist_;
            table_schema.metric_type_ = index.metric_type_;
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386

            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 已提交
387 388 389 390 391 392

    return Status::OK();
}

Status SqliteMetaImpl::UpdateTableFlag(const std::string &table_id, int64_t flag) {
    try {
Y
Yu Kun 已提交
393
        server::MetricCollector metric;
S
starlord 已提交
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408

        //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);
    }

409 410 411 412 413
    return Status::OK();
}

Status SqliteMetaImpl::DescribeTableIndex(const std::string &table_id, TableIndex& index) {
    try {
Y
Yu Kun 已提交
414
        server::MetricCollector metric;
415 416 417 418 419 420 421 422 423

        auto groups = ConnectorPtr->select(columns(&TableSchema::engine_type_,
                                                   &TableSchema::nlist_,
                                                   &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 已提交
424
            index.nlist_ = std::get<1>(groups[0]);
S
starlord 已提交
425
            index.metric_type_ = std::get<2>(groups[0]);
426 427 428 429 430 431 432 433 434 435 436 437 438
        } 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 {
Y
Yu Kun 已提交
439
        server::MetricCollector metric;
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

        //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
                ));

466 467 468 469 470 471 472 473 474 475 476
        //set table index type to raw
        ConnectorPtr->update_all(
                set(
                        c(&TableSchema::engine_type_) = DEFAULT_ENGINE_TYPE,
                        c(&TableSchema::nlist_) = DEFAULT_NLIST,
                        c(&TableSchema::metric_type_) = DEFAULT_METRIC_TYPE
                ),
                where(
                        c(&TableSchema::table_id_) == table_id
                ));

477 478 479 480 481 482 483
    } catch (std::exception &e) {
        return HandleException("Encounter exception when delete table index files", e);
    }

    return Status::OK();
}

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

G
groot 已提交
487
    try {
Y
Yu Kun 已提交
488
        server::MetricCollector metric;
G
groot 已提交
489
        auto tables = ConnectorPtr->select(columns(&TableSchema::id_),
G
groot 已提交
490 491
                                           where(c(&TableSchema::table_id_) == table_id
                                           and c(&TableSchema::state_) != (int)TableSchema::TO_DELETE));
492
        if (tables.size() == 1) {
493 494 495 496
            has_or_not = true;
        } else {
            has_or_not = false;
        }
G
groot 已提交
497

498
    } catch (std::exception &e) {
G
groot 已提交
499
        return HandleException("Encounter exception when lookup table", e);
G
groot 已提交
500
    }
G
groot 已提交
501

G
groot 已提交
502 503 504
    return Status::OK();
}

S
starlord 已提交
505
Status SqliteMetaImpl::AllTables(std::vector<TableSchema>& table_schema_array) {
G
groot 已提交
506
    try {
Y
Yu Kun 已提交
507
        server::MetricCollector metric;
G
groot 已提交
508

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

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

G
groot 已提交
534
    } catch (std::exception &e) {
G
groot 已提交
535
        return HandleException("Encounter exception when lookup all tables", e);
X
Xu Peng 已提交
536
    }
G
groot 已提交
537

X
Xu Peng 已提交
538
    return Status::OK();
X
Xu Peng 已提交
539 540
}

S
starlord 已提交
541
Status SqliteMetaImpl::CreateTableFile(TableFileSchema &file_schema) {
G
groot 已提交
542
    if (file_schema.date_ == EmptyDate) {
543
        file_schema.date_ = utils::GetDate();
X
Xu Peng 已提交
544
    }
545
    TableSchema table_schema;
G
groot 已提交
546
    table_schema.table_id_ = file_schema.table_id_;
X
Xu Peng 已提交
547
    auto status = DescribeTable(table_schema);
X
Xu Peng 已提交
548 549 550
    if (!status.ok()) {
        return status;
    }
551

G
groot 已提交
552
    try {
Y
Yu Kun 已提交
553
        server::MetricCollector metric;
G
groot 已提交
554 555 556

        NextFileId(file_schema.file_id_);
        file_schema.dimension_ = table_schema.dimension_;
557 558
        file_schema.file_size_ = 0;
        file_schema.row_count_ = 0;
G
groot 已提交
559 560
        file_schema.created_on_ = utils::GetMicroSecTimeStamp();
        file_schema.updated_time_ = file_schema.created_on_;
561
        file_schema.index_file_size_ = table_schema.index_file_size_;
G
groot 已提交
562
        file_schema.engine_type_ = table_schema.engine_type_;
S
starlord 已提交
563 564
        file_schema.nlist_ = table_schema.nlist_;
        file_schema.metric_type_ = table_schema.metric_type_;
G
groot 已提交
565

566 567 568
        //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 已提交
569 570 571
        auto id = ConnectorPtr->insert(file_schema);
        file_schema.id_ = id;

S
starlord 已提交
572
        return utils::CreateTableFilePath(options_, file_schema);
573

G
groot 已提交
574 575
    } catch (std::exception& ex) {
        return HandleException("Encounter exception when create table file", ex);
576 577
    }

X
Xu Peng 已提交
578
    return Status::OK();
X
Xu Peng 已提交
579 580
}

S
starlord 已提交
581
Status SqliteMetaImpl::FilesToIndex(TableFilesSchema &files) {
X
Xu Peng 已提交
582
    files.clear();
X
Xu Peng 已提交
583

584
    try {
Y
Yu Kun 已提交
585
        server::MetricCollector metric;
G
groot 已提交
586

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

599
        std::map<std::string, TableSchema> groups;
X
Xu Peng 已提交
600
        TableFileSchema table_file;
601

602
        for (auto &file : selected) {
G
groot 已提交
603 604 605 606
            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 已提交
607 608 609 610 611
            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 已提交
612

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

631
    } catch (std::exception &e) {
G
groot 已提交
632
        return HandleException("Encounter exception when iterate raw files", e);
X
Xu Peng 已提交
633
    }
X
Xu Peng 已提交
634

X
Xu Peng 已提交
635 636 637
    return Status::OK();
}

S
starlord 已提交
638
Status SqliteMetaImpl::FilesToSearch(const std::string &table_id,
X
xj.lin 已提交
639 640 641 642
                                 const std::vector<size_t> &ids,
                                 const DatesT &partition,
                                 DatePartionedTableFilesSchema &files) {
    files.clear();
Y
Yu Kun 已提交
643
    server::MetricCollector metric;
X
xj.lin 已提交
644 645 646 647 648 649

    try {
        auto select_columns = columns(&TableFileSchema::id_,
                                      &TableFileSchema::table_id_,
                                      &TableFileSchema::file_id_,
                                      &TableFileSchema::file_type_,
S
starlord 已提交
650
                                      &TableFileSchema::file_size_,
651
                                      &TableFileSchema::row_count_,
X
xj.lin 已提交
652 653 654 655
                                      &TableFileSchema::date_,
                                      &TableFileSchema::engine_type_);

        auto match_tableid = c(&TableFileSchema::table_id_) == table_id;
X
xj.lin 已提交
656 657 658

        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 已提交
659 660 661 662 663 664 665 666

        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 已提交
667
            auto filter = where(match_tableid and match_type);
X
xj.lin 已提交
668 669 670 671
            result = ConnectorPtr->select(select_columns, filter);
        }
        else if (partition.empty() && !ids.empty()) {
            auto match_fileid = in(&TableFileSchema::id_, ids);
X
xj.lin 已提交
672
            auto filter = where(match_tableid and match_fileid and match_type);
X
xj.lin 已提交
673 674 675 676
            result = ConnectorPtr->select(select_columns, filter);
        }
        else if (!partition.empty() && ids.empty()) {
            auto match_date = in(&TableFileSchema::date_, partition);
X
xj.lin 已提交
677
            auto filter = where(match_tableid and match_date and match_type);
X
xj.lin 已提交
678 679 680 681 682
            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 已提交
683
            auto filter = where(match_tableid and match_fileid and match_date and match_type);
X
xj.lin 已提交
684 685 686 687 688 689 690 691 692
            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 已提交
693 694 695 696
            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 已提交
697
            table_file.dimension_ = table_schema.dimension_;
S
starlord 已提交
698
            table_file.index_file_size_ = table_schema.index_file_size_;
699
            table_file.nlist_ = table_schema.nlist_;
S
starlord 已提交
700 701
            table_file.metric_type_ = table_schema.metric_type_;

X
xj.lin 已提交
702 703 704 705 706 707 708
            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);
        }
709 710 711
        if(files.empty()) {
            std::cout << "ERROR" << std::endl;
        }
X
xj.lin 已提交
712 713 714 715
    } catch (std::exception &e) {
        return HandleException("Encounter exception when iterate index files", e);
    }

716 717


X
xj.lin 已提交
718 719 720
    return Status::OK();
}

S
starlord 已提交
721
Status SqliteMetaImpl::FilesToMerge(const std::string &table_id,
722
                                DatePartionedTableFilesSchema &files) {
X
Xu Peng 已提交
723
    files.clear();
X
Xu Peng 已提交
724

725
    try {
Y
Yu Kun 已提交
726
        server::MetricCollector metric;
G
groot 已提交
727

S
starlord 已提交
728 729 730 731 732 733 734 735 736
        //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 已提交
737 738 739 740
        auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                     &TableFileSchema::table_id_,
                                                     &TableFileSchema::file_id_,
                                                     &TableFileSchema::file_type_,
741
                                                     &TableFileSchema::file_size_,
S
starlord 已提交
742 743 744
                                                     &TableFileSchema::row_count_,
                                                     &TableFileSchema::date_,
                                                     &TableFileSchema::created_on_),
G
groot 已提交
745
                                             where(c(&TableFileSchema::file_type_) == (int) TableFileSchema::RAW and
G
groot 已提交
746
                                                 c(&TableFileSchema::table_id_) == table_id),
747
                                             order_by(&TableFileSchema::file_size_).desc());
G
groot 已提交
748

749
        for (auto &file : selected) {
S
starlord 已提交
750 751 752 753 754 755
            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 已提交
756 757 758 759
            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
            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 已提交
763
            table_file.dimension_ = table_schema.dimension_;
S
starlord 已提交
764
            table_file.index_file_size_ = table_schema.index_file_size_;
765
            table_file.nlist_ = table_schema.nlist_;
S
starlord 已提交
766 767
            table_file.metric_type_ = table_schema.metric_type_;

S
starlord 已提交
768
            utils::GetTableFilePath(options_, table_file);
G
groot 已提交
769
            auto dateItr = files.find(table_file.date_);
770
            if (dateItr == files.end()) {
G
groot 已提交
771
                files[table_file.date_] = TableFilesSchema();
772
            }
G
groot 已提交
773
            files[table_file.date_].push_back(table_file);
X
Xu Peng 已提交
774
        }
775
    } catch (std::exception &e) {
G
groot 已提交
776
        return HandleException("Encounter exception when iterate merge files", e);
X
Xu Peng 已提交
777 778 779
    }

    return Status::OK();
X
Xu Peng 已提交
780 781
}

S
starlord 已提交
782
Status SqliteMetaImpl::GetTableFiles(const std::string& table_id,
783 784
                                 const std::vector<size_t>& ids,
                                 TableFilesSchema& table_files) {
X
Xu Peng 已提交
785
    try {
786
        table_files.clear();
Y
yu yunfeng 已提交
787 788
        auto files = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                  &TableFileSchema::file_id_,
G
groot 已提交
789
                                                  &TableFileSchema::file_type_,
790 791
                                                  &TableFileSchema::file_size_,
                                                  &TableFileSchema::row_count_,
792
                                                  &TableFileSchema::date_,
S
starlord 已提交
793 794
                                                  &TableFileSchema::engine_type_,
                                                  &TableFileSchema::created_on_),
795 796
                                          where(c(&TableFileSchema::table_id_) == table_id and
                                                  in(&TableFileSchema::id_, ids)
X
Xu Peng 已提交
797
                                          ));
798 799 800 801 802 803 804 805 806 807

        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 已提交
808
            file_schema.table_id_ = table_id;
Y
yu yunfeng 已提交
809 810 811
            file_schema.id_ = std::get<0>(file);
            file_schema.file_id_ = std::get<1>(file);
            file_schema.file_type_ = std::get<2>(file);
812 813 814 815
            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 已提交
816
            file_schema.created_on_ = std::get<7>(file);
817
            file_schema.dimension_ = table_schema.dimension_;
818 819 820
            file_schema.index_file_size_ = table_schema.index_file_size_;
            file_schema.nlist_ = table_schema.nlist_;
            file_schema.metric_type_ = table_schema.metric_type_;
S
starlord 已提交
821

S
starlord 已提交
822
            utils::GetTableFilePath(options_, file_schema);
823 824

            table_files.emplace_back(file_schema);
X
Xu Peng 已提交
825 826
        }
    } catch (std::exception &e) {
827
        return HandleException("Encounter exception when lookup table files", e);
X
Xu Peng 已提交
828 829
    }

X
Xu Peng 已提交
830
    return Status::OK();
X
Xu Peng 已提交
831 832
}

X
Xu Peng 已提交
833
// PXU TODO: Support Swap
S
starlord 已提交
834
Status SqliteMetaImpl::Archive() {
835
    auto &criterias = options_.archive_conf.GetCriterias();
X
Xu Peng 已提交
836 837 838 839 840
    if (criterias.size() == 0) {
        return Status::OK();
    }

    for (auto kv : criterias) {
841 842
        auto &criteria = kv.first;
        auto &limit = kv.second;
G
groot 已提交
843
        if (criteria == engine::ARCHIVE_CONF_DAYS) {
X
Xu Peng 已提交
844
            long usecs = limit * D_SEC * US_PS;
845
            long now = utils::GetMicroSecTimeStamp();
846
            try {
847 848 849
                //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 已提交
850
                ConnectorPtr->update_all(
851
                    set(
G
groot 已提交
852
                        c(&TableFileSchema::file_type_) = (int) TableFileSchema::TO_DELETE
853 854
                    ),
                    where(
G
groot 已提交
855 856
                        c(&TableFileSchema::created_on_) < (long) (now - usecs) and
                            c(&TableFileSchema::file_type_) != (int) TableFileSchema::TO_DELETE
857 858
                    ));
            } catch (std::exception &e) {
G
groot 已提交
859
                return HandleException("Encounter exception when update table files", e);
X
Xu Peng 已提交
860 861
            }
        }
G
groot 已提交
862
        if (criteria == engine::ARCHIVE_CONF_DISK) {
G
groot 已提交
863
            uint64_t sum = 0;
X
Xu Peng 已提交
864
            Size(sum);
X
Xu Peng 已提交
865

G
groot 已提交
866
            int64_t to_delete = (int64_t)sum - limit * G;
X
Xu Peng 已提交
867
            DiscardFiles(to_delete);
X
Xu Peng 已提交
868 869 870 871 872 873
        }
    }

    return Status::OK();
}

S
starlord 已提交
874
Status SqliteMetaImpl::Size(uint64_t &result) {
X
Xu Peng 已提交
875
    result = 0;
X
Xu Peng 已提交
876
    try {
877
        auto selected = ConnectorPtr->select(columns(sum(&TableFileSchema::file_size_)),
S
starlord 已提交
878 879 880
                                          where(
                                                  c(&TableFileSchema::file_type_) != (int) TableFileSchema::TO_DELETE
                                          ));
881 882 883
        for (auto &total_size : selected) {
            if (!std::get<0>(total_size)) {
                continue;
X
Xu Peng 已提交
884
            }
885
            result += (uint64_t) (*std::get<0>(total_size));
X
Xu Peng 已提交
886
        }
887

888
    } catch (std::exception &e) {
G
groot 已提交
889
        return HandleException("Encounter exception when calculte db size", e);
X
Xu Peng 已提交
890 891 892 893 894
    }

    return Status::OK();
}

S
starlord 已提交
895
Status SqliteMetaImpl::DiscardFiles(long to_discard_size) {
X
Xu Peng 已提交
896 897 898
    if (to_discard_size <= 0) {
        return Status::OK();
    }
G
groot 已提交
899

G
groot 已提交
900
    ENGINE_LOG_DEBUG << "About to discard size=" << to_discard_size;
G
groot 已提交
901

X
Xu Peng 已提交
902
    try {
Y
Yu Kun 已提交
903
        server::MetricCollector metric;
G
groot 已提交
904

905 906 907
        //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 已提交
908 909
        auto commited = ConnectorPtr->transaction([&]() mutable {
            auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
910
                                                         &TableFileSchema::file_size_),
G
groot 已提交
911
                                                 where(c(&TableFileSchema::file_type_)
912
                                                       != (int) TableFileSchema::TO_DELETE),
G
groot 已提交
913 914
                                                 order_by(&TableFileSchema::id_),
                                                 limit(10));
X
Xu Peng 已提交
915

G
groot 已提交
916 917
            std::vector<int> ids;
            TableFileSchema table_file;
918

G
groot 已提交
919 920 921
            for (auto &file : selected) {
                if (to_discard_size <= 0) break;
                table_file.id_ = std::get<0>(file);
922
                table_file.file_size_ = std::get<1>(file);
G
groot 已提交
923 924
                ids.push_back(table_file.id_);
                ENGINE_LOG_DEBUG << "Discard table_file.id=" << table_file.file_id_
925 926
                                 << " table_file.size=" << table_file.file_size_;
                to_discard_size -= table_file.file_size_;
G
groot 已提交
927
            }
928

G
groot 已提交
929 930 931
            if (ids.size() == 0) {
                return true;
            }
932

G
groot 已提交
933 934 935 936 937 938 939 940 941 942 943 944 945
            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) {
946
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
947 948
            return Status::DBTransactionError("Update table file error");
        }
X
Xu Peng 已提交
949

950
    } catch (std::exception &e) {
G
groot 已提交
951
        return HandleException("Encounter exception when discard table file", e);
X
Xu Peng 已提交
952 953
    }

X
Xu Peng 已提交
954
    return DiscardFiles(to_discard_size);
X
Xu Peng 已提交
955 956
}

S
starlord 已提交
957
Status SqliteMetaImpl::UpdateTableFile(TableFileSchema &file_schema) {
G
groot 已提交
958
    file_schema.updated_time_ = utils::GetMicroSecTimeStamp();
959
    try {
Y
Yu Kun 已提交
960
        server::MetricCollector metric;
G
groot 已提交
961

962 963 964
        //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 已提交
965 966 967 968 969 970 971 972 973
        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 已提交
974
        ConnectorPtr->update(file_schema);
G
groot 已提交
975

976
    } catch (std::exception &e) {
G
groot 已提交
977 978 979
        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 已提交
980
    }
X
Xu Peng 已提交
981
    return Status::OK();
X
Xu Peng 已提交
982 983
}

S
starlord 已提交
984
Status SqliteMetaImpl::UpdateTableFilesToIndex(const std::string& table_id) {
P
peng.xu 已提交
985
    try {
Y
Yu Kun 已提交
986
        server::MetricCollector metric;
987 988 989 990

        //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 已提交
991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
        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 已提交
1006
Status SqliteMetaImpl::UpdateTableFiles(TableFilesSchema &files) {
1007
    try {
Y
Yu Kun 已提交
1008
        server::MetricCollector metric;
G
groot 已提交
1009

1010 1011 1012
        //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 已提交
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
        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;
            }
        }

1028 1029
        auto commited = ConnectorPtr->transaction([&]() mutable {
            for (auto &file : files) {
G
groot 已提交
1030 1031 1032 1033
                if(!has_tables[file.table_id_]) {
                    file.file_type_ = TableFileSchema::TO_DELETE;
                }

G
groot 已提交
1034
                file.updated_time_ = utils::GetMicroSecTimeStamp();
1035 1036 1037 1038
                ConnectorPtr->update(file);
            }
            return true;
        });
G
groot 已提交
1039

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

1045
    } catch (std::exception &e) {
G
groot 已提交
1046
        return HandleException("Encounter exception when update table files", e);
X
Xu Peng 已提交
1047
    }
1048 1049 1050
    return Status::OK();
}

S
starlord 已提交
1051
Status SqliteMetaImpl::CleanUpFilesWithTTL(uint16_t seconds) {
X
Xu Peng 已提交
1052
    auto now = utils::GetMicroSecTimeStamp();
S
starlord 已提交
1053 1054 1055
    std::set<std::string> table_ids;

    //remove to_delete files
1056
    try {
Y
Yu Kun 已提交
1057
        server::MetricCollector metric;
1058

1059 1060 1061
        //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 已提交
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
        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));
1072

G
groot 已提交
1073 1074 1075 1076 1077 1078 1079 1080
        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 已提交
1081
                utils::DeleteTableFilePath(options_, table_file);
1082
                ENGINE_LOG_DEBUG << "Removing file id:" << table_file.file_id_ << " location:" << table_file.location_;
G
groot 已提交
1083 1084
                ConnectorPtr->remove<TableFileSchema>(table_file.id_);

S
starlord 已提交
1085
                table_ids.insert(table_file.table_id_);
1086
            }
G
groot 已提交
1087 1088 1089 1090
            return true;
        });

        if (!commited) {
1091
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
1092 1093 1094 1095 1096 1097 1098
            return Status::DBTransactionError("Clean files error");
        }

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

S
starlord 已提交
1099
    //remove to_delete tables
G
groot 已提交
1100
    try {
Y
Yu Kun 已提交
1101
        server::MetricCollector metric;
G
groot 已提交
1102

1103 1104 1105
        //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 已提交
1106 1107 1108 1109 1110 1111
        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 已提交
1112
                utils::DeleteTablePath(options_, std::get<1>(table), false);//only delete empty folder
G
groot 已提交
1113
                ConnectorPtr->remove<TableSchema>(std::get<0>(table));
1114
            }
G
groot 已提交
1115 1116 1117 1118 1119

            return true;
        });

        if (!commited) {
1120
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
1121
            return Status::DBTransactionError("Clean files error");
X
Xu Peng 已提交
1122
        }
G
groot 已提交
1123

1124
    } catch (std::exception &e) {
G
groot 已提交
1125
        return HandleException("Encounter exception when clean table files", e);
X
Xu Peng 已提交
1126 1127
    }

S
starlord 已提交
1128 1129 1130
    //remove deleted table folder
    //don't remove table folder until all its files has been deleted
    try {
Y
Yu Kun 已提交
1131
        server::MetricCollector metric;
S
starlord 已提交
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144

        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 已提交
1145 1146 1147
    return Status::OK();
}

S
starlord 已提交
1148
Status SqliteMetaImpl::CleanUp() {
1149
    try {
Y
Yu Kun 已提交
1150
        server::MetricCollector metric;
1151 1152 1153 1154

        //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_);

1155 1156
        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)));
1157

G
groot 已提交
1158 1159 1160 1161
        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));
1162
            }
G
groot 已提交
1163 1164 1165 1166
            return true;
        });

        if (!commited) {
1167
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
1168
            return Status::DBTransactionError("Clean files error");
X
Xu Peng 已提交
1169
        }
G
groot 已提交
1170

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

    return Status::OK();
}

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

1180
    try {
Y
Yu Kun 已提交
1181
        server::MetricCollector metric;
1182

1183 1184 1185
        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 已提交
1186
                                                   and c(&TableFileSchema::table_id_) == table_id));
1187

1188
        TableSchema table_schema;
G
groot 已提交
1189
        table_schema.table_id_ = table_id;
X
Xu Peng 已提交
1190
        auto status = DescribeTable(table_schema);
1191

1192 1193 1194 1195 1196
        if (!status.ok()) {
            return status;
        }

        result = 0;
1197
        for (auto &file : selected) {
1198 1199
            result += std::get<0>(file);
        }
X
Xu Peng 已提交
1200

1201
    } catch (std::exception &e) {
G
groot 已提交
1202
        return HandleException("Encounter exception when calculate table file size", e);
X
Xu Peng 已提交
1203 1204 1205 1206
    }
    return Status::OK();
}

S
starlord 已提交
1207
Status SqliteMetaImpl::DropAll() {
X
Xu Peng 已提交
1208 1209
    if (boost::filesystem::is_directory(options_.path)) {
        boost::filesystem::remove_all(options_.path);
X
Xu Peng 已提交
1210 1211 1212 1213
    }
    return Status::OK();
}

1214
} // namespace meta
X
Xu Peng 已提交
1215
} // namespace engine
J
jinhai 已提交
1216
} // namespace milvus
X
Xu Peng 已提交
1217
} // namespace zilliz