1 /*
2  * Copyright (c) 2023 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 RD_SINGLE_VER_NATURAL_STORE_CONNECTION_H
17 #define RD_SINGLE_VER_NATURAL_STORE_CONNECTION_H
18 #include <atomic>
19 
20 #include "db_common.h"
21 #include "db_types.h"
22 #include "rd_single_ver_natural_store.h"
23 #include "rd_single_ver_storage_executor.h"
24 #include "runtime_context.h"
25 #include "sync_able_kvdb_connection.h"
26 #include "single_ver_natural_store_connection.h"
27 
28 namespace DistributedDB {
29 class SQLiteSingleVerNaturalStore;
30 
31 class RdSingleVerNaturalStoreConnection : public SingleVerNaturalStoreConnection {
32 public:
33     explicit RdSingleVerNaturalStoreConnection(RdSingleVerNaturalStore *kvDB);
34     ~RdSingleVerNaturalStoreConnection() override;
35 
36     // Delete the copy and assign constructors
37     DISABLE_COPY_ASSIGN_MOVE(RdSingleVerNaturalStoreConnection);
38 
39     // Get the value from the database
40     int Get(const IOption &option, const Key &key, Value &value) const override;
41 
42     // Clear all the data from the database
43     int Clear(const IOption &option) override;
44 
45     // Get all the data from the database
46     int GetEntries(const IOption &option, const Key &keyPrefix, std::vector<Entry> &entries) const override;
47 
48     int GetEntries(const IOption &option, const Query &query, std::vector<Entry> &entries) const override;
49 
50     int GetCount(const IOption &option, const Query &query, int &count) const override;
51 
52     // Get the snapshot
53     int GetSnapshot(IKvDBSnapshot *&snapshot) const override;
54 
55     // Release the created snapshot
56     void ReleaseSnapshot(IKvDBSnapshot *&snapshot) override;
57 
58     // Start the transaction
59     int StartTransaction() override;
60 
61     // Commit the transaction
62     int Commit() override;
63 
64     // Roll back the transaction
65     int RollBack() override;
66 
67     // Check if the transaction already started manually
68     bool IsTransactionStarted() const override;
69 
70     // Pragma interface.
71     int Pragma(int cmd, void *parameter) override;
72 
73     // Parse event types(from observer mode).
74     int TranslateObserverModeToEventTypes(unsigned mode, std::list<int> &eventTypes) const override;
75 
76     int Rekey(const CipherPassword &passwd) override;
77 
78     int Export(const std::string &filePath, const CipherPassword &passwd) override;
79 
80     int Import(const std::string &filePath, const CipherPassword &passwd) override;
81 
82     // Get the result set
83     int GetResultSet(const IOption &option, const Key &keyPrefix, IKvDBResultSet *&resultSet) const override;
84 
85     int GetResultSet(const IOption &option, const Query &query, IKvDBResultSet *&resultSet) const override;
86 
87     // Release the result set
88     void ReleaseResultSet(IKvDBResultSet *&resultSet) override;
89 
90     int RegisterLifeCycleCallback(const DatabaseLifeCycleNotifier &notifier) override;
91 
92     // Called when Close and delete the connection.
93     int PreClose() override;
94 
95     int CheckIntegrity() const override;
96 
97     int GetKeys(const IOption &option, const Key &keyPrefix, std::vector<Key> &keys) const override;
98 
99     int UpdateKey(const UpdateKeyCallback &callback) override;
100 
101     int GetSyncDataSize(const std::string &device, size_t &size) const override;
102 
103     int Sync(const CloudSyncOption &option, const SyncProcessCallback &onProcess) override;
104 
105     int SetCloudDB(const std::map<std::string, std::shared_ptr<ICloudDb>> &cloudDBs) override;
106 
107     void SetGenCloudVersionCallback(const GenerateCloudVersionCallback &callback) override;
108 
109 private:
110     int CheckRdMonoStatus(OperatePerm perm);
111 
112     int GetEntriesInner(bool isGetValue, const IOption &option,
113         const Key &keyPrefix, std::vector<Entry> &entries) const;
114 
115     int GetEntriesInner(const IOption &option, const Query &query,
116         std::vector<Entry> &entries) const;
117 
118     static int CheckOption(const IOption &option, SingleVerDataType &type);
119     int ForceCheckPoint() const;
120     mutable std::mutex kvDbResultSetsMutex_;
121     mutable std::set<IKvDBResultSet *> kvDbResultSets_;
122 
123     // ResultSet Related Info
124     static constexpr std::size_t MAX_RESULTSET_SIZE = 8; // Max 8 ResultSet At The Same Time
125 
126     int CheckSyncEntriesValid(const std::vector<Entry> &entries) const override;
127 
128     int PutBatchInner(const IOption &option, const std::vector<Entry> &entries) override;
129 
130     int SaveSyncEntries(const std::vector<Entry> &entries, bool isDelete);
131 
132     // This func currently only be called in local procedure to change sync_data table, do not use in sync procedure.
133     // It will check and amend value when need if it is a schema database. return error if some value disagree with the
134     // schema. But in sync procedure, we just neglect the value that disagree with schema.
135     int SaveEntry(const Entry &entry, bool isDelete, Timestamp timestamp = 0);
136 
137     int SaveEntryNormally(const Entry &entry, bool isDelete);
138 
139     RdSingleVerStorageExecutor *GetExecutor(bool isWrite, int &errCode) const;
140 
141     void ReleaseExecutor(RdSingleVerStorageExecutor *&executor) const;
142 
143     void ReleaseCommitData(SingleVerNaturalStoreCommitNotifyData *&committedData);
144 
145     int StartTransactionInner(TransactType transType = TransactType::DEFERRED);
146 
147     int StartTransactionNormally(TransactType transType = TransactType::DEFERRED);
148 
149     int CommitInner();
150 
151     int RollbackInner();
152 
153     void CommitAndReleaseNotifyData(SingleVerNaturalStoreCommitNotifyData *&committedData,
154         bool isNeedCommit, int eventType);
155 
156     int CheckReadDataControlled() const;
157 
158     int CheckSyncKeysValid(const std::vector<Key> &keys) const override;
159 
160     int DeleteBatchInner(const IOption &option, const std::vector<Key> &keys) override;
161 
162     int DeleteSyncEntries(const std::vector<Key> &keys);
163 
IsSinglePutOrDelete(const std::vector<Entry> & entries)164     bool IsSinglePutOrDelete(const std::vector<Entry> &entries)
165     {
166         return entries.size() == 1;
167     }
168 
169     SingleVerNaturalStoreCommitNotifyData *committedData_; // used for transaction
170 
171     mutable std::mutex transactionMutex_;
172     std::mutex importMutex_;
173     RdSingleVerStorageExecutor *writeHandle_; // only existed while in transaction.
174 };
175 }
176 #endif