• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #define LOG_TAG "RdbCloud"
17 #include "rdb_cloud.h"
18 
19 #include "cloud/schema_meta.h"
20 #include "log_print.h"
21 #include "rdb_query.h"
22 #include "relational_store_manager.h"
23 #include "value_proxy.h"
24 #include "utils/anonymous.h"
25 
26 namespace OHOS::DistributedRdb {
27 using namespace DistributedDB;
28 using namespace DistributedData;
RdbCloud(std::shared_ptr<DistributedData::CloudDB> cloudDB,BindAssets * bindAssets)29 RdbCloud::RdbCloud(std::shared_ptr<DistributedData::CloudDB> cloudDB, BindAssets* bindAssets)
30     : cloudDB_(std::move(cloudDB)), snapshots_(bindAssets)
31 {
32 }
33 
BatchInsert(const std::string & tableName,std::vector<DBVBucket> && record,std::vector<DBVBucket> & extend)34 DBStatus RdbCloud::BatchInsert(
35     const std::string &tableName, std::vector<DBVBucket> &&record, std::vector<DBVBucket> &extend)
36 {
37     extend.resize(record.size());
38     VBuckets extends = ValueProxy::Convert(std::move(extend));
39     VBuckets records = ValueProxy::Convert(std::move(record));
40     std::set<std::string> skipAssets;
41     PostEvent(records, skipAssets, extends, DistributedData::AssetEvent::UPLOAD);
42     VBuckets temp = records;
43     auto error = cloudDB_->BatchInsert(tableName, std::move(records), extends);
44     PostEvent(temp, skipAssets, extends, DistributedData::AssetEvent::UPLOAD_FINISHED);
45     extend = ValueProxy::Convert(std::move(extends));
46     return ConvertStatus(static_cast<GeneralError>(error));
47 }
48 
BatchUpdate(const std::string & tableName,std::vector<DBVBucket> && record,std::vector<DBVBucket> & extend)49 DBStatus RdbCloud::BatchUpdate(
50     const std::string &tableName, std::vector<DBVBucket> &&record, std::vector<DBVBucket> &extend)
51 {
52     extend.resize(record.size());
53     VBuckets extends = ValueProxy::Convert(std::move(extend));
54     VBuckets records = ValueProxy::Convert(std::move(record));
55     std::set<std::string> skipAssets;
56     PostEvent(records, skipAssets, extends, DistributedData::AssetEvent::UPLOAD);
57     VBuckets temp = records;
58     auto error = cloudDB_->BatchUpdate(tableName, std::move(records), extends);
59     PostEvent(temp, skipAssets, extends, DistributedData::AssetEvent::UPLOAD_FINISHED);
60     extend = ValueProxy::Convert(std::move(extends));
61     return ConvertStatus(static_cast<GeneralError>(error));
62 }
63 
BatchDelete(const std::string & tableName,std::vector<DBVBucket> & extend)64 DBStatus RdbCloud::BatchDelete(const std::string &tableName, std::vector<DBVBucket> &extend)
65 {
66     auto error = cloudDB_->BatchDelete(tableName, ValueProxy::Convert(std::move(extend)));
67     return ConvertStatus(static_cast<GeneralError>(error));
68 }
69 
Query(const std::string & tableName,DBVBucket & extend,std::vector<DBVBucket> & data)70 DBStatus RdbCloud::Query(const std::string &tableName, DBVBucket &extend, std::vector<DBVBucket> &data)
71 {
72     auto [nodes, status] = ConvertQuery(extend);
73     std::shared_ptr<Cursor> cursor = nullptr;
74     if (status == GeneralError::E_OK && !nodes.empty()) {
75         RdbQuery query;
76         query.SetQueryNodes(tableName, std::move(nodes));
77         cursor = cloudDB_->Query(query, ValueProxy::Convert(std::move(extend)));
78     } else {
79         cursor = cloudDB_->Query(tableName, ValueProxy::Convert(std::move(extend)));
80     }
81     if (cursor == nullptr) {
82         ZLOGE("cursor is null, table:%{public}s, extend:%{public}zu",
83             Anonymous::Change(tableName).c_str(), extend.size());
84         return ConvertStatus(static_cast<GeneralError>(E_ERROR));
85     }
86     int32_t count = cursor->GetCount();
87     data.reserve(count);
88     auto err = cursor->MoveToFirst();
89     while (err == E_OK && count > 0) {
90         DistributedData::VBucket entry;
91         err = cursor->GetEntry(entry);
92         if (err != E_OK) {
93             break;
94         }
95         data.emplace_back(ValueProxy::Convert(std::move(entry)));
96         err = cursor->MoveToNext();
97         count--;
98     }
99     DistributedData::Value cursorFlag;
100     cursor->Get(SchemaMeta::CURSOR_FIELD, cursorFlag);
101     extend[SchemaMeta::CURSOR_FIELD] = ValueProxy::Convert(std::move(cursorFlag));
102     if (cursor->IsEnd()) {
103         ZLOGD("query end, table:%{public}s", Anonymous::Change(tableName).c_str());
104         return DBStatus::QUERY_END;
105     }
106     return ConvertStatus(static_cast<GeneralError>(err));
107 }
108 
PreSharing(const std::string & tableName,VBuckets & extend)109 DistributedData::GeneralError RdbCloud::PreSharing(const std::string& tableName, VBuckets& extend)
110 {
111     return static_cast<GeneralError>(cloudDB_->PreSharing(tableName, extend));
112 }
113 
Lock()114 std::pair<DBStatus, uint32_t> RdbCloud::Lock()
115 {
116     auto error = cloudDB_->Lock();
117     return std::make_pair(  // int64_t <-> uint32_t, s <-> ms
118         ConvertStatus(static_cast<GeneralError>(error)), cloudDB_->AliveTime() * TO_MS);
119 }
120 
UnLock()121 DBStatus RdbCloud::UnLock()
122 {
123     auto error = cloudDB_->Unlock();
124     return ConvertStatus(static_cast<GeneralError>(error));
125 }
126 
HeartBeat()127 DBStatus RdbCloud::HeartBeat()
128 {
129     auto error = cloudDB_->Heartbeat();
130     return ConvertStatus(static_cast<GeneralError>(error));
131 }
132 
Close()133 DBStatus RdbCloud::Close()
134 {
135     auto error = cloudDB_->Close();
136     return ConvertStatus(static_cast<GeneralError>(error));
137 }
138 
GetEmptyCursor(const std::string & tableName)139 std::pair<DBStatus, std::string> RdbCloud::GetEmptyCursor(const std::string &tableName)
140 {
141     auto [error, cursor] = cloudDB_->GetEmptyCursor(tableName);
142     return { ConvertStatus(static_cast<GeneralError>(error)), cursor };
143 }
144 
ConvertStatus(DistributedData::GeneralError error)145 DBStatus RdbCloud::ConvertStatus(DistributedData::GeneralError error)
146 {
147     switch (error) {
148         case GeneralError::E_OK:
149             return DBStatus::OK;
150         case GeneralError::E_NETWORK_ERROR:
151             return DBStatus::CLOUD_NETWORK_ERROR;
152         case GeneralError::E_LOCKED_BY_OTHERS:
153             return DBStatus::CLOUD_LOCK_ERROR;
154         case GeneralError::E_RECODE_LIMIT_EXCEEDED:
155             return DBStatus::CLOUD_FULL_RECORDS;
156         case GeneralError::E_NO_SPACE_FOR_ASSET:
157             return DBStatus::CLOUD_ASSET_SPACE_INSUFFICIENT;
158         case GeneralError::E_RECORD_EXIST_CONFLICT:
159             return DBStatus::CLOUD_RECORD_EXIST_CONFLICT;
160         default:
161             ZLOGI("error:0x%{public}x", error);
162             break;
163     }
164     return DBStatus::CLOUD_ERROR;
165 }
166 
ConvertQuery(RdbCloud::DBVBucket & extend)167 std::pair<RdbCloud::QueryNodes, DistributedData::GeneralError> RdbCloud::ConvertQuery(RdbCloud::DBVBucket& extend)
168 {
169     auto it = extend.find(TYPE_FIELD);
170     if (it == extend.end() || std::get<int64_t>(it->second) != static_cast<int64_t>(CloudQueryType::QUERY_FIELD)) {
171         return { {}, GeneralError::E_ERROR };
172     }
173     it = extend.find(QUERY_FIELD);
174     if (it == extend.end()) {
175         ZLOGE("error, no QUERY_FIELD!");
176         return { {}, GeneralError::E_ERROR };
177     }
178 
179     auto bytes = std::get_if<DistributedDB::Bytes>(&it->second);
180     std::vector<DistributedDB::QueryNode> nodes;
181     DBStatus status = DB_ERROR;
182     if (bytes != nullptr) {
183         nodes = DistributedDB::RelationalStoreManager::ParserQueryNodes(*bytes, status);
184     }
185     if (status != OK) {
186         ZLOGE("error, ParserQueryNodes failed, status:%{public}d", status);
187         return { {}, GeneralError::E_ERROR };
188     }
189     return { ConvertQuery(std::move(nodes)), GeneralError::E_OK };
190 }
191 
ConvertQuery(RdbCloud::DBQueryNodes && nodes)192 RdbCloud::QueryNodes RdbCloud::ConvertQuery(RdbCloud::DBQueryNodes&& nodes)
193 {
194     QueryNodes queryNodes;
195     queryNodes.reserve(nodes.size());
196     for (auto& node : nodes) {
197         QueryNode queryNode;
198         queryNode.fieldName = std::move(node.fieldName);
199         queryNode.fieldValue = ValueProxy::Convert(std::move(node.fieldValue));
200         switch (node.type) {
201             case QueryNodeType::IN:
202                 queryNode.op = QueryOperation::IN;
203                 break;
204             case QueryNodeType::OR:
205                 queryNode.op = QueryOperation::OR;
206                 break;
207             case QueryNodeType::AND:
208                 queryNode.op = QueryOperation::AND;
209                 break;
210             case QueryNodeType::EQUAL_TO:
211                 queryNode.op = QueryOperation::EQUAL_TO;
212                 break;
213             case QueryNodeType::BEGIN_GROUP:
214                 queryNode.op = QueryOperation::BEGIN_GROUP;
215                 break;
216             case QueryNodeType::END_GROUP:
217                 queryNode.op = QueryOperation::END_GROUP;
218                 break;
219             default:
220                 ZLOGE("invalid operation:0x%{public}d", node.type);
221                 return {};
222         }
223         queryNodes.emplace_back(std::move(queryNode));
224     }
225     return queryNodes;
226 }
227 
PostEvent(VBuckets & records,std::set<std::string> & skipAssets,VBuckets & extend,DistributedData::AssetEvent eventId)228 void RdbCloud::PostEvent(VBuckets& records, std::set<std::string>& skipAssets, VBuckets& extend,
229     DistributedData::AssetEvent eventId)
230 {
231     int32_t index = 0;
232     for (auto& record : records) {
233         DataBucket& ext = extend[index++];
234         for (auto& [key, value] : record) {
235             PostEvent(value, ext, skipAssets, eventId);
236         }
237     }
238 }
239 
PostEvent(DistributedData::Value & value,DataBucket & extend,std::set<std::string> & skipAssets,DistributedData::AssetEvent eventId)240 void RdbCloud::PostEvent(DistributedData::Value& value, DataBucket& extend, std::set<std::string>& skipAssets,
241     DistributedData::AssetEvent eventId)
242 {
243     if (value.index() != TYPE_INDEX<DistributedData::Asset> && value.index() != TYPE_INDEX<DistributedData::Assets>) {
244         return;
245     }
246 
247     if (value.index() == TYPE_INDEX<DistributedData::Asset>) {
248         auto* asset = Traits::get_if<DistributedData::Asset>(&value);
249         PostEventAsset(*asset, extend, skipAssets, eventId);
250     }
251 
252     if (value.index() == TYPE_INDEX<DistributedData::Assets>) {
253         auto* assets = Traits::get_if<DistributedData::Assets>(&value);
254         for (auto& asset : *assets) {
255             PostEventAsset(asset, extend, skipAssets, eventId);
256         }
257     }
258 }
259 
PostEventAsset(DistributedData::Asset & asset,DataBucket & extend,std::set<std::string> & skipAssets,DistributedData::AssetEvent eventId)260 void RdbCloud::PostEventAsset(DistributedData::Asset& asset, DataBucket& extend, std::set<std::string>& skipAssets,
261     DistributedData::AssetEvent eventId)
262 {
263     if (snapshots_->bindAssets == nullptr) {
264         return;
265     }
266     auto it = snapshots_->bindAssets->find(asset.uri);
267     if (it == snapshots_->bindAssets->end() || it->second == nullptr) {
268         return;
269     }
270 
271     if (eventId == DistributedData::UPLOAD) {
272         it->second->Upload(asset);
273         if (it->second->GetAssetStatus(asset) == TransferStatus::STATUS_WAIT_UPLOAD) {
274             skipAssets.insert(asset.uri);
275             extend[SchemaMeta::ERROR_FIELD] = DBStatus::CLOUD_RECORD_EXIST_CONFLICT;
276         }
277     }
278 
279     if (eventId == DistributedData::UPLOAD_FINISHED) {
280         auto skip = skipAssets.find(asset.uri);
281         if (skip != skipAssets.end()) {
282             return;
283         }
284         it->second->Uploaded(asset);
285     }
286 }
287 } // namespace OHOS::DistributedRdb
288