1 /*
2  * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef DATASHARESERVICE_KV_DELEGATE_H
17 #define DATASHARESERVICE_KV_DELEGATE_H
18 
19 #include <mutex>
20 #include <string>
21 
22 #include "db_delegate.h"
23 #include "executor_pool.h"
24 #include "grd_base/grd_db_api.h"
25 
26 namespace OHOS::DataShare {
27 class KvDelegate final : public KvDBDelegate {
28 public:
29     KvDelegate(const std::string &path, const std::shared_ptr<ExecutorPool> &executors);
30     ~KvDelegate() override;
31     int32_t Upsert(const std::string &collectionName, const KvData &value) override;
32     int32_t Delete(const std::string &collectionName, const std::string &filter) override;
33     int32_t Get(const std::string &collectionName, const Id &id, std::string &value) override;
34 
35     int32_t Get(const std::string &collectionName, const std::string &filter, const std::string &projection,
36         std::string &result) override;
37     int32_t GetBatch(const std::string &collectionName, const std::string &filter, const std::string &projection,
38         std::vector<std::string> &result) override;
39     void NotifyBackup() override;
40 
41 private:
42     bool Init();
43     bool GetVersion(const std::string &collectionName, const std::string &filter, int &version);
44     int64_t Upsert(const std::string &collectionName, const std::string &filter, const std::string &value);
45     void Flush();
46     bool RestoreIfNeed(int32_t dbStatus);
47     void Backup();
48     void Restore();
49     void RemoveDbFile(bool isBackUp);
50     bool CopyFile(bool isBackup);
51     std::recursive_mutex mutex_;
52     std::string path_;
53     GRD_DB *db_ = nullptr;
54     bool isInitDone_ = false;
55     std::shared_ptr<ExecutorPool> executors_ = nullptr;
56     ExecutorPool::TaskId taskId_ = ExecutorPool::INVALID_TASK_ID;
57     bool hasChange_ = false;
58 };
59 } // namespace OHOS::DataShare
60 #endif // DATASHARESERVICE_KV_DELEGATE_H
61