1/**
2 * Copyright 2021 Alibaba, Inc. and its affiliates. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15
16 * \author Haichao.chc
17 * \date Oct 2020
18 * \brief Implementation of id map
19 */
20
21#include "id_map.h"
22#include "common/error_code.h"
23#include "constants.h"
24#include "file_helper.h"
25#include "typedef.h"
26
27namespace proxima {
28namespace be {
29namespace index {
30
31IDMapPtr IDMap::Create(const std::string &collection_name,
32 const std::string &collection_path) {
33 return std::make_shared<IDMap>(collection_name, collection_path);
34}
35
36int IDMap::CreateAndOpen(const std::string &collection_name,
37 const std::string &collection_path,
38 const ReadOptions &read_options, IDMapPtr *id_map) {
39 (*id_map) = Create(collection_name, collection_path);
40
41 return (*id_map)->open(read_options);
42}
43
44IDMap::~IDMap() {
45 if (opened_) {
46 this->close();
47 }
48}
49
50int IDMap::open(const ReadOptions &read_options) {
51 CHECK_STATUS(opened_, false);
52
53 int ret = Snapshot::CreateAndOpen(collection_path_, FileID::ID_FILE,
54 read_options, &snapshot_);
55 CHECK_RETURN_WITH_CLOG(ret, 0, "Create and open snapshot failed.");
56
57 ret = key_map_.mount(snapshot_->data());
58 CHECK_RETURN_WITH_CLOG(ret, 0, "Mount snapshot failed.");
59
60 opened_ = true;
61 CLOG_DEBUG("Opened id map.");
62 return 0;
63}
64
65int IDMap::flush() {
66 CHECK_STATUS(opened_, true);
67
68 return snapshot_->flush();
69}
70
71int IDMap::close() {
72 CHECK_STATUS(opened_, true);
73
74 key_map_.unmount();
75
76 // Do not break close logic
77 int ret = snapshot_->close();
78 if (ret != 0) {
79 LOG_WARN("Close snapshot failed.");
80 }
81
82 opened_ = false;
83 CLOG_DEBUG("Closed id map.");
84 return ret;
85}
86
87int IDMap::insert(uint64_t key, idx_t doc_id) {
88 CHECK_STATUS(opened_, true);
89
90 int ret = key_map_.emplace(key, doc_id);
91 CHECK_RETURN(ret, 0);
92 return 0;
93}
94
95bool IDMap::has(uint64_t key) const {
96 return key_map_.has(key);
97}
98
99idx_t IDMap::get_mapping_id(uint64_t key) const {
100 idx_t doc_id = INVALID_DOC_ID;
101 if (key_map_.has(key)) {
102 key_map_.get(key, &doc_id);
103 }
104 return doc_id;
105}
106
107void IDMap::remove(uint64_t key) {
108 if (key_map_.has(key)) {
109 key_map_.erase(key);
110 }
111}
112
113} // end namespace index
114} // namespace be
115} // end namespace proxima
116