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

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

X
Xu Peng 已提交
22 23

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

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

G
groot 已提交
30 31
namespace {

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

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

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

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

G
groot 已提交
55 56
}

57
inline auto StoragePrototype(const std::string &path) {
X
Xu Peng 已提交
58
    return make_storage(path,
G
groot 已提交
59
                        make_table("Tables",
G
groot 已提交
60 61
                                   make_column("id", &TableSchema::id_, primary_key()),
                                   make_column("table_id", &TableSchema::table_id_, unique()),
G
groot 已提交
62
                                   make_column("state", &TableSchema::state_),
G
groot 已提交
63 64 65 66 67
                                   make_column("dimension", &TableSchema::dimension_),
                                   make_column("created_on", &TableSchema::created_on_),
                                   make_column("files_cnt", &TableSchema::files_cnt_, default_value(0)),
                                   make_column("engine_type", &TableSchema::engine_type_),
                                   make_column("store_raw_data", &TableSchema::store_raw_data_)),
G
groot 已提交
68
                        make_table("TableFiles",
G
groot 已提交
69 70
                                   make_column("id", &TableFileSchema::id_, primary_key()),
                                   make_column("table_id", &TableFileSchema::table_id_),
G
groot 已提交
71
                                   make_column("engine_type", &TableFileSchema::engine_type_),
G
groot 已提交
72 73 74 75 76 77
                                   make_column("file_id", &TableFileSchema::file_id_),
                                   make_column("file_type", &TableFileSchema::file_type_),
                                   make_column("size", &TableFileSchema::size_, default_value(0)),
                                   make_column("updated_time", &TableFileSchema::updated_time_),
                                   make_column("created_on", &TableFileSchema::created_on_),
                                   make_column("date", &TableFileSchema::date_))
78
    );
X
Xu Peng 已提交
79 80 81

}

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

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

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

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

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

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

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

122
    CleanUp();
X
Xu Peng 已提交
123

X
Xu Peng 已提交
124
    return Status::OK();
X
Xu Peng 已提交
125 126
}

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

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

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

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

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

X
Xu Peng 已提交
165 166 167
    return Status::OK();
}

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

G
groot 已提交
170 171 172
    try {
        MetricCollector metric;

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

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

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

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

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

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

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

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

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

    return Status::OK();
}

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

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

    return Status::OK();
}

S
starlord 已提交
272
Status SqliteMetaImpl::DescribeTable(TableSchema &table_schema) {
273
    try {
G
groot 已提交
274 275
        MetricCollector metric;

G
groot 已提交
276 277 278 279 280 281
        auto groups = ConnectorPtr->select(columns(&TableSchema::id_,
                                                   &TableSchema::table_id_,
                                                   &TableSchema::files_cnt_,
                                                   &TableSchema::dimension_,
                                                   &TableSchema::engine_type_,
                                                   &TableSchema::store_raw_data_),
G
groot 已提交
282 283 284
                                           where(c(&TableSchema::table_id_) == table_schema.table_id_
                                                 and c(&TableSchema::state_) != (int)TableSchema::TO_DELETE));

285
        if (groups.size() == 1) {
G
groot 已提交
286 287 288 289 290
            table_schema.id_ = std::get<0>(groups[0]);
            table_schema.files_cnt_ = std::get<2>(groups[0]);
            table_schema.dimension_ = std::get<3>(groups[0]);
            table_schema.engine_type_ = std::get<4>(groups[0]);
            table_schema.store_raw_data_ = std::get<5>(groups[0]);
291
        } else {
G
groot 已提交
292
            return Status::NotFound("Table " + table_schema.table_id_ + " not found");
293
        }
G
groot 已提交
294

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

X
Xu Peng 已提交
299
    return Status::OK();
X
Xu Peng 已提交
300 301
}

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

        if (selected.size() >= 1) {
            has = true;
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

            int raw_count = 0, new_count = 0, new_merge_count = 0, new_index_count = 0, to_index_count = 0;
            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 已提交
348 349 350 351 352 353 354 355
        }

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

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

G
groot 已提交
359 360
    try {
        MetricCollector metric;
G
groot 已提交
361
        auto tables = ConnectorPtr->select(columns(&TableSchema::id_),
G
groot 已提交
362 363
                                           where(c(&TableSchema::table_id_) == table_id
                                           and c(&TableSchema::state_) != (int)TableSchema::TO_DELETE));
364
        if (tables.size() == 1) {
365 366 367 368
            has_or_not = true;
        } else {
            has_or_not = false;
        }
G
groot 已提交
369

370
    } catch (std::exception &e) {
G
groot 已提交
371
        return HandleException("Encounter exception when lookup table", e);
G
groot 已提交
372
    }
G
groot 已提交
373

G
groot 已提交
374 375 376
    return Status::OK();
}

S
starlord 已提交
377
Status SqliteMetaImpl::AllTables(std::vector<TableSchema>& table_schema_array) {
G
groot 已提交
378
    try {
G
groot 已提交
379 380
        MetricCollector metric;

G
groot 已提交
381 382 383 384 385
        auto selected = ConnectorPtr->select(columns(&TableSchema::id_,
                                                   &TableSchema::table_id_,
                                                   &TableSchema::files_cnt_,
                                                   &TableSchema::dimension_,
                                                   &TableSchema::engine_type_,
G
groot 已提交
386 387
                                                   &TableSchema::store_raw_data_),
                                             where(c(&TableSchema::state_) != (int)TableSchema::TO_DELETE));
G
groot 已提交
388 389 390 391 392 393 394 395 396 397 398
        for (auto &table : selected) {
            TableSchema schema;
            schema.id_ = std::get<0>(table);
            schema.table_id_ = std::get<1>(table);
            schema.files_cnt_ = std::get<2>(table);
            schema.dimension_ = std::get<3>(table);
            schema.engine_type_ = std::get<4>(table);
            schema.store_raw_data_ = std::get<5>(table);

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

G
groot 已提交
400
    } catch (std::exception &e) {
G
groot 已提交
401
        return HandleException("Encounter exception when lookup all tables", e);
X
Xu Peng 已提交
402
    }
G
groot 已提交
403

X
Xu Peng 已提交
404
    return Status::OK();
X
Xu Peng 已提交
405 406
}

S
starlord 已提交
407
Status SqliteMetaImpl::CreateTableFile(TableFileSchema &file_schema) {
G
groot 已提交
408 409
    if (file_schema.date_ == EmptyDate) {
        file_schema.date_ = Meta::GetDate();
X
Xu Peng 已提交
410
    }
411
    TableSchema table_schema;
G
groot 已提交
412
    table_schema.table_id_ = file_schema.table_id_;
X
Xu Peng 已提交
413
    auto status = DescribeTable(table_schema);
X
Xu Peng 已提交
414 415 416
    if (!status.ok()) {
        return status;
    }
417

G
groot 已提交
418 419 420 421 422 423 424 425 426 427
    try {
        MetricCollector metric;

        NextFileId(file_schema.file_id_);
        file_schema.dimension_ = table_schema.dimension_;
        file_schema.size_ = 0;
        file_schema.created_on_ = utils::GetMicroSecTimeStamp();
        file_schema.updated_time_ = file_schema.created_on_;
        file_schema.engine_type_ = table_schema.engine_type_;

428 429 430
        //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 已提交
431 432 433
        auto id = ConnectorPtr->insert(file_schema);
        file_schema.id_ = id;

S
starlord 已提交
434
        return utils::CreateTableFilePath(options_, file_schema);
435

G
groot 已提交
436 437
    } catch (std::exception& ex) {
        return HandleException("Encounter exception when create table file", ex);
438 439
    }

X
Xu Peng 已提交
440
    return Status::OK();
X
Xu Peng 已提交
441 442
}

S
starlord 已提交
443
Status SqliteMetaImpl::FilesToIndex(TableFilesSchema &files) {
X
Xu Peng 已提交
444
    files.clear();
X
Xu Peng 已提交
445

446
    try {
G
groot 已提交
447 448
        MetricCollector metric;

G
groot 已提交
449 450 451 452 453 454 455 456
        auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                     &TableFileSchema::table_id_,
                                                     &TableFileSchema::file_id_,
                                                     &TableFileSchema::file_type_,
                                                     &TableFileSchema::size_,
                                                     &TableFileSchema::date_,
                                                     &TableFileSchema::engine_type_),
                                             where(c(&TableFileSchema::file_type_)
457
                                                       == (int) TableFileSchema::TO_INDEX));
458

459
        std::map<std::string, TableSchema> groups;
X
Xu Peng 已提交
460
        TableFileSchema table_file;
461

462
        for (auto &file : selected) {
G
groot 已提交
463 464 465 466 467 468 469 470
            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);
            table_file.size_ = std::get<4>(file);
            table_file.date_ = std::get<5>(file);
            table_file.engine_type_ = std::get<6>(file);

S
starlord 已提交
471
            utils::GetTableFilePath(options_, table_file);
G
groot 已提交
472
            auto groupItr = groups.find(table_file.table_id_);
473
            if (groupItr == groups.end()) {
474
                TableSchema table_schema;
G
groot 已提交
475
                table_schema.table_id_ = table_file.table_id_;
X
Xu Peng 已提交
476
                auto status = DescribeTable(table_schema);
477 478 479
                if (!status.ok()) {
                    return status;
                }
G
groot 已提交
480
                groups[table_file.table_id_] = table_schema;
X
Xu Peng 已提交
481
            }
G
groot 已提交
482
            table_file.dimension_ = groups[table_file.table_id_].dimension_;
X
Xu Peng 已提交
483
            files.push_back(table_file);
X
Xu Peng 已提交
484
        }
G
groot 已提交
485

486
    } catch (std::exception &e) {
G
groot 已提交
487
        return HandleException("Encounter exception when iterate raw files", e);
X
Xu Peng 已提交
488
    }
X
Xu Peng 已提交
489

X
Xu Peng 已提交
490 491 492
    return Status::OK();
}

S
starlord 已提交
493
Status SqliteMetaImpl::FilesToSearch(const std::string &table_id,
494 495
                                 const DatesT &partition,
                                 DatePartionedTableFilesSchema &files) {
X
xj.lin 已提交
496
    files.clear();
X
Xu Peng 已提交
497

498
    try {
G
groot 已提交
499 500
        MetricCollector metric;

X
Xu Peng 已提交
501
        if (partition.empty()) {
G
groot 已提交
502 503 504 505 506 507 508 509 510 511
            auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                         &TableFileSchema::table_id_,
                                                         &TableFileSchema::file_id_,
                                                         &TableFileSchema::file_type_,
                                                         &TableFileSchema::size_,
                                                         &TableFileSchema::date_,
                                                         &TableFileSchema::engine_type_),
                                                 where(c(&TableFileSchema::table_id_) == table_id and
                                                     (c(&TableFileSchema::file_type_) == (int) TableFileSchema::RAW or
                                                         c(&TableFileSchema::file_type_)
X
Xu Peng 已提交
512
                                                             == (int) TableFileSchema::TO_INDEX or
G
groot 已提交
513
                                                         c(&TableFileSchema::file_type_)
X
Xu Peng 已提交
514
                                                             == (int) TableFileSchema::INDEX)));
G
groot 已提交
515

X
Xu Peng 已提交
516
            TableSchema table_schema;
G
groot 已提交
517
            table_schema.table_id_ = table_id;
X
Xu Peng 已提交
518 519 520 521
            auto status = DescribeTable(table_schema);
            if (!status.ok()) {
                return status;
            }
X
xj.lin 已提交
522

X
Xu Peng 已提交
523 524 525
            TableFileSchema table_file;

            for (auto &file : selected) {
G
groot 已提交
526 527 528 529 530 531 532 533
                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);
                table_file.size_ = std::get<4>(file);
                table_file.date_ = std::get<5>(file);
                table_file.engine_type_ = std::get<6>(file);
                table_file.dimension_ = table_schema.dimension_;
S
starlord 已提交
534
                utils::GetTableFilePath(options_, table_file);
G
groot 已提交
535
                auto dateItr = files.find(table_file.date_);
X
Xu Peng 已提交
536
                if (dateItr == files.end()) {
G
groot 已提交
537
                    files[table_file.date_] = TableFilesSchema();
X
Xu Peng 已提交
538
                }
G
groot 已提交
539
                files[table_file.date_].push_back(table_file);
X
Xu Peng 已提交
540 541 542
            }
        }
        else {
G
groot 已提交
543 544 545 546 547
            auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                         &TableFileSchema::table_id_,
                                                         &TableFileSchema::file_id_,
                                                         &TableFileSchema::file_type_,
                                                         &TableFileSchema::size_,
G
groot 已提交
548 549
                                                         &TableFileSchema::date_,
                                                         &TableFileSchema::engine_type_),
G
groot 已提交
550 551 552 553
                                                 where(c(&TableFileSchema::table_id_) == table_id and
                                                     in(&TableFileSchema::date_, partition) and
                                                     (c(&TableFileSchema::file_type_) == (int) TableFileSchema::RAW or
                                                         c(&TableFileSchema::file_type_)
X
Xu Peng 已提交
554
                                                             == (int) TableFileSchema::TO_INDEX or
G
groot 已提交
555
                                                         c(&TableFileSchema::file_type_)
X
Xu Peng 已提交
556
                                                             == (int) TableFileSchema::INDEX)));
G
groot 已提交
557

X
Xu Peng 已提交
558
            TableSchema table_schema;
G
groot 已提交
559
            table_schema.table_id_ = table_id;
X
Xu Peng 已提交
560 561 562 563
            auto status = DescribeTable(table_schema);
            if (!status.ok()) {
                return status;
            }
X
Xu Peng 已提交
564

X
Xu Peng 已提交
565 566 567
            TableFileSchema table_file;

            for (auto &file : selected) {
G
groot 已提交
568 569 570 571 572 573
                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);
                table_file.size_ = std::get<4>(file);
                table_file.date_ = std::get<5>(file);
G
groot 已提交
574
                table_file.engine_type_ = std::get<6>(file);
G
groot 已提交
575
                table_file.dimension_ = table_schema.dimension_;
S
starlord 已提交
576
                utils::GetTableFilePath(options_, table_file);
G
groot 已提交
577
                auto dateItr = files.find(table_file.date_);
X
Xu Peng 已提交
578
                if (dateItr == files.end()) {
G
groot 已提交
579
                    files[table_file.date_] = TableFilesSchema();
X
Xu Peng 已提交
580
                }
G
groot 已提交
581
                files[table_file.date_].push_back(table_file);
582
            }
X
Xu Peng 已提交
583

X
xj.lin 已提交
584
        }
585
    } catch (std::exception &e) {
G
groot 已提交
586
        return HandleException("Encounter exception when iterate index files", e);
X
xj.lin 已提交
587 588 589 590 591
    }

    return Status::OK();
}

S
starlord 已提交
592
Status SqliteMetaImpl::FilesToSearch(const std::string &table_id,
X
xj.lin 已提交
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
                                 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_,
                                      &TableFileSchema::size_,
                                      &TableFileSchema::date_,
                                      &TableFileSchema::engine_type_);

        auto match_tableid = c(&TableFileSchema::table_id_) == table_id;
        auto is_raw = c(&TableFileSchema::file_type_) == (int) TableFileSchema::RAW;
        auto is_toindex = c(&TableFileSchema::file_type_) == (int) TableFileSchema::TO_INDEX;
        auto is_index = c(&TableFileSchema::file_type_) == (int) TableFileSchema::INDEX;

        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()) {
            auto filter = where(match_tableid and (is_raw or is_toindex or is_index));
            result = ConnectorPtr->select(select_columns, filter);
        }
        else if (partition.empty() && !ids.empty()) {
            auto match_fileid = in(&TableFileSchema::id_, ids);
            auto filter = where(match_tableid and match_fileid and (is_raw or is_toindex or is_index));
            result = ConnectorPtr->select(select_columns, filter);
        }
        else if (!partition.empty() && ids.empty()) {
            auto match_date = in(&TableFileSchema::date_, partition);
            auto filter = where(match_tableid and match_date and (is_raw or is_toindex or is_index));
            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);
            auto filter = where(match_tableid and match_fileid and match_date and (is_raw or is_toindex or is_index));
            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);
            table_file.size_ = std::get<4>(file);
            table_file.date_ = std::get<5>(file);
            table_file.engine_type_ = std::get<6>(file);
            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 已提交
665
Status SqliteMetaImpl::FilesToMerge(const std::string &table_id,
666
                                DatePartionedTableFilesSchema &files) {
X
Xu Peng 已提交
667
    files.clear();
X
Xu Peng 已提交
668

669
    try {
G
groot 已提交
670 671
        MetricCollector metric;

G
groot 已提交
672 673 674 675 676 677 678
        auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                     &TableFileSchema::table_id_,
                                                     &TableFileSchema::file_id_,
                                                     &TableFileSchema::file_type_,
                                                     &TableFileSchema::size_,
                                                     &TableFileSchema::date_),
                                             where(c(&TableFileSchema::file_type_) == (int) TableFileSchema::RAW and
G
groot 已提交
679 680
                                                 c(&TableFileSchema::table_id_) == table_id),
                                             order_by(&TableFileSchema::size_).desc());
G
groot 已提交
681

682
        TableSchema table_schema;
G
groot 已提交
683
        table_schema.table_id_ = table_id;
X
Xu Peng 已提交
684
        auto status = DescribeTable(table_schema);
685

686 687 688
        if (!status.ok()) {
            return status;
        }
X
Xu Peng 已提交
689

X
Xu Peng 已提交
690
        TableFileSchema table_file;
691
        for (auto &file : selected) {
G
groot 已提交
692 693 694 695 696 697 698
            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);
            table_file.size_ = std::get<4>(file);
            table_file.date_ = std::get<5>(file);
            table_file.dimension_ = table_schema.dimension_;
S
starlord 已提交
699
            utils::GetTableFilePath(options_, table_file);
G
groot 已提交
700
            auto dateItr = files.find(table_file.date_);
701
            if (dateItr == files.end()) {
G
groot 已提交
702
                files[table_file.date_] = TableFilesSchema();
703
            }
G
groot 已提交
704
            files[table_file.date_].push_back(table_file);
X
Xu Peng 已提交
705
        }
706
    } catch (std::exception &e) {
G
groot 已提交
707
        return HandleException("Encounter exception when iterate merge files", e);
X
Xu Peng 已提交
708 709 710
    }

    return Status::OK();
X
Xu Peng 已提交
711 712
}

S
starlord 已提交
713
Status SqliteMetaImpl::GetTableFiles(const std::string& table_id,
714 715
                                 const std::vector<size_t>& ids,
                                 TableFilesSchema& table_files) {
X
Xu Peng 已提交
716
    try {
717
        table_files.clear();
Y
yu yunfeng 已提交
718 719
        auto files = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                  &TableFileSchema::file_id_,
G
groot 已提交
720 721
                                                  &TableFileSchema::file_type_,
                                                  &TableFileSchema::size_,
722 723 724 725
                                                  &TableFileSchema::date_,
                                                  &TableFileSchema::engine_type_),
                                          where(c(&TableFileSchema::table_id_) == table_id and
                                                  in(&TableFileSchema::id_, ids)
X
Xu Peng 已提交
726
                                          ));
727 728 729 730 731 732 733 734 735 736

        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 已提交
737
            file_schema.table_id_ = table_id;
Y
yu yunfeng 已提交
738 739 740 741 742 743
            file_schema.id_ = std::get<0>(file);
            file_schema.file_id_ = std::get<1>(file);
            file_schema.file_type_ = std::get<2>(file);
            file_schema.size_ = std::get<3>(file);
            file_schema.date_ = std::get<4>(file);
            file_schema.engine_type_ = std::get<5>(file);
744
            file_schema.dimension_ = table_schema.dimension_;
S
starlord 已提交
745
            utils::GetTableFilePath(options_, file_schema);
746 747

            table_files.emplace_back(file_schema);
X
Xu Peng 已提交
748 749
        }
    } catch (std::exception &e) {
750
        return HandleException("Encounter exception when lookup table files", e);
X
Xu Peng 已提交
751 752
    }

X
Xu Peng 已提交
753
    return Status::OK();
X
Xu Peng 已提交
754 755
}

X
Xu Peng 已提交
756
// PXU TODO: Support Swap
S
starlord 已提交
757
Status SqliteMetaImpl::Archive() {
758
    auto &criterias = options_.archive_conf.GetCriterias();
X
Xu Peng 已提交
759 760 761 762 763
    if (criterias.size() == 0) {
        return Status::OK();
    }

    for (auto kv : criterias) {
764 765
        auto &criteria = kv.first;
        auto &limit = kv.second;
G
groot 已提交
766
        if (criteria == engine::ARCHIVE_CONF_DAYS) {
X
Xu Peng 已提交
767
            long usecs = limit * D_SEC * US_PS;
768
            long now = utils::GetMicroSecTimeStamp();
769
            try {
770 771 772
                //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 已提交
773
                ConnectorPtr->update_all(
774
                    set(
G
groot 已提交
775
                        c(&TableFileSchema::file_type_) = (int) TableFileSchema::TO_DELETE
776 777
                    ),
                    where(
G
groot 已提交
778 779
                        c(&TableFileSchema::created_on_) < (long) (now - usecs) and
                            c(&TableFileSchema::file_type_) != (int) TableFileSchema::TO_DELETE
780 781
                    ));
            } catch (std::exception &e) {
G
groot 已提交
782
                return HandleException("Encounter exception when update table files", e);
X
Xu Peng 已提交
783 784
            }
        }
G
groot 已提交
785
        if (criteria == engine::ARCHIVE_CONF_DISK) {
G
groot 已提交
786
            uint64_t sum = 0;
X
Xu Peng 已提交
787
            Size(sum);
X
Xu Peng 已提交
788

G
groot 已提交
789
            int64_t to_delete = (int64_t)sum - limit * G;
X
Xu Peng 已提交
790
            DiscardFiles(to_delete);
X
Xu Peng 已提交
791 792 793 794 795 796
        }
    }

    return Status::OK();
}

S
starlord 已提交
797
Status SqliteMetaImpl::Size(uint64_t &result) {
X
Xu Peng 已提交
798
    result = 0;
X
Xu Peng 已提交
799
    try {
S
starlord 已提交
800 801 802 803 804 805
        auto files = ConnectorPtr->select(columns(&TableFileSchema::size_,
                                                  &TableFileSchema::file_type_,
                                                  &TableFileSchema::engine_type_),
                                          where(
                                                  c(&TableFileSchema::file_type_) != (int) TableFileSchema::TO_DELETE
                                          ));
X
Xu Peng 已提交
806

S
starlord 已提交
807 808 809 810 811 812 813 814
        for (auto &file : files) {
            auto file_size = std::get<0>(file);
            auto file_type = std::get<1>(file);
            auto engine_type = std::get<2>(file);
            if(file_type == (int)TableFileSchema::INDEX && engine_type == (int)EngineType::FAISS_IVFSQ8) {
                result += (uint64_t)file_size/4;//hardcode for sq8
            } else {
                result += (uint64_t)file_size;
X
Xu Peng 已提交
815 816
            }
        }
817
    } catch (std::exception &e) {
G
groot 已提交
818
        return HandleException("Encounter exception when calculte db size", e);
X
Xu Peng 已提交
819 820 821 822 823
    }

    return Status::OK();
}

S
starlord 已提交
824
Status SqliteMetaImpl::DiscardFiles(long to_discard_size) {
X
Xu Peng 已提交
825 826 827
    if (to_discard_size <= 0) {
        return Status::OK();
    }
G
groot 已提交
828

G
groot 已提交
829
    ENGINE_LOG_DEBUG << "About to discard size=" << to_discard_size;
G
groot 已提交
830

X
Xu Peng 已提交
831
    try {
G
groot 已提交
832 833
        MetricCollector metric;

834 835 836
        //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 已提交
837 838 839 840
        auto commited = ConnectorPtr->transaction([&]() mutable {
            auto selected = ConnectorPtr->select(columns(&TableFileSchema::id_,
                                                         &TableFileSchema::size_),
                                                 where(c(&TableFileSchema::file_type_)
841
                                                       != (int) TableFileSchema::TO_DELETE),
G
groot 已提交
842 843
                                                 order_by(&TableFileSchema::id_),
                                                 limit(10));
X
Xu Peng 已提交
844

G
groot 已提交
845 846
            std::vector<int> ids;
            TableFileSchema table_file;
847

G
groot 已提交
848 849 850 851 852 853 854 855 856
            for (auto &file : selected) {
                if (to_discard_size <= 0) break;
                table_file.id_ = std::get<0>(file);
                table_file.size_ = std::get<1>(file);
                ids.push_back(table_file.id_);
                ENGINE_LOG_DEBUG << "Discard table_file.id=" << table_file.file_id_
                                 << " table_file.size=" << table_file.size_;
                to_discard_size -= table_file.size_;
            }
857

G
groot 已提交
858 859 860
            if (ids.size() == 0) {
                return true;
            }
861

G
groot 已提交
862 863 864 865 866 867 868 869 870 871 872 873 874
            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) {
875
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
876 877
            return Status::DBTransactionError("Update table file error");
        }
X
Xu Peng 已提交
878

879
    } catch (std::exception &e) {
G
groot 已提交
880
        return HandleException("Encounter exception when discard table file", e);
X
Xu Peng 已提交
881 882
    }

X
Xu Peng 已提交
883
    return DiscardFiles(to_discard_size);
X
Xu Peng 已提交
884 885
}

S
starlord 已提交
886
Status SqliteMetaImpl::UpdateTableFile(TableFileSchema &file_schema) {
G
groot 已提交
887
    file_schema.updated_time_ = utils::GetMicroSecTimeStamp();
888
    try {
G
groot 已提交
889 890
        MetricCollector metric;

891 892 893
        //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 已提交
894 895 896 897 898 899 900 901 902
        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 已提交
903
        ConnectorPtr->update(file_schema);
G
groot 已提交
904

905
    } catch (std::exception &e) {
G
groot 已提交
906 907 908
        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 已提交
909
    }
X
Xu Peng 已提交
910
    return Status::OK();
X
Xu Peng 已提交
911 912
}

S
starlord 已提交
913
Status SqliteMetaImpl::UpdateTableFilesToIndex(const std::string& table_id) {
P
peng.xu 已提交
914
    try {
915 916 917 918 919
        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 已提交
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
        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 已提交
935
Status SqliteMetaImpl::UpdateTableFiles(TableFilesSchema &files) {
936
    try {
G
groot 已提交
937 938
        MetricCollector metric;

939 940 941
        //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 已提交
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
        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;
            }
        }

957 958
        auto commited = ConnectorPtr->transaction([&]() mutable {
            for (auto &file : files) {
G
groot 已提交
959 960 961 962
                if(!has_tables[file.table_id_]) {
                    file.file_type_ = TableFileSchema::TO_DELETE;
                }

G
groot 已提交
963
                file.updated_time_ = utils::GetMicroSecTimeStamp();
964 965 966 967
                ConnectorPtr->update(file);
            }
            return true;
        });
G
groot 已提交
968

969
        if (!commited) {
970
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
971
            return Status::DBTransactionError("Update table files error");
X
Xu Peng 已提交
972
        }
G
groot 已提交
973

974
    } catch (std::exception &e) {
G
groot 已提交
975
        return HandleException("Encounter exception when update table files", e);
X
Xu Peng 已提交
976
    }
977 978 979
    return Status::OK();
}

S
starlord 已提交
980
Status SqliteMetaImpl::CleanUpFilesWithTTL(uint16_t seconds) {
X
Xu Peng 已提交
981
    auto now = utils::GetMicroSecTimeStamp();
982
    try {
G
groot 已提交
983
        MetricCollector metric;
984

985 986 987
        //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 已提交
988 989 990 991 992 993 994 995 996 997
        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));
998

G
groot 已提交
999 1000 1001 1002 1003 1004 1005 1006
        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 已提交
1007
                utils::DeleteTableFilePath(options_, table_file);
1008
                ENGINE_LOG_DEBUG << "Removing file id:" << table_file.file_id_ << " location:" << table_file.location_;
G
groot 已提交
1009 1010
                ConnectorPtr->remove<TableFileSchema>(table_file.id_);

1011
            }
G
groot 已提交
1012 1013 1014 1015
            return true;
        });

        if (!commited) {
1016
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
            return Status::DBTransactionError("Clean files error");
        }

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

    try {
        MetricCollector metric;

1027 1028 1029
        //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 已提交
1030 1031 1032 1033 1034 1035
        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 已提交
1036
                utils::DeleteTablePath(options_, std::get<1>(table));
G
groot 已提交
1037
                ConnectorPtr->remove<TableSchema>(std::get<0>(table));
1038
            }
G
groot 已提交
1039 1040 1041 1042 1043

            return true;
        });

        if (!commited) {
1044
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
1045
            return Status::DBTransactionError("Clean files error");
X
Xu Peng 已提交
1046
        }
G
groot 已提交
1047

1048
    } catch (std::exception &e) {
G
groot 已提交
1049
        return HandleException("Encounter exception when clean table files", e);
X
Xu Peng 已提交
1050 1051 1052 1053 1054
    }

    return Status::OK();
}

S
starlord 已提交
1055
Status SqliteMetaImpl::CleanUp() {
1056
    try {
1057 1058 1059 1060 1061
        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_);

G
groot 已提交
1062
        auto files = ConnectorPtr->select(columns(&TableFileSchema::id_),
1063 1064 1065 1066 1067
                                             where(c(&TableFileSchema::file_type_) == (int) TableFileSchema::NEW
                                                   or
                                                   c(&TableFileSchema::file_type_) == (int) TableFileSchema::NEW_INDEX
                                                   or
                                                   c(&TableFileSchema::file_type_) == (int) TableFileSchema::NEW_MERGE));
1068

G
groot 已提交
1069 1070 1071 1072
        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));
1073
            }
G
groot 已提交
1074 1075 1076 1077
            return true;
        });

        if (!commited) {
1078
            ENGINE_LOG_ERROR << "sqlite transaction failed";
G
groot 已提交
1079
            return Status::DBTransactionError("Clean files error");
X
Xu Peng 已提交
1080
        }
G
groot 已提交
1081

1082
    } catch (std::exception &e) {
G
groot 已提交
1083
        return HandleException("Encounter exception when clean table file", e);
X
Xu Peng 已提交
1084 1085 1086 1087 1088
    }

    return Status::OK();
}

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

1091
    try {
G
groot 已提交
1092
        MetricCollector metric;
1093

G
groot 已提交
1094 1095 1096 1097 1098 1099
        auto selected = ConnectorPtr->select(columns(&TableFileSchema::size_),
                                             where((c(&TableFileSchema::file_type_) == (int) TableFileSchema::RAW
                                                    or
                                                    c(&TableFileSchema::file_type_) == (int) TableFileSchema::TO_INDEX
                                                    or c(&TableFileSchema::file_type_) == (int) TableFileSchema::INDEX)
                                                   and c(&TableFileSchema::table_id_) == table_id));
1100

1101
        TableSchema table_schema;
G
groot 已提交
1102
        table_schema.table_id_ = table_id;
X
Xu Peng 已提交
1103
        auto status = DescribeTable(table_schema);
1104

1105 1106 1107 1108 1109
        if (!status.ok()) {
            return status;
        }

        result = 0;
1110
        for (auto &file : selected) {
1111 1112
            result += std::get<0>(file);
        }
X
Xu Peng 已提交
1113

G
groot 已提交
1114
        result /= table_schema.dimension_;
G
groot 已提交
1115
        result /= sizeof(float);
X
Xu Peng 已提交
1116

1117
    } catch (std::exception &e) {
G
groot 已提交
1118
        return HandleException("Encounter exception when calculate table file size", e);
X
Xu Peng 已提交
1119 1120 1121 1122
    }
    return Status::OK();
}

S
starlord 已提交
1123
Status SqliteMetaImpl::DropAll() {
X
Xu Peng 已提交
1124 1125
    if (boost::filesystem::is_directory(options_.path)) {
        boost::filesystem::remove_all(options_.path);
X
Xu Peng 已提交
1126 1127 1128 1129
    }
    return Status::OK();
}

S
starlord 已提交
1130
SqliteMetaImpl::~SqliteMetaImpl() {
1131
    CleanUp();
X
Xu Peng 已提交
1132 1133
}

1134
} // namespace meta
X
Xu Peng 已提交
1135
} // namespace engine
J
jinhai 已提交
1136
} // namespace milvus
X
Xu Peng 已提交
1137
} // namespace zilliz