1 /*
2  * Copyright (c) 2021 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 #include "kv_store_nb_delegate_impl.h"
17 
18 #include <functional>
19 #include <string>
20 
21 #include "db_common.h"
22 #include "db_constant.h"
23 #include "db_errno.h"
24 #include "db_types.h"
25 #include "kv_store_changed_data_impl.h"
26 #include "kv_store_errno.h"
27 #include "kv_store_nb_conflict_data_impl.h"
28 #include "kv_store_observer.h"
29 #include "kv_store_result_set_impl.h"
30 #include "kvdb_manager.h"
31 #include "kvdb_pragma.h"
32 #include "log_print.h"
33 #include "param_check_utils.h"
34 #include "performance_analysis.h"
35 #include "platform_specific.h"
36 #include "store_types.h"
37 #include "sync_operation.h"
38 
39 namespace DistributedDB {
40 namespace {
41     struct PragmaCmdPair {
42         int externCmd = 0;
43         int innerCmd = 0;
44     };
45 
46     const PragmaCmdPair g_pragmaMap[] = {
47         {GET_DEVICE_IDENTIFIER_OF_ENTRY, PRAGMA_GET_DEVICE_IDENTIFIER_OF_ENTRY},
48         {AUTO_SYNC, PRAGMA_AUTO_SYNC},
49         {PERFORMANCE_ANALYSIS_GET_REPORT, PRAGMA_PERFORMANCE_ANALYSIS_GET_REPORT},
50         {PERFORMANCE_ANALYSIS_OPEN, PRAGMA_PERFORMANCE_ANALYSIS_OPEN},
51         {PERFORMANCE_ANALYSIS_CLOSE, PRAGMA_PERFORMANCE_ANALYSIS_CLOSE},
52         {PERFORMANCE_ANALYSIS_SET_REPORTFILENAME, PRAGMA_PERFORMANCE_ANALYSIS_SET_REPORTFILENAME},
53         {GET_IDENTIFIER_OF_DEVICE, PRAGMA_GET_IDENTIFIER_OF_DEVICE},
54         {GET_QUEUED_SYNC_SIZE, PRAGMA_GET_QUEUED_SYNC_SIZE},
55         {SET_QUEUED_SYNC_LIMIT, PRAGMA_SET_QUEUED_SYNC_LIMIT},
56         {GET_QUEUED_SYNC_LIMIT, PRAGMA_GET_QUEUED_SYNC_LIMIT},
57         {SET_WIPE_POLICY, PRAGMA_SET_WIPE_POLICY},
58         {RESULT_SET_CACHE_MODE, PRAGMA_RESULT_SET_CACHE_MODE},
59         {RESULT_SET_CACHE_MAX_SIZE, PRAGMA_RESULT_SET_CACHE_MAX_SIZE},
60         {SET_SYNC_RETRY, PRAGMA_SET_SYNC_RETRY},
61         {SET_MAX_LOG_LIMIT, PRAGMA_SET_MAX_LOG_LIMIT},
62         {EXEC_CHECKPOINT, PRAGMA_EXEC_CHECKPOINT},
63     };
64 
65     constexpr const char *INVALID_CONNECTION = "[KvStoreNbDelegate] Invalid connection for operation";
66 }
67 
KvStoreNbDelegateImpl(IKvDBConnection * conn,const std::string & storeId)68 KvStoreNbDelegateImpl::KvStoreNbDelegateImpl(IKvDBConnection *conn, const std::string &storeId)
69     : conn_(conn),
70       storeId_(storeId),
71       releaseFlag_(false)
72 {}
73 
~KvStoreNbDelegateImpl()74 KvStoreNbDelegateImpl::~KvStoreNbDelegateImpl()
75 {
76     if (!releaseFlag_) {
77         LOGF("[KvStoreNbDelegate] Can't release directly");
78         return;
79     }
80 
81     conn_ = nullptr;
82 }
83 
Get(const Key & key,Value & value) const84 DBStatus KvStoreNbDelegateImpl::Get(const Key &key, Value &value) const
85 {
86     IOption option;
87     option.dataType = IOption::SYNC_DATA;
88     return GetInner(option, key, value);
89 }
90 
GetEntries(const Key & keyPrefix,std::vector<Entry> & entries) const91 DBStatus KvStoreNbDelegateImpl::GetEntries(const Key &keyPrefix, std::vector<Entry> &entries) const
92 {
93     IOption option;
94     option.dataType = IOption::SYNC_DATA;
95     return GetEntriesInner(option, keyPrefix, entries);
96 }
97 
GetEntries(const Key & keyPrefix,KvStoreResultSet * & resultSet) const98 DBStatus KvStoreNbDelegateImpl::GetEntries(const Key &keyPrefix, KvStoreResultSet *&resultSet) const
99 {
100     if (conn_ == nullptr) {
101         LOGE("%s", INVALID_CONNECTION);
102         return DB_ERROR;
103     }
104 
105     IOption option;
106     option.dataType = IOption::SYNC_DATA;
107     IKvDBResultSet *kvDbResultSet = nullptr;
108     int errCode = conn_->GetResultSet(option, keyPrefix, kvDbResultSet);
109     if (errCode == E_OK) {
110         resultSet = new (std::nothrow) KvStoreResultSetImpl(kvDbResultSet);
111         if (resultSet != nullptr) {
112             return OK;
113         }
114 
115         LOGE("[KvStoreNbDelegate] Alloc result set failed.");
116         conn_->ReleaseResultSet(kvDbResultSet);
117         kvDbResultSet = nullptr;
118         return DB_ERROR;
119     }
120 
121     LOGE("[KvStoreNbDelegate] Get result set failed: %d", errCode);
122     return TransferDBErrno(errCode);
123 }
124 
GetEntries(const Query & query,std::vector<Entry> & entries) const125 DBStatus KvStoreNbDelegateImpl::GetEntries(const Query &query, std::vector<Entry> &entries) const
126 {
127     IOption option;
128     option.dataType = IOption::SYNC_DATA;
129     if (conn_ != nullptr) {
130         int errCode = conn_->GetEntries(option, query, entries);
131         if (errCode == E_OK) {
132             return OK;
133         } else if (errCode == -E_NOT_FOUND) {
134             LOGD("[KvStoreNbDelegate] Not found the data by query");
135             return NOT_FOUND;
136         }
137 
138         LOGE("[KvStoreNbDelegate] Get the batch data by query err:%d", errCode);
139         return TransferDBErrno(errCode);
140     }
141 
142     LOGE("%s", INVALID_CONNECTION);
143     return DB_ERROR;
144 }
145 
GetEntries(const Query & query,KvStoreResultSet * & resultSet) const146 DBStatus KvStoreNbDelegateImpl::GetEntries(const Query &query, KvStoreResultSet *&resultSet) const
147 {
148     if (conn_ == nullptr) {
149         LOGE("%s", INVALID_CONNECTION);
150         return DB_ERROR;
151     }
152 
153     IOption option;
154     option.dataType = IOption::SYNC_DATA;
155     IKvDBResultSet *kvDbResultSet = nullptr;
156     int errCode = conn_->GetResultSet(option, query, kvDbResultSet);
157     if (errCode == E_OK) {
158         resultSet = new (std::nothrow) KvStoreResultSetImpl(kvDbResultSet);
159         if (resultSet != nullptr) {
160             return OK;
161         }
162 
163         LOGE("[KvStoreNbDelegate] Alloc result set failed.");
164         conn_->ReleaseResultSet(kvDbResultSet);
165         kvDbResultSet = nullptr;
166         return DB_ERROR;
167     }
168 
169     LOGE("[KvStoreNbDelegate] Get result set for query failed: %d", errCode);
170     return TransferDBErrno(errCode);
171 }
172 
GetCount(const Query & query,int & count) const173 DBStatus KvStoreNbDelegateImpl::GetCount(const Query &query, int &count) const
174 {
175     if (conn_ == nullptr) {
176         LOGE("%s", INVALID_CONNECTION);
177         return DB_ERROR;
178     }
179 
180     IOption option;
181     option.dataType = IOption::SYNC_DATA;
182     int errCode = conn_->GetCount(option, query, count);
183     if (errCode == E_OK) {
184         if (count == 0) {
185             return NOT_FOUND;
186         }
187         return OK;
188     }
189 
190     LOGE("[KvStoreNbDelegate] Get count for query failed: %d", errCode);
191     return TransferDBErrno(errCode);
192 }
193 
CloseResultSet(KvStoreResultSet * & resultSet)194 DBStatus KvStoreNbDelegateImpl::CloseResultSet(KvStoreResultSet *&resultSet)
195 {
196     if (resultSet == nullptr) {
197         return INVALID_ARGS;
198     }
199 
200     if (conn_ == nullptr) {
201         LOGE("%s", INVALID_CONNECTION);
202         return DB_ERROR;
203     }
204 
205     // release inner result set
206     IKvDBResultSet *kvDbResultSet = nullptr;
207     (static_cast<KvStoreResultSetImpl *>(resultSet))->GetResultSet(kvDbResultSet);
208     conn_->ReleaseResultSet(kvDbResultSet);
209     // release external result set
210     delete resultSet;
211     resultSet = nullptr;
212     return OK;
213 }
214 
Put(const Key & key,const Value & value)215 DBStatus KvStoreNbDelegateImpl::Put(const Key &key, const Value &value)
216 {
217     IOption option;
218     option.dataType = IOption::SYNC_DATA;
219     return PutInner(option, key, value);
220 }
221 
PutBatch(const std::vector<Entry> & entries)222 DBStatus KvStoreNbDelegateImpl::PutBatch(const std::vector<Entry> &entries)
223 {
224     if (conn_ != nullptr) {
225         IOption option;
226         option.dataType = IOption::SYNC_DATA;
227         int errCode = conn_->PutBatch(option, entries);
228         if (errCode == E_OK) {
229             return OK;
230         }
231 
232         LOGE("[KvStoreNbDelegate] Put batch data failed:%d", errCode);
233         return TransferDBErrno(errCode);
234     }
235 
236     LOGE("%s", INVALID_CONNECTION);
237     return DB_ERROR;
238 }
239 
DeleteBatch(const std::vector<Key> & keys)240 DBStatus KvStoreNbDelegateImpl::DeleteBatch(const std::vector<Key> &keys)
241 {
242     if (conn_ == nullptr) {
243         LOGE("%s", INVALID_CONNECTION);
244         return DB_ERROR;
245     }
246 
247     IOption option;
248     option.dataType = IOption::SYNC_DATA;
249     int errCode = conn_->DeleteBatch(option, keys);
250     if (errCode == E_OK || errCode == -E_NOT_FOUND) {
251         return OK;
252     }
253 
254     LOGE("[KvStoreNbDelegate] Delete batch data failed:%d", errCode);
255     return TransferDBErrno(errCode);
256 }
257 
Delete(const Key & key)258 DBStatus KvStoreNbDelegateImpl::Delete(const Key &key)
259 {
260     IOption option;
261     option.dataType = IOption::SYNC_DATA;
262     return DeleteInner(option, key);
263 }
264 
GetLocal(const Key & key,Value & value) const265 DBStatus KvStoreNbDelegateImpl::GetLocal(const Key &key, Value &value) const
266 {
267     IOption option;
268     option.dataType = IOption::LOCAL_DATA;
269     return GetInner(option, key, value);
270 }
271 
GetLocalEntries(const Key & keyPrefix,std::vector<Entry> & entries) const272 DBStatus KvStoreNbDelegateImpl::GetLocalEntries(const Key &keyPrefix, std::vector<Entry> &entries) const
273 {
274     IOption option;
275     option.dataType = IOption::LOCAL_DATA;
276     return GetEntriesInner(option, keyPrefix, entries);
277 }
278 
PutLocal(const Key & key,const Value & value)279 DBStatus KvStoreNbDelegateImpl::PutLocal(const Key &key, const Value &value)
280 {
281     IOption option;
282     option.dataType = IOption::LOCAL_DATA;
283     return PutInner(option, key, value);
284 }
285 
DeleteLocal(const Key & key)286 DBStatus KvStoreNbDelegateImpl::DeleteLocal(const Key &key)
287 {
288     IOption option;
289     option.dataType = IOption::LOCAL_DATA;
290     return DeleteInner(option, key);
291 }
292 
PublishLocal(const Key & key,bool deleteLocal,bool updateTimestamp,const KvStoreNbPublishOnConflict & onConflict)293 DBStatus KvStoreNbDelegateImpl::PublishLocal(const Key &key, bool deleteLocal, bool updateTimestamp,
294     const KvStoreNbPublishOnConflict &onConflict)
295 {
296     if (key.empty() || key.size() > DBConstant::MAX_KEY_SIZE) {
297         LOGW("[KvStoreNbDelegate][Publish] Invalid para");
298         return INVALID_ARGS;
299     }
300 
301     if (conn_ != nullptr) {
302         PragmaPublishInfo publishInfo{ key, deleteLocal, updateTimestamp, onConflict };
303         int errCode = conn_->Pragma(PRAGMA_PUBLISH_LOCAL, static_cast<PragmaData>(&publishInfo));
304         if (errCode != E_OK) {
305             LOGE("[KvStoreNbDelegate] Publish local err:%d", errCode);
306         }
307         return TransferDBErrno(errCode);
308     }
309 
310     LOGE("%s", INVALID_CONNECTION);
311     return DB_ERROR;
312 }
313 
UnpublishToLocal(const Key & key,bool deletePublic,bool updateTimestamp)314 DBStatus KvStoreNbDelegateImpl::UnpublishToLocal(const Key &key, bool deletePublic, bool updateTimestamp)
315 {
316     if (key.empty() || key.size() > DBConstant::MAX_KEY_SIZE) {
317         LOGW("[KvStoreNbDelegate][Unpublish] Invalid para");
318         return INVALID_ARGS;
319     }
320 
321     if (conn_ != nullptr) {
322         PragmaUnpublishInfo unpublishInfo{ key, deletePublic, updateTimestamp };
323         int errCode = conn_->Pragma(PRAGMA_UNPUBLISH_SYNC, static_cast<PragmaData>(&unpublishInfo));
324         if (errCode != E_OK) {
325             LOGE("[KvStoreNbDelegate] Unpublish result:%d", errCode);
326         }
327         return TransferDBErrno(errCode);
328     }
329 
330     LOGE("%s", INVALID_CONNECTION);
331     return DB_ERROR;
332 }
333 
PutLocalBatch(const std::vector<Entry> & entries)334 DBStatus KvStoreNbDelegateImpl::PutLocalBatch(const std::vector<Entry> &entries)
335 {
336     if (conn_ == nullptr) {
337         LOGE("%s", INVALID_CONNECTION);
338         return DB_ERROR;
339     }
340 
341     IOption option;
342     option.dataType = IOption::LOCAL_DATA;
343     int errCode = conn_->PutBatch(option, entries);
344     if (errCode != E_OK) {
345         LOGE("[KvStoreNbDelegate] Put local batch data failed:%d", errCode);
346     }
347     return TransferDBErrno(errCode);
348 }
349 
DeleteLocalBatch(const std::vector<Key> & keys)350 DBStatus KvStoreNbDelegateImpl::DeleteLocalBatch(const std::vector<Key> &keys)
351 {
352     if (conn_ == nullptr) {
353         LOGE("%s", INVALID_CONNECTION);
354         return DB_ERROR;
355     }
356 
357     IOption option;
358     option.dataType = IOption::LOCAL_DATA;
359     int errCode = conn_->DeleteBatch(option, keys);
360     if (errCode == E_OK || errCode == -E_NOT_FOUND) {
361         return OK;
362     }
363 
364     LOGE("[KvStoreNbDelegate] Delete local batch data failed:%d", errCode);
365     return TransferDBErrno(errCode);
366 }
367 
RegisterObserver(const Key & key,unsigned int mode,KvStoreObserver * observer)368 DBStatus KvStoreNbDelegateImpl::RegisterObserver(const Key &key, unsigned int mode, KvStoreObserver *observer)
369 {
370     if (key.size() > DBConstant::MAX_KEY_SIZE) {
371         return INVALID_ARGS;
372     }
373     uint64_t rawMode = DBCommon::EraseBit(mode, DBConstant::OBSERVER_CHANGES_MASK);
374     if (rawMode == static_cast<uint64_t>(ObserverMode::OBSERVER_CHANGES_CLOUD)) {
375         return RegisterCloudObserver(key, mode, observer);
376     }
377     return RegisterDeviceObserver(key, static_cast<unsigned int>(rawMode), observer);
378 }
379 
RegisterDeviceObserver(const Key & key,unsigned int mode,KvStoreObserver * observer)380 DBStatus KvStoreNbDelegateImpl::RegisterDeviceObserver(const Key &key, unsigned int mode, KvStoreObserver *observer)
381 {
382     if (!ParamCheckUtils::CheckObserver(key, mode)) {
383         LOGE("Register nb observer by illegal mode or key size!");
384         return INVALID_ARGS;
385     }
386 
387     if (observer == nullptr) {
388         return INVALID_ARGS;
389     }
390 
391     std::lock_guard<std::mutex> lockGuard(observerMapLock_);
392     if (observerMap_.size() >= DBConstant::MAX_OBSERVER_COUNT) {
393         LOGE("[KvStoreNbDelegate] The number of kv observers has been over limit, storeId[%.3s]", storeId_.c_str());
394         return OVER_MAX_LIMITS;
395     }
396     if (observerMap_.find(observer) != observerMap_.end()) {
397         LOGE("[KvStoreNbDelegate] Observer has been already registered!");
398         return ALREADY_SET;
399     }
400 
401     if (conn_ == nullptr) {
402         LOGE("%s", INVALID_CONNECTION);
403         return DB_ERROR;
404     }
405 
406     if (conn_->IsTransactionStarted()) {
407         return BUSY;
408     }
409 
410     int errCode = E_OK;
411     auto storeId = storeId_;
412     KvDBObserverHandle *observerHandle = conn_->RegisterObserver(
413         mode, key,
414         [observer, storeId](const KvDBCommitNotifyData &notifyData) {
415             KvStoreChangedDataImpl data(&notifyData);
416             LOGD("[KvStoreNbDelegate] Trigger [%s] on change", storeId.c_str());
417             observer->OnChange(data);
418         },
419         errCode);
420 
421     if (errCode != E_OK || observerHandle == nullptr) {
422         LOGE("[KvStoreNbDelegate] RegisterListener failed:%d!", errCode);
423         return DB_ERROR;
424     }
425 
426     observerMap_.insert(std::pair<const KvStoreObserver *, const KvDBObserverHandle *>(observer, observerHandle));
427     LOGI("[KvStoreNbDelegate] RegisterDeviceObserver ok mode:%u", mode);
428     return OK;
429 }
430 
RegisterCloudObserver(const Key & key,unsigned int mode,KvStoreObserver * observer)431 DBStatus KvStoreNbDelegateImpl::RegisterCloudObserver(const Key &key, unsigned int mode,
432     KvStoreObserver *observer)
433 {
434     if (conn_ == nullptr) {
435         LOGE("%s", INVALID_CONNECTION);
436         return DB_ERROR;
437     }
438 
439     std::lock_guard<std::mutex> lockGuard(observerMapLock_);
440     if (cloudObserverMap_.size() >= DBConstant::MAX_OBSERVER_COUNT) {
441         LOGE("[KvStoreNbDelegate] The number of kv cloud observers has been over limit, storeId[%.3s]",
442             storeId_.c_str());
443         return OVER_MAX_LIMITS;
444     }
445     if (cloudObserverMap_.find(observer) != cloudObserverMap_.end() && cloudObserverMap_[observer] == mode) {
446         LOGE("[KvStoreNbDelegate] Cloud observer has been already registered!");
447         return ALREADY_SET;
448     }
449 
450     auto storeId = storeId_;
451     ObserverAction action = [observer, storeId](
452                                 const std::string &device, ChangedData &&changedData, bool isChangedData) {
453         if (isChangedData) {
454             LOGD("[KvStoreNbDelegate] Trigger [%s] on change", storeId.c_str());
455             observer->OnChange(Origin::ORIGIN_CLOUD, device, std::move(changedData));
456         }
457     };
458     int errCode = conn_->RegisterObserverAction(observer, action);
459     if (errCode != E_OK) {
460         LOGE("[KvStoreNbDelegate] RegisterCloudObserver failed:%d!", errCode);
461         return DB_ERROR;
462     }
463     cloudObserverMap_[observer] = mode;
464     LOGI("[KvStoreNbDelegate] RegisterCloudObserver ok mode:%u", mode);
465     return OK;
466 }
467 
UnRegisterObserver(const KvStoreObserver * observer)468 DBStatus KvStoreNbDelegateImpl::UnRegisterObserver(const KvStoreObserver *observer)
469 {
470     if (observer == nullptr) {
471         return INVALID_ARGS;
472     }
473 
474     if (conn_ == nullptr) {
475         LOGE("%s", INVALID_CONNECTION);
476         return DB_ERROR;
477     }
478 
479     DBStatus cloudRet = UnRegisterCloudObserver(observer);
480     DBStatus devRet = UnRegisterDeviceObserver(observer);
481     if (cloudRet == OK || devRet == OK) {
482         return OK;
483     }
484     return devRet;
485 }
486 
UnRegisterDeviceObserver(const KvStoreObserver * observer)487 DBStatus KvStoreNbDelegateImpl::UnRegisterDeviceObserver(const KvStoreObserver *observer)
488 {
489     std::lock_guard<std::mutex> lockGuard(observerMapLock_);
490     auto iter = observerMap_.find(observer);
491     if (iter == observerMap_.end()) {
492         LOGE("[KvStoreNbDelegate] [%s] Observer has not been registered!", storeId_.c_str());
493         return NOT_FOUND;
494     }
495 
496     const KvDBObserverHandle *observerHandle = iter->second;
497     int errCode = conn_->UnRegisterObserver(observerHandle);
498     if (errCode != E_OK) {
499         LOGE("[KvStoreNbDelegate] UnRegistObserver failed:%d!", errCode);
500         return DB_ERROR;
501     }
502     observerMap_.erase(iter);
503     return OK;
504 }
505 
UnRegisterCloudObserver(const KvStoreObserver * observer)506 DBStatus KvStoreNbDelegateImpl::UnRegisterCloudObserver(const KvStoreObserver *observer)
507 {
508     std::lock_guard<std::mutex> lockGuard(observerMapLock_);
509     auto iter = cloudObserverMap_.find(observer);
510     if (iter == cloudObserverMap_.end()) {
511         LOGW("[KvStoreNbDelegate] [%s] CloudObserver has not been registered!", storeId_.c_str());
512         return NOT_FOUND;
513     }
514     int errCode = conn_->UnRegisterObserverAction(observer);
515     if (errCode != E_OK) {
516         LOGE("[KvStoreNbDelegate] UnRegisterCloudObserver failed:%d!", errCode);
517         return DB_ERROR;
518     }
519     cloudObserverMap_.erase(iter);
520     return OK;
521 }
522 
RemoveDeviceData(const std::string & device)523 DBStatus KvStoreNbDelegateImpl::RemoveDeviceData(const std::string &device)
524 {
525     if (conn_ == nullptr) {
526         LOGE("%s", INVALID_CONNECTION);
527         return DB_ERROR;
528     }
529     if (device.empty() || device.length() > DBConstant::MAX_DEV_LENGTH) {
530         return INVALID_ARGS;
531     }
532     int errCode = conn_->Pragma(PRAGMA_RM_DEVICE_DATA,
533         const_cast<void *>(static_cast<const void *>(&device)));
534     if (errCode != E_OK) {
535         LOGE("[KvStoreNbDelegate] Remove device data failed:%d", errCode);
536     }
537     return TransferDBErrno(errCode);
538 }
539 
GetStoreId() const540 std::string KvStoreNbDelegateImpl::GetStoreId() const
541 {
542     return storeId_;
543 }
544 
Sync(const std::vector<std::string> & devices,SyncMode mode,const std::function<void (const std::map<std::string,DBStatus> & devicesMap)> & onComplete,bool wait=false)545 DBStatus KvStoreNbDelegateImpl::Sync(const std::vector<std::string> &devices, SyncMode mode,
546     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete,
547     bool wait = false)
548 {
549     if (conn_ == nullptr) {
550         LOGE("%s", INVALID_CONNECTION);
551         return DB_ERROR;
552     }
553     if (mode > SYNC_MODE_PUSH_PULL) {
554         LOGE("not support other mode");
555         return NOT_SUPPORT;
556     }
557 
558     PragmaSync pragmaData(
559         devices, mode, [this, onComplete](const std::map<std::string, int> &statuses) {
560             OnSyncComplete(statuses, onComplete);
561         }, wait);
562     int errCode = conn_->Pragma(PRAGMA_SYNC_DEVICES, &pragmaData);
563     if (errCode < E_OK) {
564         LOGE("[KvStoreNbDelegate] Sync data failed:%d", errCode);
565         return TransferDBErrno(errCode);
566     }
567     return OK;
568 }
569 
Sync(const std::vector<std::string> & devices,SyncMode mode,const std::function<void (const std::map<std::string,DBStatus> & devicesMap)> & onComplete,const Query & query,bool wait)570 DBStatus KvStoreNbDelegateImpl::Sync(const std::vector<std::string> &devices, SyncMode mode,
571     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete,
572     const Query &query, bool wait)
573 {
574     if (conn_ == nullptr) {
575         LOGE("%s", INVALID_CONNECTION);
576         return DB_ERROR;
577     }
578     if (mode > SYNC_MODE_PUSH_PULL) {
579         LOGE("not support other mode");
580         return NOT_SUPPORT;
581     }
582 
583     if (!DBCommon::CheckQueryWithoutMultiTable(query)) {
584         LOGE("not support for invalid query");
585         return NOT_SUPPORT;
586     }
587     QuerySyncObject querySyncObj(query);
588     if (querySyncObj.GetSortType() != SortType::NONE || querySyncObj.IsQueryByRange()) {
589         LOGE("not support order by timestamp and query by range");
590         return NOT_SUPPORT;
591     }
592     PragmaSync pragmaData(
593         devices, mode, querySyncObj, [this, onComplete](const std::map<std::string, int> &statuses) {
594             OnSyncComplete(statuses, onComplete);
595         }, wait);
596     int errCode = conn_->Pragma(PRAGMA_SYNC_DEVICES, &pragmaData);
597     if (errCode < E_OK) {
598         LOGE("[KvStoreNbDelegate] QuerySync data failed:%d", errCode);
599         return TransferDBErrno(errCode);
600     }
601     return OK;
602 }
603 
Pragma(PragmaCmd cmd,PragmaData & paramData)604 DBStatus KvStoreNbDelegateImpl::Pragma(PragmaCmd cmd, PragmaData &paramData)
605 {
606     if (conn_ == nullptr) {
607         LOGE("%s", INVALID_CONNECTION);
608         return DB_ERROR;
609     }
610 
611     int errCode = -E_NOT_SUPPORT;
612     for (const auto &item : g_pragmaMap) {
613         if (item.externCmd == cmd) {
614             errCode = conn_->Pragma(item.innerCmd, paramData);
615             break;
616         }
617     }
618 
619     if (errCode != E_OK) {
620         LOGE("[KvStoreNbDelegate] Pragma failed:%d", errCode);
621     }
622     return TransferDBErrno(errCode);
623 }
624 
SetConflictNotifier(int conflictType,const KvStoreNbConflictNotifier & notifier)625 DBStatus KvStoreNbDelegateImpl::SetConflictNotifier(int conflictType, const KvStoreNbConflictNotifier &notifier)
626 {
627     if (conn_ == nullptr) {
628         LOGE("%s", INVALID_CONNECTION);
629         return DB_ERROR;
630     }
631 
632     if (!ParamCheckUtils::CheckConflictNotifierType(conflictType)) {
633         LOGE("%s", INVALID_CONNECTION);
634         return INVALID_ARGS;
635     }
636 
637     int errCode;
638     if (!notifier) {
639         errCode = conn_->SetConflictNotifier(conflictType, nullptr);
640         goto END;
641     }
642 
643     errCode = conn_->SetConflictNotifier(conflictType,
644         [conflictType, notifier](const KvDBCommitNotifyData &data) {
645             int resultCode;
646             const std::list<KvDBConflictEntry> entries = data.GetCommitConflicts(resultCode);
647             if (resultCode != E_OK) {
648                 LOGE("Get commit conflicted entries failed:%d!", resultCode);
649                 return;
650             }
651 
652             for (const auto &entry : entries) {
653                 // Prohibit signed numbers to perform bit operations
654                 uint32_t entryType = static_cast<uint32_t>(entry.type);
655                 uint32_t type = static_cast<uint32_t>(conflictType);
656                 if (entryType & type) {
657                     KvStoreNbConflictDataImpl dataImpl;
658                     dataImpl.SetConflictData(entry);
659                     notifier(dataImpl);
660                 }
661             }
662         });
663 
664 END:
665     if (errCode != E_OK) {
666         LOGE("[KvStoreNbDelegate] Register conflict failed:%d!", errCode);
667     }
668     return TransferDBErrno(errCode);
669 }
670 
Rekey(const CipherPassword & password)671 DBStatus KvStoreNbDelegateImpl::Rekey(const CipherPassword &password)
672 {
673     if (conn_ == nullptr) {
674         LOGE("%s", INVALID_CONNECTION);
675         return DB_ERROR;
676     }
677 
678     int errCode = conn_->Rekey(password);
679     if (errCode == E_OK) {
680         return OK;
681     }
682 
683     LOGE("[KvStoreNbDelegate] Rekey failed:%d", errCode);
684     return TransferDBErrno(errCode);
685 }
686 
Export(const std::string & filePath,const CipherPassword & passwd,bool force)687 DBStatus KvStoreNbDelegateImpl::Export(const std::string &filePath, const CipherPassword &passwd, bool force)
688 {
689     if (conn_ == nullptr) {
690         LOGE("%s", INVALID_CONNECTION);
691         return DB_ERROR;
692     }
693 
694     std::string fileDir;
695     std::string fileName;
696     OS::SplitFilePath(filePath, fileDir, fileName);
697 
698     std::string canonicalUrl;
699     if (!ParamCheckUtils::CheckDataDir(fileDir, canonicalUrl)) {
700         return INVALID_ARGS;
701     }
702 
703     if (!OS::CheckPathExistence(canonicalUrl)) {
704         return NO_PERMISSION;
705     }
706 
707     canonicalUrl = canonicalUrl + "/" + fileName;
708     if (!force && OS::CheckPathExistence(canonicalUrl)) {
709         return FILE_ALREADY_EXISTED;
710     }
711 
712     int errCode = conn_->Export(canonicalUrl, passwd);
713     if (errCode == E_OK) {
714         return OK;
715     }
716     LOGE("[KvStoreNbDelegate] Export failed:%d", errCode);
717     return TransferDBErrno(errCode);
718 }
719 
Import(const std::string & filePath,const CipherPassword & passwd)720 DBStatus KvStoreNbDelegateImpl::Import(const std::string &filePath, const CipherPassword &passwd)
721 {
722     if (conn_ == nullptr) {
723         LOGE("%s", INVALID_CONNECTION);
724         return DB_ERROR;
725     }
726 
727     std::string fileDir;
728     std::string fileName;
729     OS::SplitFilePath(filePath, fileDir, fileName);
730 
731     std::string canonicalUrl;
732     if (!ParamCheckUtils::CheckDataDir(fileDir, canonicalUrl)) {
733         return INVALID_ARGS;
734     }
735 
736     canonicalUrl = canonicalUrl + "/" + fileName;
737     if (!OS::CheckPathExistence(canonicalUrl)) {
738         LOGE("Import file path err, DBStatus = INVALID_FILE errno = [%d]", errno);
739         return INVALID_FILE;
740     }
741 
742     int errCode = conn_->Import(canonicalUrl, passwd);
743     if (errCode == E_OK) {
744         LOGI("[KvStoreNbDelegate] Import ok");
745         return OK;
746     }
747 
748     LOGE("[KvStoreNbDelegate] Import failed:%d", errCode);
749     return TransferDBErrno(errCode);
750 }
751 
StartTransaction()752 DBStatus KvStoreNbDelegateImpl::StartTransaction()
753 {
754     if (conn_ == nullptr) {
755         LOGE("%s", INVALID_CONNECTION);
756         return DB_ERROR;
757     }
758 
759     int errCode = conn_->StartTransaction();
760     if (errCode != E_OK) {
761         LOGE("[KvStoreNbDelegate] StartTransaction failed:%d", errCode);
762     }
763     return TransferDBErrno(errCode);
764 }
765 
Commit()766 DBStatus KvStoreNbDelegateImpl::Commit()
767 {
768     if (conn_ == nullptr) {
769         LOGE("%s", INVALID_CONNECTION);
770         return DB_ERROR;
771     }
772 
773     int errCode = conn_->Commit();
774     if (errCode != E_OK) {
775         LOGE("[KvStoreNbDelegate] Commit failed:%d", errCode);
776     }
777     return TransferDBErrno(errCode);
778 }
779 
Rollback()780 DBStatus KvStoreNbDelegateImpl::Rollback()
781 {
782     if (conn_ == nullptr) {
783         LOGE("%s", INVALID_CONNECTION);
784         return DB_ERROR;
785     }
786 
787     int errCode = conn_->RollBack();
788     if (errCode != E_OK) {
789         LOGE("[KvStoreNbDelegate] Rollback failed:%d", errCode);
790     }
791     return TransferDBErrno(errCode);
792 }
793 
SetReleaseFlag(bool flag)794 void KvStoreNbDelegateImpl::SetReleaseFlag(bool flag)
795 {
796     releaseFlag_ = flag;
797 }
798 
Close()799 DBStatus KvStoreNbDelegateImpl::Close()
800 {
801     if (conn_ != nullptr) {
802         int errCode = KvDBManager::ReleaseDatabaseConnection(conn_);
803         if (errCode == -E_BUSY) {
804             LOGI("[KvStoreNbDelegate] Busy for close");
805             return BUSY;
806         }
807         conn_ = nullptr;
808     }
809     return OK;
810 }
811 
CheckIntegrity() const812 DBStatus KvStoreNbDelegateImpl::CheckIntegrity() const
813 {
814     if (conn_ == nullptr) {
815         LOGE("%s", INVALID_CONNECTION);
816         return DB_ERROR;
817     }
818 
819     return TransferDBErrno(conn_->CheckIntegrity());
820 }
821 
GetSecurityOption(SecurityOption & option) const822 DBStatus KvStoreNbDelegateImpl::GetSecurityOption(SecurityOption &option) const
823 {
824     if (conn_ == nullptr) {
825         LOGE("%s", INVALID_CONNECTION);
826         return DB_ERROR;
827     }
828     return TransferDBErrno(conn_->GetSecurityOption(option.securityLabel, option.securityFlag));
829 }
830 
SetRemotePushFinishedNotify(const RemotePushFinishedNotifier & notifier)831 DBStatus KvStoreNbDelegateImpl::SetRemotePushFinishedNotify(const RemotePushFinishedNotifier &notifier)
832 {
833     if (conn_ == nullptr) {
834         LOGE("%s", INVALID_CONNECTION);
835         return DB_ERROR;
836     }
837 
838     PragmaRemotePushNotify notify(notifier);
839     int errCode = conn_->Pragma(PRAGMA_REMOTE_PUSH_FINISHED_NOTIFY, reinterpret_cast<void *>(&notify));
840     if (errCode != E_OK) {
841         LOGE("[KvStoreNbDelegate] Set remote push finished notify failed : %d", errCode);
842     }
843     return TransferDBErrno(errCode);
844 }
845 
GetInner(const IOption & option,const Key & key,Value & value) const846 DBStatus KvStoreNbDelegateImpl::GetInner(const IOption &option, const Key &key, Value &value) const
847 {
848     if (conn_ == nullptr) {
849         LOGE("%s", INVALID_CONNECTION);
850         return DB_ERROR;
851     }
852 
853     int errCode = conn_->Get(option, key, value);
854     if (errCode == E_OK) {
855         return OK;
856     }
857 
858     if (errCode != -E_NOT_FOUND) {
859         LOGE("[KvStoreNbDelegate] [%s] Get the data failed:%d", storeId_.c_str(), errCode);
860     }
861     return TransferDBErrno(errCode);
862 }
863 
GetEntriesInner(const IOption & option,const Key & keyPrefix,std::vector<Entry> & entries) const864 DBStatus KvStoreNbDelegateImpl::GetEntriesInner(const IOption &option,
865     const Key &keyPrefix, std::vector<Entry> &entries) const
866 {
867     if (conn_ == nullptr) {
868         LOGE("%s", INVALID_CONNECTION);
869         return DB_ERROR;
870     }
871 
872     int errCode = conn_->GetEntries(option, keyPrefix, entries);
873     if (errCode == E_OK) {
874         return OK;
875     }
876     LOGE("[KvStoreNbDelegate] Get the batch data failed:%d", errCode);
877     return TransferDBErrno(errCode);
878 }
879 
PutInner(const IOption & option,const Key & key,const Value & value)880 DBStatus KvStoreNbDelegateImpl::PutInner(const IOption &option, const Key &key, const Value &value)
881 {
882     if (conn_ == nullptr) {
883         LOGE("%s", INVALID_CONNECTION);
884         return DB_ERROR;
885     }
886 
887     PerformanceAnalysis *performance = PerformanceAnalysis::GetInstance();
888     if (performance != nullptr) {
889         performance->StepTimeRecordStart(PT_TEST_RECORDS::RECORD_PUT_DATA);
890     }
891 
892     int errCode = conn_->Put(option, key, value);
893     if (performance != nullptr) {
894         performance->StepTimeRecordEnd(PT_TEST_RECORDS::RECORD_PUT_DATA);
895     }
896 
897     if (errCode == E_OK) {
898         return OK;
899     }
900     LOGE("[KvStoreNbDelegate] Put the data failed:%d", errCode);
901     return TransferDBErrno(errCode);
902 }
903 
DeleteInner(const IOption & option,const Key & key)904 DBStatus KvStoreNbDelegateImpl::DeleteInner(const IOption &option, const Key &key)
905 {
906     if (conn_ == nullptr) {
907         LOGE("%s", INVALID_CONNECTION);
908         return DB_ERROR;
909     }
910 
911     int errCode = conn_->Delete(option, key);
912     if (errCode == E_OK || errCode == -E_NOT_FOUND) {
913         return OK;
914     }
915 
916     LOGE("[KvStoreNbDelegate] Delete the data failed:%d", errCode);
917     return TransferDBErrno(errCode);
918 }
919 
OnSyncComplete(const std::map<std::string,int> & statuses,const std::function<void (const std::map<std::string,DBStatus> & devicesMap)> & onComplete) const920 void KvStoreNbDelegateImpl::OnSyncComplete(const std::map<std::string, int> &statuses,
921     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete) const
922 {
923     std::map<std::string, DBStatus> result;
924     for (const auto &pair : statuses) {
925         DBStatus status = SyncOperation::DBStatusTrans(pair.second);
926         result.insert(std::pair<std::string, DBStatus>(pair.first, status));
927     }
928     if (onComplete) {
929         onComplete(result);
930     }
931 }
932 
SetEqualIdentifier(const std::string & identifier,const std::vector<std::string> & targets)933 DBStatus KvStoreNbDelegateImpl::SetEqualIdentifier(const std::string &identifier,
934     const std::vector<std::string> &targets)
935 {
936     if (conn_ == nullptr) {
937         LOGE("%s", INVALID_CONNECTION);
938         return DB_ERROR;
939     }
940 
941     PragmaSetEqualIdentifier pragma(identifier, targets);
942     int errCode = conn_->Pragma(PRAGMA_ADD_EQUAL_IDENTIFIER, reinterpret_cast<void *>(&pragma));
943     if (errCode != E_OK) {
944         LOGE("[KvStoreNbDelegate] Set store equal identifier failed : %d", errCode);
945     }
946 
947     return TransferDBErrno(errCode);
948 }
949 
SetPushDataInterceptor(const PushDataInterceptor & interceptor)950 DBStatus KvStoreNbDelegateImpl::SetPushDataInterceptor(const PushDataInterceptor &interceptor)
951 {
952     if (conn_ == nullptr) {
953         LOGE("%s", INVALID_CONNECTION);
954         return DB_ERROR;
955     }
956 
957     PushDataInterceptor notify = interceptor;
958     int errCode = conn_->Pragma(PRAGMA_INTERCEPT_SYNC_DATA, static_cast<void *>(&notify));
959     if (errCode != E_OK) {
960         LOGE("[KvStoreNbDelegate] Set data interceptor notify failed : %d", errCode);
961     }
962     return TransferDBErrno(errCode);
963 }
964 
SubscribeRemoteQuery(const std::vector<std::string> & devices,const std::function<void (const std::map<std::string,DBStatus> & devicesMap)> & onComplete,const Query & query,bool wait)965 DBStatus KvStoreNbDelegateImpl::SubscribeRemoteQuery(const std::vector<std::string> &devices,
966     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete,
967     const Query &query, bool wait)
968 {
969     if (conn_ == nullptr) {
970         LOGE("%s", INVALID_CONNECTION);
971         return DB_ERROR;
972     }
973 
974     QuerySyncObject querySyncObj(query);
975     if (querySyncObj.GetSortType() != SortType::NONE || querySyncObj.IsQueryByRange()) {
976         LOGE("not support order by timestamp and query by range");
977         return NOT_SUPPORT;
978     }
979     PragmaSync pragmaData(devices, SyncModeType::SUBSCRIBE_QUERY, querySyncObj,
980         [this, onComplete](const std::map<std::string, int> &statuses) { OnSyncComplete(statuses, onComplete); }, wait);
981     int errCode = conn_->Pragma(PRAGMA_SUBSCRIBE_QUERY, &pragmaData);
982     if (errCode < E_OK) {
983         LOGE("[KvStoreNbDelegate] Subscribe remote data with query failed:%d", errCode);
984         return TransferDBErrno(errCode);
985     }
986     return OK;
987 }
988 
UnSubscribeRemoteQuery(const std::vector<std::string> & devices,const std::function<void (const std::map<std::string,DBStatus> & devicesMap)> & onComplete,const Query & query,bool wait)989 DBStatus KvStoreNbDelegateImpl::UnSubscribeRemoteQuery(const std::vector<std::string> &devices,
990     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete,
991     const Query &query, bool wait)
992 {
993     if (conn_ == nullptr) {
994         LOGE("%s", INVALID_CONNECTION);
995         return DB_ERROR;
996     }
997 
998     QuerySyncObject querySyncObj(query);
999     if (querySyncObj.GetSortType() != SortType::NONE || querySyncObj.IsQueryByRange()) {
1000         LOGE("not support order by timestamp and query by range");
1001         return NOT_SUPPORT;
1002     }
1003     PragmaSync pragmaData(devices, SyncModeType::UNSUBSCRIBE_QUERY, querySyncObj,
1004         [this, onComplete](const std::map<std::string, int> &statuses) { OnSyncComplete(statuses, onComplete); }, wait);
1005     int errCode = conn_->Pragma(PRAGMA_SUBSCRIBE_QUERY, &pragmaData);
1006     if (errCode < E_OK) {
1007         LOGE("[KvStoreNbDelegate] Unsubscribe remote data with query failed:%d", errCode);
1008         return TransferDBErrno(errCode);
1009     }
1010     return OK;
1011 }
1012 
RemoveDeviceData()1013 DBStatus KvStoreNbDelegateImpl::RemoveDeviceData()
1014 {
1015     if (conn_ == nullptr) {
1016         LOGE("%s", INVALID_CONNECTION);
1017         return DB_ERROR;
1018     }
1019 
1020     std::string device; // Empty device for remove all device data
1021     int errCode = conn_->Pragma(PRAGMA_RM_DEVICE_DATA,
1022         const_cast<void *>(static_cast<const void *>(&device)));
1023     if (errCode != E_OK) {
1024         LOGE("[KvStoreNbDelegate] Remove device data failed:%d", errCode);
1025     }
1026     return TransferDBErrno(errCode);
1027 }
1028 
GetKeys(const Key & keyPrefix,std::vector<Key> & keys) const1029 DBStatus KvStoreNbDelegateImpl::GetKeys(const Key &keyPrefix, std::vector<Key> &keys) const
1030 {
1031     if (conn_ == nullptr) {
1032         LOGE("%s", INVALID_CONNECTION);
1033         return DB_ERROR;
1034     }
1035     IOption option;
1036     option.dataType = IOption::SYNC_DATA;
1037     int errCode = conn_->GetKeys(option, keyPrefix, keys);
1038     if (errCode == E_OK) {
1039         return OK;
1040     }
1041     LOGE("[KvStoreNbDelegate] Get the keys failed:%d", errCode);
1042     return TransferDBErrno(errCode);
1043 }
1044 
GetSyncDataSize(const std::string & device) const1045 size_t KvStoreNbDelegateImpl::GetSyncDataSize(const std::string &device) const
1046 {
1047     if (conn_ == nullptr) {
1048         LOGE("%s", INVALID_CONNECTION);
1049         return 0;
1050     }
1051     if (device.empty()) {
1052         LOGE("device len is invalid");
1053         return 0;
1054     }
1055     size_t size = 0;
1056     int errCode = conn_->GetSyncDataSize(device, size);
1057     if (errCode != E_OK) {
1058         LOGE("[KvStoreNbDelegate] calculate sync data size failed : %d", errCode);
1059         return 0;
1060     }
1061     return size;
1062 }
1063 
UpdateKey(const UpdateKeyCallback & callback)1064 DBStatus KvStoreNbDelegateImpl::UpdateKey(const UpdateKeyCallback &callback)
1065 {
1066     if (conn_ == nullptr) {
1067         LOGE("%s", INVALID_CONNECTION);
1068         return DB_ERROR;
1069     }
1070     if (callback == nullptr) {
1071         LOGE("[KvStoreNbDelegate] Invalid callback for operation");
1072         return INVALID_ARGS;
1073     }
1074     int errCode = conn_->UpdateKey(callback);
1075     if (errCode == E_OK) {
1076         LOGI("[KvStoreNbDelegate] update keys success");
1077         return OK;
1078     }
1079     LOGE("[KvStoreNbDelegate] update keys failed:%d", errCode);
1080     return TransferDBErrno(errCode);
1081 }
1082 
GetWatermarkInfo(const std::string & device)1083 std::pair<DBStatus, WatermarkInfo> KvStoreNbDelegateImpl::GetWatermarkInfo(const std::string &device)
1084 {
1085     std::pair<DBStatus, WatermarkInfo> res;
1086     if (device.empty() || device.size() > DBConstant::MAX_DEV_LENGTH) {
1087         LOGE("[KvStoreNbDelegate] device invalid length %zu", device.size());
1088         res.first = INVALID_ARGS;
1089         return res;
1090     }
1091     if (conn_ == nullptr) {
1092         LOGE("%s", INVALID_CONNECTION);
1093         res.first = DB_ERROR;
1094         return res;
1095     }
1096     int errCode = conn_->GetWatermarkInfo(device, res.second);
1097     if (errCode == E_OK) {
1098         LOGI("[KvStoreNbDelegate] get watermark info success");
1099     } else {
1100         LOGE("[KvStoreNbDelegate] get watermark info failed:%d", errCode);
1101     }
1102     res.first = TransferDBErrno(errCode);
1103     return res;
1104 }
1105 
Sync(const CloudSyncOption & option,const SyncProcessCallback & onProcess)1106 DBStatus KvStoreNbDelegateImpl::Sync(const CloudSyncOption &option, const SyncProcessCallback &onProcess)
1107 {
1108     if (conn_ == nullptr) {
1109         LOGE("%s", INVALID_CONNECTION);
1110         return DB_ERROR;
1111     }
1112     return TransferDBErrno(conn_->Sync(option, onProcess));
1113 }
1114 
SetCloudDB(const std::map<std::string,std::shared_ptr<ICloudDb>> & cloudDBs)1115 DBStatus KvStoreNbDelegateImpl::SetCloudDB(const std::map<std::string, std::shared_ptr<ICloudDb>> &cloudDBs)
1116 {
1117     if (conn_ == nullptr) {
1118         LOGE("%s", INVALID_CONNECTION);
1119         return DB_ERROR;
1120     }
1121     if (cloudDBs.empty()) {
1122         LOGE("[KvStoreNbDelegate] no cloud db");
1123         return INVALID_ARGS;
1124     }
1125     return TransferDBErrno(conn_->SetCloudDB(cloudDBs));
1126 }
1127 
SetCloudDbSchema(const std::map<std::string,DataBaseSchema> & schema)1128 DBStatus KvStoreNbDelegateImpl::SetCloudDbSchema(const std::map<std::string, DataBaseSchema> &schema)
1129 {
1130     if (conn_ == nullptr) {
1131         LOGE("%s", INVALID_CONNECTION);
1132         return DB_ERROR;
1133     }
1134     return TransferDBErrno(conn_->SetCloudDbSchema(schema));
1135 }
1136 
RemoveDeviceData(const std::string & device,ClearMode mode)1137 DBStatus KvStoreNbDelegateImpl::RemoveDeviceData(const std::string &device, ClearMode mode)
1138 {
1139     if (conn_ == nullptr) {
1140         LOGE("%s", INVALID_CONNECTION);
1141         return DB_ERROR;
1142     }
1143     int errCode = conn_->RemoveDeviceData(device, mode);
1144     if (errCode != E_OK) {
1145         LOGE("[KvStoreNbDelegate] remove device data res %d", errCode);
1146     }
1147     LOGI("[KvStoreNbDelegate] remove device data res");
1148     return TransferDBErrno(errCode);
1149 }
1150 
RemoveDeviceData(const std::string & device,const std::string & user,ClearMode mode)1151 DBStatus KvStoreNbDelegateImpl::RemoveDeviceData(const std::string &device, const std::string &user,
1152     ClearMode mode)
1153 {
1154     if (conn_ == nullptr) {
1155         LOGE("%s", INVALID_CONNECTION);
1156         return DB_ERROR;
1157     }
1158     if (user.empty() && mode != ClearMode::DEFAULT) {
1159         LOGE("[KvStoreNbDelegate] remove device data with empty user!");
1160         return INVALID_ARGS;
1161     }
1162     int errCode = conn_->RemoveDeviceData(device, user, mode);
1163     if (errCode != E_OK) {
1164         LOGE("[KvStoreNbDelegate] remove device data with user res %d", errCode);
1165     }
1166     LOGI("[KvStoreNbDelegate] remove device data with user res");
1167     return TransferDBErrno(errCode);
1168 }
1169 
GetTaskCount()1170 int32_t KvStoreNbDelegateImpl::GetTaskCount()
1171 {
1172     if (conn_ == nullptr) {
1173         LOGE("%s", INVALID_CONNECTION);
1174         return DB_ERROR;
1175     }
1176     return conn_->GetTaskCount();
1177 }
1178 
SetGenCloudVersionCallback(const GenerateCloudVersionCallback & callback)1179 void KvStoreNbDelegateImpl::SetGenCloudVersionCallback(const GenerateCloudVersionCallback &callback)
1180 {
1181     if (conn_ == nullptr || callback == nullptr) {
1182         LOGD("[KvStoreNbDelegate] Invalid connection or callback for operation");
1183         return;
1184     }
1185     conn_->SetGenCloudVersionCallback(callback);
1186 }
1187 
GetCloudVersion(const std::string & device)1188 std::pair<DBStatus, std::map<std::string, std::string>> KvStoreNbDelegateImpl::GetCloudVersion(
1189     const std::string &device)
1190 {
1191     std::pair<DBStatus, std::map<std::string, std::string>> res;
1192     if (device.size() > DBConstant::MAX_DEV_LENGTH) {
1193         LOGE("[KvStoreNbDelegate] device invalid length %zu", device.size());
1194         res.first = INVALID_ARGS;
1195         return res;
1196     }
1197     if (conn_ == nullptr) {
1198         LOGE("%s", INVALID_CONNECTION);
1199         res.first = DB_ERROR;
1200         return res;
1201     }
1202     int errCode = conn_->GetCloudVersion(device, res.second);
1203     if (errCode == E_OK) {
1204         LOGI("[KvStoreNbDelegate] get cloudVersion success");
1205     } else {
1206         LOGE("[KvStoreNbDelegate] get cloudVersion failed:%d", errCode);
1207     }
1208     if (errCode == E_OK && res.second.empty()) {
1209         errCode = -E_NOT_FOUND;
1210     }
1211     res.first = TransferDBErrno(errCode);
1212     return res;
1213 }
1214 
SetReceiveDataInterceptor(const DataInterceptor & interceptor)1215 DBStatus KvStoreNbDelegateImpl::SetReceiveDataInterceptor(const DataInterceptor &interceptor)
1216 {
1217     if (conn_ == nullptr) {
1218         LOGE("%s", INVALID_CONNECTION);
1219         return DB_ERROR;
1220     }
1221     int errCode = conn_->SetReceiveDataInterceptor(interceptor);
1222     if (errCode != E_OK) {
1223         LOGE("[KvStoreNbDelegate] Set receive data interceptor errCode:%d", errCode);
1224     }
1225     LOGI("[KvStoreNbDelegate] Set receive data interceptor");
1226     return TransferDBErrno(errCode);
1227 }
1228 
SetCloudSyncConfig(const CloudSyncConfig & config)1229 DBStatus KvStoreNbDelegateImpl::SetCloudSyncConfig(const CloudSyncConfig &config)
1230 {
1231     if (conn_ == nullptr) {
1232         LOGE("%s", INVALID_CONNECTION);
1233         return DB_ERROR;
1234     }
1235     if (!DBCommon::CheckCloudSyncConfigValid(config)) {
1236         return INVALID_ARGS;
1237     }
1238     int errCode = conn_->SetCloudSyncConfig(config);
1239     if (errCode != E_OK) {
1240         LOGE("[KvStoreNbDelegate] Set cloud sync config errCode:%d", errCode);
1241     }
1242     LOGI("[KvStoreNbDelegate] Set cloud sync config");
1243     return TransferDBErrno(errCode);
1244 }
1245 
GetDeviceEntries(const std::string & device,std::vector<Entry> & entries) const1246 DBStatus KvStoreNbDelegateImpl::GetDeviceEntries(const std::string &device, std::vector<Entry> &entries) const
1247 {
1248     if (conn_ == nullptr) {
1249         LOGE("%s", INVALID_CONNECTION);
1250         return DB_ERROR;
1251     }
1252     int errCode = conn_->GetEntries(device, entries);
1253     if (errCode == E_OK) {
1254         return OK;
1255     }
1256     LOGE("[KvStoreNbDelegate] Get the entries failed:%d", errCode);
1257     return TransferDBErrno(errCode);
1258 }
1259 
GetDatabaseStatus() const1260 KvStoreNbDelegate::DatabaseStatus KvStoreNbDelegateImpl::GetDatabaseStatus() const
1261 {
1262     KvStoreNbDelegate::DatabaseStatus status;
1263     if (conn_ == nullptr) {
1264         LOGE("%s", INVALID_CONNECTION);
1265         return status;
1266     }
1267     status.isRebuild = conn_->IsRebuild();
1268     LOGI("[KvStoreNbDelegate] rebuild %d", static_cast<int>(status.isRebuild));
1269     return status;
1270 }
1271 } // namespace DistributedDB
1272