• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "platform_specific.h"
22 #include "log_print.h"
23 #include "db_constant.h"
24 #include "db_errno.h"
25 #include "db_types.h"
26 #include "param_check_utils.h"
27 #include "store_types.h"
28 #include "kvdb_pragma.h"
29 #include "kvdb_manager.h"
30 #include "kv_store_errno.h"
31 #include "kv_store_observer.h"
32 #include "kv_store_changed_data_impl.h"
33 #include "kv_store_nb_conflict_data_impl.h"
34 #include "kv_store_result_set_impl.h"
35 #include "sync_operation.h"
36 #include "performance_analysis.h"
37 
38 namespace DistributedDB {
39 namespace {
40     struct PragmaCmdPair {
41         int externCmd = 0;
42         int innerCmd = 0;
43     };
44 
45     const PragmaCmdPair g_pragmaMap[] = {
46         {GET_DEVICE_IDENTIFIER_OF_ENTRY, PRAGMA_GET_DEVICE_IDENTIFIER_OF_ENTRY},
47         {AUTO_SYNC, PRAGMA_AUTO_SYNC},
48         {PERFORMANCE_ANALYSIS_GET_REPORT, PRAGMA_PERFORMANCE_ANALYSIS_GET_REPORT},
49         {PERFORMANCE_ANALYSIS_OPEN, PRAGMA_PERFORMANCE_ANALYSIS_OPEN},
50         {PERFORMANCE_ANALYSIS_CLOSE, PRAGMA_PERFORMANCE_ANALYSIS_CLOSE},
51         {PERFORMANCE_ANALYSIS_SET_REPORTFILENAME, PRAGMA_PERFORMANCE_ANALYSIS_SET_REPORTFILENAME},
52         {GET_IDENTIFIER_OF_DEVICE, PRAGMA_GET_IDENTIFIER_OF_DEVICE},
53         {GET_QUEUED_SYNC_SIZE, PRAGMA_GET_QUEUED_SYNC_SIZE},
54         {SET_QUEUED_SYNC_LIMIT, PRAGMA_SET_QUEUED_SYNC_LIMIT},
55         {GET_QUEUED_SYNC_LIMIT, PRAGMA_GET_QUEUED_SYNC_LIMIT},
56         {SET_WIPE_POLICY, PRAGMA_SET_WIPE_POLICY},
57         {RESULT_SET_CACHE_MODE, PRAGMA_RESULT_SET_CACHE_MODE},
58         {RESULT_SET_CACHE_MAX_SIZE, PRAGMA_RESULT_SET_CACHE_MAX_SIZE},
59         {SET_SYNC_RETRY, PRAGMA_SET_SYNC_RETRY},
60         {SET_MAX_LOG_LIMIT, PRAGMA_SET_MAX_LOG_LIMIT},
61         {EXEC_CHECKPOINT, PRAGMA_EXEC_CHECKPOINT},
62     };
63 
64     const std::string INVALID_CONNECTION = "[KvStoreNbDelegate] Invalid connection for operation";
65 }
66 
KvStoreNbDelegateImpl(IKvDBConnection * conn,const std::string & storeId)67 KvStoreNbDelegateImpl::KvStoreNbDelegateImpl(IKvDBConnection *conn, const std::string &storeId)
68     : conn_(conn),
69       storeId_(storeId),
70       releaseFlag_(false)
71 {}
72 
~KvStoreNbDelegateImpl()73 KvStoreNbDelegateImpl::~KvStoreNbDelegateImpl()
74 {
75     if (!releaseFlag_) {
76         LOGF("[KvStoreNbDelegate] Can't release directly");
77         return;
78     }
79 
80     conn_ = nullptr;
81 }
82 
Get(const Key & key,Value & value) const83 DBStatus KvStoreNbDelegateImpl::Get(const Key &key, Value &value) const
84 {
85     IOption option;
86     option.dataType = IOption::SYNC_DATA;
87     return GetInner(option, key, value);
88 }
89 
GetEntries(const Key & keyPrefix,std::vector<Entry> & entries) const90 DBStatus KvStoreNbDelegateImpl::GetEntries(const Key &keyPrefix, std::vector<Entry> &entries) const
91 {
92     IOption option;
93     option.dataType = IOption::SYNC_DATA;
94     return GetEntriesInner(option, keyPrefix, entries);
95 }
96 
GetEntries(const Key & keyPrefix,KvStoreResultSet * & resultSet) const97 DBStatus KvStoreNbDelegateImpl::GetEntries(const Key &keyPrefix, KvStoreResultSet *&resultSet) const
98 {
99     if (conn_ == nullptr) {
100         LOGE("%s", INVALID_CONNECTION.c_str());
101         return DB_ERROR;
102     }
103 
104     IOption option;
105     option.dataType = IOption::SYNC_DATA;
106     IKvDBResultSet *kvDbResultSet = nullptr;
107     int errCode = conn_->GetResultSet(option, keyPrefix, kvDbResultSet);
108     if (errCode == E_OK) {
109         resultSet = new (std::nothrow) KvStoreResultSetImpl(kvDbResultSet);
110         if (resultSet != nullptr) {
111             return OK;
112         }
113 
114         LOGE("[KvStoreNbDelegate] Alloc result set failed.");
115         conn_->ReleaseResultSet(kvDbResultSet);
116         kvDbResultSet = nullptr;
117         return DB_ERROR;
118     }
119 
120     LOGE("[KvStoreNbDelegate] Get result set failed: %d", errCode);
121     return TransferDBErrno(errCode);
122 }
123 
GetEntries(const Query & query,std::vector<Entry> & entries) const124 DBStatus KvStoreNbDelegateImpl::GetEntries(const Query &query, std::vector<Entry> &entries) const
125 {
126     IOption option;
127     option.dataType = IOption::SYNC_DATA;
128     if (conn_ != nullptr) {
129         int errCode = conn_->GetEntries(option, query, entries);
130         if (errCode == E_OK) {
131             return OK;
132         } else if (errCode == -E_NOT_FOUND) {
133             LOGD("[KvStoreNbDelegate] Not found the data by query");
134             return NOT_FOUND;
135         }
136 
137         LOGE("[KvStoreNbDelegate] Get the batch data by query err:%d", errCode);
138         return TransferDBErrno(errCode);
139     }
140 
141     LOGE("%s", INVALID_CONNECTION.c_str());
142     return DB_ERROR;
143 }
144 
GetEntries(const Query & query,KvStoreResultSet * & resultSet) const145 DBStatus KvStoreNbDelegateImpl::GetEntries(const Query &query, KvStoreResultSet *&resultSet) const
146 {
147     if (conn_ == nullptr) {
148         LOGE("%s", INVALID_CONNECTION.c_str());
149         return DB_ERROR;
150     }
151 
152     IOption option;
153     option.dataType = IOption::SYNC_DATA;
154     IKvDBResultSet *kvDbResultSet = nullptr;
155     int errCode = conn_->GetResultSet(option, query, kvDbResultSet);
156     if (errCode == E_OK) {
157         resultSet = new (std::nothrow) KvStoreResultSetImpl(kvDbResultSet);
158         if (resultSet != nullptr) {
159             return OK;
160         }
161 
162         LOGE("[KvStoreNbDelegate] Alloc result set failed.");
163         conn_->ReleaseResultSet(kvDbResultSet);
164         kvDbResultSet = nullptr;
165         return DB_ERROR;
166     }
167 
168     LOGE("[KvStoreNbDelegate] Get result set for query failed: %d", errCode);
169     return TransferDBErrno(errCode);
170 }
171 
GetCount(const Query & query,int & count) const172 DBStatus KvStoreNbDelegateImpl::GetCount(const Query &query, int &count) const
173 {
174     if (conn_ == nullptr) {
175         LOGE("%s", INVALID_CONNECTION.c_str());
176         return DB_ERROR;
177     }
178 
179     IOption option;
180     option.dataType = IOption::SYNC_DATA;
181     int errCode = conn_->GetCount(option, query, count);
182     if (errCode == E_OK) {
183         if (count == 0) {
184             return NOT_FOUND;
185         }
186         return OK;
187     }
188 
189     LOGE("[KvStoreNbDelegate] Get count for query failed: %d", errCode);
190     return TransferDBErrno(errCode);
191 }
192 
CloseResultSet(KvStoreResultSet * & resultSet)193 DBStatus KvStoreNbDelegateImpl::CloseResultSet(KvStoreResultSet *&resultSet)
194 {
195     if (resultSet == nullptr) {
196         return INVALID_ARGS;
197     }
198 
199     if (conn_ == nullptr) {
200         LOGE("%s", INVALID_CONNECTION.c_str());
201         return DB_ERROR;
202     }
203 
204     // release inner result set
205     IKvDBResultSet *kvDbResultSet = nullptr;
206     (static_cast<KvStoreResultSetImpl *>(resultSet))->GetResultSet(kvDbResultSet);
207     conn_->ReleaseResultSet(kvDbResultSet);
208     // release external result set
209     delete resultSet;
210     resultSet = nullptr;
211     return OK;
212 }
213 
Put(const Key & key,const Value & value)214 DBStatus KvStoreNbDelegateImpl::Put(const Key &key, const Value &value)
215 {
216     IOption option;
217     option.dataType = IOption::SYNC_DATA;
218     return PutInner(option, key, value);
219 }
220 
PutBatch(const std::vector<Entry> & entries)221 DBStatus KvStoreNbDelegateImpl::PutBatch(const std::vector<Entry> &entries)
222 {
223     if (conn_ != nullptr) {
224         IOption option;
225         option.dataType = IOption::SYNC_DATA;
226         int errCode = conn_->PutBatch(option, entries);
227         if (errCode == E_OK) {
228             return OK;
229         }
230 
231         LOGE("[KvStoreNbDelegate] Put batch data failed:%d", errCode);
232         return TransferDBErrno(errCode);
233     }
234 
235     LOGE("%s", INVALID_CONNECTION.c_str());
236     return DB_ERROR;
237 }
238 
DeleteBatch(const std::vector<Key> & keys)239 DBStatus KvStoreNbDelegateImpl::DeleteBatch(const std::vector<Key> &keys)
240 {
241     if (conn_ == nullptr) {
242         LOGE("%s", INVALID_CONNECTION.c_str());
243         return DB_ERROR;
244     }
245 
246     IOption option;
247     option.dataType = IOption::SYNC_DATA;
248     int errCode = conn_->DeleteBatch(option, keys);
249     if (errCode == E_OK || errCode == -E_NOT_FOUND) {
250         return OK;
251     }
252 
253     LOGE("[KvStoreNbDelegate] Delete batch data failed:%d", errCode);
254     return TransferDBErrno(errCode);
255 }
256 
Delete(const Key & key)257 DBStatus KvStoreNbDelegateImpl::Delete(const Key &key)
258 {
259     IOption option;
260     option.dataType = IOption::SYNC_DATA;
261     return DeleteInner(option, key);
262 }
263 
GetLocal(const Key & key,Value & value) const264 DBStatus KvStoreNbDelegateImpl::GetLocal(const Key &key, Value &value) const
265 {
266     IOption option;
267     option.dataType = IOption::LOCAL_DATA;
268     return GetInner(option, key, value);
269 }
270 
GetLocalEntries(const Key & keyPrefix,std::vector<Entry> & entries) const271 DBStatus KvStoreNbDelegateImpl::GetLocalEntries(const Key &keyPrefix, std::vector<Entry> &entries) const
272 {
273     IOption option;
274     option.dataType = IOption::LOCAL_DATA;
275     return GetEntriesInner(option, keyPrefix, entries);
276 }
277 
PutLocal(const Key & key,const Value & value)278 DBStatus KvStoreNbDelegateImpl::PutLocal(const Key &key, const Value &value)
279 {
280     IOption option;
281     option.dataType = IOption::LOCAL_DATA;
282     return PutInner(option, key, value);
283 }
284 
DeleteLocal(const Key & key)285 DBStatus KvStoreNbDelegateImpl::DeleteLocal(const Key &key)
286 {
287     IOption option;
288     option.dataType = IOption::LOCAL_DATA;
289     return DeleteInner(option, key);
290 }
291 
PublishLocal(const Key & key,bool deleteLocal,bool updateTimestamp,const KvStoreNbPublishOnConflict & onConflict)292 DBStatus KvStoreNbDelegateImpl::PublishLocal(const Key &key, bool deleteLocal, bool updateTimestamp,
293     const KvStoreNbPublishOnConflict &onConflict)
294 {
295     if (key.empty() || key.size() > DBConstant::MAX_KEY_SIZE) {
296         LOGW("[KvStoreNbDelegate][Publish] Invalid para");
297         return INVALID_ARGS;
298     }
299 
300     if (conn_ != nullptr) {
301         PragmaPublishInfo publishInfo{ key, deleteLocal, updateTimestamp, onConflict };
302         int errCode = conn_->Pragma(PRAGMA_PUBLISH_LOCAL, static_cast<PragmaData>(&publishInfo));
303         if (errCode != E_OK) {
304             LOGD("[KvStoreNbDelegate] Publish local err:%d", errCode);
305             return TransferDBErrno(errCode);
306         }
307         return OK;
308     }
309 
310     LOGE("%s", INVALID_CONNECTION.c_str());
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             LOGD("[KvStoreNbDelegate] Unpublish result:%d", errCode);
326             return TransferDBErrno(errCode);
327         }
328         return OK;
329     }
330 
331     LOGE("%s", INVALID_CONNECTION.c_str());
332     return DB_ERROR;
333 }
334 
PutLocalBatch(const std::vector<Entry> & entries)335 DBStatus KvStoreNbDelegateImpl::PutLocalBatch(const std::vector<Entry> &entries)
336 {
337     if (conn_ == nullptr) {
338         LOGE("%s", INVALID_CONNECTION.c_str());
339         return DB_ERROR;
340     }
341 
342     IOption option;
343     option.dataType = IOption::LOCAL_DATA;
344     int errCode = conn_->PutBatch(option, entries);
345     if (errCode != E_OK) {
346         LOGE("[KvStoreNbDelegate] Put local batch data failed:%d", errCode);
347         return TransferDBErrno(errCode);
348     }
349 
350     return OK;
351 }
352 
DeleteLocalBatch(const std::vector<Key> & keys)353 DBStatus KvStoreNbDelegateImpl::DeleteLocalBatch(const std::vector<Key> &keys)
354 {
355     if (conn_ == nullptr) {
356         LOGE("%s", INVALID_CONNECTION.c_str());
357         return DB_ERROR;
358     }
359 
360     IOption option;
361     option.dataType = IOption::LOCAL_DATA;
362     int errCode = conn_->DeleteBatch(option, keys);
363     if (errCode == E_OK || errCode == -E_NOT_FOUND) {
364         return OK;
365     }
366 
367     LOGE("[KvStoreNbDelegate] Delete local batch data failed:%d", errCode);
368     return TransferDBErrno(errCode);
369 }
370 
RegisterObserver(const Key & key,unsigned int mode,KvStoreObserver * observer)371 DBStatus KvStoreNbDelegateImpl::RegisterObserver(const Key &key, unsigned int mode, KvStoreObserver *observer)
372 {
373     if (key.size() > DBConstant::MAX_KEY_SIZE) {
374         return INVALID_ARGS;
375     }
376 
377     if (!ParamCheckUtils::CheckObserver(key, mode)) {
378         LOGE("Register nb observer by illegal mode or key size!");
379         return INVALID_ARGS;
380     }
381 
382     if (observer == nullptr) {
383         return INVALID_ARGS;
384     }
385 
386     std::lock_guard<std::mutex> lockGuard(observerMapLock_);
387     if (observerMap_.find(observer) != observerMap_.end()) {
388         LOGE("[KvStoreNbDelegate] Observer has been already registered!");
389         return DB_ERROR;
390     }
391 
392     if (conn_ == nullptr) {
393         LOGE("%s", INVALID_CONNECTION.c_str());
394         return DB_ERROR;
395     }
396 
397     if (conn_->IsTransactionStarted()) {
398         return BUSY;
399     }
400 
401     int errCode = E_OK;
402     KvDBObserverHandle *observerHandle = conn_->RegisterObserver(
403         mode, key,
404         [observer](const KvDBCommitNotifyData &notifyData) {
405             KvStoreChangedDataImpl data(&notifyData);
406             observer->OnChange(data);
407         },
408         errCode);
409 
410     if (errCode != E_OK || observerHandle == nullptr) {
411         LOGE("[KvStoreNbDelegate] RegisterListener failed:%d!", errCode);
412         return DB_ERROR;
413     }
414 
415     observerMap_.insert(std::pair<const KvStoreObserver *, const KvDBObserverHandle *>(observer, observerHandle));
416     LOGI("[KvStoreNbDelegate] RegisterObserver ok mode:%u", mode);
417     return OK;
418 }
419 
UnRegisterObserver(const KvStoreObserver * observer)420 DBStatus KvStoreNbDelegateImpl::UnRegisterObserver(const KvStoreObserver *observer)
421 {
422     if (observer == nullptr) {
423         return INVALID_ARGS;
424     }
425 
426     if (conn_ == nullptr) {
427         LOGE("%s", INVALID_CONNECTION.c_str());
428         return DB_ERROR;
429     }
430 
431     std::lock_guard<std::mutex> lockGuard(observerMapLock_);
432     auto iter = observerMap_.find(observer);
433     if (iter == observerMap_.end()) {
434         LOGE("[KvStoreNbDelegate] Observer has not been registered!");
435         return NOT_FOUND;
436     }
437 
438     const KvDBObserverHandle *observerHandle = iter->second;
439     int errCode = conn_->UnRegisterObserver(observerHandle);
440     if (errCode != E_OK) {
441         LOGE("[KvStoreNbDelegate] UnRegistObserver failed:%d!", errCode);
442         return DB_ERROR;
443     }
444     observerMap_.erase(iter);
445     return OK;
446 }
447 
RemoveDeviceData(const std::string & device)448 DBStatus KvStoreNbDelegateImpl::RemoveDeviceData(const std::string &device)
449 {
450     if (conn_ == nullptr) {
451         LOGE("%s", INVALID_CONNECTION.c_str());
452         return DB_ERROR;
453     }
454 
455     int errCode = conn_->Pragma(PRAGMA_RM_DEVICE_DATA,
456         const_cast<void *>(static_cast<const void *>(&device)));
457     if (errCode != E_OK) {
458         LOGE("[KvStoreNbDelegate] Remove device data failed:%d", errCode);
459         return TransferDBErrno(errCode);
460     }
461     return OK;
462 }
463 
GetStoreId() const464 std::string KvStoreNbDelegateImpl::GetStoreId() const
465 {
466     return storeId_;
467 }
468 
Sync(const std::vector<std::string> & devices,SyncMode mode,const std::function<void (const std::map<std::string,DBStatus> & devicesMap)> & onComplete,bool wait=false)469 DBStatus KvStoreNbDelegateImpl::Sync(const std::vector<std::string> &devices, SyncMode mode,
470     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete,
471     bool wait = false)
472 {
473     if (conn_ == nullptr) {
474         LOGE("%s", INVALID_CONNECTION.c_str());
475         return DB_ERROR;
476     }
477 
478     PragmaSync pragmaData(devices, mode, std::bind(&KvStoreNbDelegateImpl::OnSyncComplete,
479         this, std::placeholders::_1, onComplete), wait);
480     int errCode = conn_->Pragma(PRAGMA_SYNC_DEVICES, &pragmaData);
481     if (errCode < E_OK) {
482         LOGE("[KvStoreNbDelegate] Sync data failed:%d", errCode);
483         return TransferDBErrno(errCode);
484     }
485     return OK;
486 }
487 
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)488 DBStatus KvStoreNbDelegateImpl::Sync(const std::vector<std::string> &devices, SyncMode mode,
489     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete,
490     const Query &query, bool wait)
491 {
492     if (conn_ == nullptr) {
493         LOGE("%s", INVALID_CONNECTION.c_str());
494         return DB_ERROR;
495     }
496 
497     QuerySyncObject querySyncObj(query);
498     if (querySyncObj.GetSortType() != SortType::NONE) {
499         LOGE("not support order by timestamp");
500         return NOT_SUPPORT;
501     }
502     PragmaSync pragmaData(devices, mode, querySyncObj, std::bind(&KvStoreNbDelegateImpl::OnSyncComplete,
503         this, std::placeholders::_1, onComplete), wait);
504     int errCode = conn_->Pragma(PRAGMA_SYNC_DEVICES, &pragmaData);
505     if (errCode < E_OK) {
506         LOGE("[KvStoreNbDelegate] QuerySync data failed:%d", errCode);
507         return TransferDBErrno(errCode);
508     }
509     return OK;
510 }
511 
Pragma(PragmaCmd cmd,PragmaData & paramData)512 DBStatus KvStoreNbDelegateImpl::Pragma(PragmaCmd cmd, PragmaData &paramData)
513 {
514     if (conn_ == nullptr) {
515         LOGE("%s", INVALID_CONNECTION.c_str());
516         return DB_ERROR;
517     }
518 
519     int errCode = -E_NOT_SUPPORT;
520     for (const auto &item : g_pragmaMap) {
521         if (item.externCmd == cmd) {
522             errCode = conn_->Pragma(item.innerCmd, paramData);
523             break;
524         }
525     }
526 
527     if (errCode != E_OK) {
528         LOGE("[KvStoreNbDelegate] Pragma failed:%d", errCode);
529         return TransferDBErrno(errCode);
530     }
531     return OK;
532 }
533 
SetConflictNotifier(int conflictType,const KvStoreNbConflictNotifier & notifier)534 DBStatus KvStoreNbDelegateImpl::SetConflictNotifier(int conflictType, const KvStoreNbConflictNotifier &notifier)
535 {
536     if (conn_ == nullptr) {
537         LOGE("%s", INVALID_CONNECTION.c_str());
538         return DB_ERROR;
539     }
540 
541     if (!ParamCheckUtils::CheckConflictNotifierType(conflictType)) {
542         LOGE("%s", INVALID_CONNECTION.c_str());
543         return INVALID_ARGS;
544     }
545 
546     int errCode;
547     if (!notifier) {
548         errCode = conn_->SetConflictNotifier(conflictType, nullptr);
549         goto END;
550     }
551 
552     errCode = conn_->SetConflictNotifier(conflictType,
553         [conflictType, notifier](const KvDBCommitNotifyData &data) {
554             int resultCode;
555             const std::list<KvDBConflictEntry> entries = data.GetCommitConflicts(resultCode);
556             if (resultCode != E_OK) {
557                 LOGE("Get commit conflicted entries failed:%d!", resultCode);
558                 return;
559             }
560 
561             for (const auto &entry : entries) {
562                 // Prohibit signed numbers to perform bit operations
563                 uint32_t entryType = static_cast<uint32_t>(entry.type);
564                 uint32_t type = static_cast<uint32_t>(conflictType);
565                 if (entryType & type) {
566                     KvStoreNbConflictDataImpl dataImpl;
567                     dataImpl.SetConflictData(entry);
568                     notifier(dataImpl);
569                 }
570             }
571         });
572 
573 END:
574     if (errCode != E_OK) {
575         LOGE("[KvStoreNbDelegate] Register conflict failed:%d!", errCode);
576         return TransferDBErrno(errCode);
577     }
578     return OK;
579 }
580 
Rekey(const CipherPassword & password)581 DBStatus KvStoreNbDelegateImpl::Rekey(const CipherPassword &password)
582 {
583     if (conn_ == nullptr) {
584         LOGE("%s", INVALID_CONNECTION.c_str());
585         return DB_ERROR;
586     }
587 
588     int errCode = conn_->Rekey(password);
589     if (errCode == E_OK) {
590         return OK;
591     }
592 
593     LOGE("[KvStoreNbDelegate] Rekey failed:%d", errCode);
594     return TransferDBErrno(errCode);
595 }
596 
Export(const std::string & filePath,const CipherPassword & passwd,bool force)597 DBStatus KvStoreNbDelegateImpl::Export(const std::string &filePath, const CipherPassword &passwd, bool force)
598 {
599     if (conn_ == nullptr) {
600         LOGE("%s", INVALID_CONNECTION.c_str());
601         return DB_ERROR;
602     }
603 
604     std::string fileDir;
605     std::string fileName;
606     OS::SplitFilePath(filePath, fileDir, fileName);
607 
608     std::string canonicalUrl;
609     if (!ParamCheckUtils::CheckDataDir(fileDir, canonicalUrl)) {
610         return INVALID_ARGS;
611     }
612 
613     if (!OS::CheckPathExistence(canonicalUrl)) {
614         return NO_PERMISSION;
615     }
616 
617     canonicalUrl = canonicalUrl + "/" + fileName;
618     if (!force && OS::CheckPathExistence(canonicalUrl)) {
619         return FILE_ALREADY_EXISTED;
620     }
621 
622     int errCode = conn_->Export(canonicalUrl, passwd);
623     if (errCode == E_OK) {
624         return OK;
625     }
626     LOGE("[KvStoreNbDelegate] Export failed:%d", errCode);
627     return TransferDBErrno(errCode);
628 }
629 
Import(const std::string & filePath,const CipherPassword & passwd)630 DBStatus KvStoreNbDelegateImpl::Import(const std::string &filePath, const CipherPassword &passwd)
631 {
632     if (conn_ == nullptr) {
633         LOGE("%s", INVALID_CONNECTION.c_str());
634         return DB_ERROR;
635     }
636 
637     std::string fileDir;
638     std::string fileName;
639     OS::SplitFilePath(filePath, fileDir, fileName);
640 
641     std::string canonicalUrl;
642     if (!ParamCheckUtils::CheckDataDir(fileDir, canonicalUrl)) {
643         return INVALID_ARGS;
644     }
645 
646     canonicalUrl = canonicalUrl + "/" + fileName;
647     if (!OS::CheckPathExistence(canonicalUrl)) {
648         LOGE("Import file path err, DBStatus = INVALID_FILE errno = [%d]", errno);
649         return INVALID_FILE;
650     }
651 
652     int errCode = conn_->Import(canonicalUrl, passwd);
653     if (errCode == E_OK) {
654         LOGI("[KvStoreNbDelegate] Import ok");
655         return OK;
656     }
657 
658     LOGE("[KvStoreNbDelegate] Import failed:%d", errCode);
659     return TransferDBErrno(errCode);
660 }
661 
StartTransaction()662 DBStatus KvStoreNbDelegateImpl::StartTransaction()
663 {
664     if (conn_ == nullptr) {
665         LOGE("%s", INVALID_CONNECTION.c_str());
666         return DB_ERROR;
667     }
668 
669     int errCode = conn_->StartTransaction();
670     if (errCode != E_OK) {
671         LOGE("[KvStoreNbDelegate] StartTransaction failed:%d", errCode);
672         return TransferDBErrno(errCode);
673     }
674     return OK;
675 }
676 
Commit()677 DBStatus KvStoreNbDelegateImpl::Commit()
678 {
679     if (conn_ == nullptr) {
680         LOGE("%s", INVALID_CONNECTION.c_str());
681         return DB_ERROR;
682     }
683 
684     int errCode = conn_->Commit();
685     if (errCode != E_OK) {
686         LOGE("[KvStoreNbDelegate] Commit failed:%d", errCode);
687         return TransferDBErrno(errCode);
688     }
689     return OK;
690 }
691 
Rollback()692 DBStatus KvStoreNbDelegateImpl::Rollback()
693 {
694     if (conn_ == nullptr) {
695         LOGE("%s", INVALID_CONNECTION.c_str());
696         return DB_ERROR;
697     }
698 
699     int errCode = conn_->RollBack();
700     if (errCode != E_OK) {
701         LOGE("[KvStoreNbDelegate] Rollback failed:%d", errCode);
702         return TransferDBErrno(errCode);
703     }
704     return OK;
705 }
706 
SetReleaseFlag(bool flag)707 void KvStoreNbDelegateImpl::SetReleaseFlag(bool flag)
708 {
709     releaseFlag_ = flag;
710 }
711 
Close()712 DBStatus KvStoreNbDelegateImpl::Close()
713 {
714     if (conn_ != nullptr) {
715         int errCode = KvDBManager::ReleaseDatabaseConnection(conn_);
716         if (errCode == -E_BUSY) {
717             LOGI("[KvStoreNbDelegate] Busy for close");
718             return BUSY;
719         }
720 
721         LOGI("[KvStoreNbDelegateImpl] Database connection Close");
722         conn_ = nullptr;
723     }
724     return OK;
725 }
726 
CheckIntegrity() const727 DBStatus KvStoreNbDelegateImpl::CheckIntegrity() const
728 {
729     if (conn_ == nullptr) {
730         LOGE("%s", INVALID_CONNECTION.c_str());
731         return DB_ERROR;
732     }
733 
734     return TransferDBErrno(conn_->CheckIntegrity());
735 }
736 
GetSecurityOption(SecurityOption & option) const737 DBStatus KvStoreNbDelegateImpl::GetSecurityOption(SecurityOption &option) const
738 {
739     if (conn_ == nullptr) {
740         LOGE("%s", INVALID_CONNECTION.c_str());
741         return DB_ERROR;
742     }
743     return TransferDBErrno(conn_->GetSecurityOption(option.securityLabel, option.securityFlag));
744 }
745 
SetRemotePushFinishedNotify(const RemotePushFinishedNotifier & notifier)746 DBStatus KvStoreNbDelegateImpl::SetRemotePushFinishedNotify(const RemotePushFinishedNotifier &notifier)
747 {
748     if (conn_ == nullptr) {
749         LOGE("%s", INVALID_CONNECTION.c_str());
750         return DB_ERROR;
751     }
752 
753     PragmaRemotePushNotify notify(notifier);
754     int errCode = conn_->Pragma(PRAGMA_REMOTE_PUSH_FINISHED_NOTIFY, reinterpret_cast<void *>(&notify));
755     if (errCode != E_OK) {
756         LOGE("[KvStoreNbDelegate] Set remote push finished notify failed : %d", errCode);
757     }
758     return TransferDBErrno(errCode);
759 }
760 
GetInner(const IOption & option,const Key & key,Value & value) const761 DBStatus KvStoreNbDelegateImpl::GetInner(const IOption &option, const Key &key, Value &value) const
762 {
763     if (conn_ == nullptr) {
764         LOGE("%s", INVALID_CONNECTION.c_str());
765         return DB_ERROR;
766     }
767 
768     int errCode = conn_->Get(option, key, value);
769     if (errCode == E_OK) {
770         return OK;
771     }
772     LOGW("[KvStoreNbDelegate] Get the data failed:%d", errCode);
773     return TransferDBErrno(errCode);
774 }
775 
GetEntriesInner(const IOption & option,const Key & keyPrefix,std::vector<Entry> & entries) const776 DBStatus KvStoreNbDelegateImpl::GetEntriesInner(const IOption &option,
777     const Key &keyPrefix, std::vector<Entry> &entries) const
778 {
779     if (conn_ == nullptr) {
780         LOGE("%s", INVALID_CONNECTION.c_str());
781         return DB_ERROR;
782     }
783 
784     int errCode = conn_->GetEntries(option, keyPrefix, entries);
785     if (errCode == E_OK) {
786         return OK;
787     }
788     LOGW("[KvStoreNbDelegate] Get the batch data failed:%d", errCode);
789     return TransferDBErrno(errCode);
790 }
791 
PutInner(const IOption & option,const Key & key,const Value & value)792 DBStatus KvStoreNbDelegateImpl::PutInner(const IOption &option, const Key &key, const Value &value)
793 {
794     if (conn_ == nullptr) {
795         LOGE("%s", INVALID_CONNECTION.c_str());
796         return DB_ERROR;
797     }
798 
799     PerformanceAnalysis *performance = PerformanceAnalysis::GetInstance();
800     if (performance != nullptr) {
801         performance->StepTimeRecordStart(PT_TEST_RECORDS::RECORD_PUT_DATA);
802     }
803 
804     int errCode = conn_->Put(option, key, value);
805     if (performance != nullptr) {
806         performance->StepTimeRecordEnd(PT_TEST_RECORDS::RECORD_PUT_DATA);
807     }
808 
809     if (errCode == E_OK) {
810         return OK;
811     }
812     LOGE("[KvStoreNbDelegate] Put the data failed:%d", errCode);
813     return TransferDBErrno(errCode);
814 }
815 
DeleteInner(const IOption & option,const Key & key)816 DBStatus KvStoreNbDelegateImpl::DeleteInner(const IOption &option, const Key &key)
817 {
818     if (conn_ == nullptr) {
819         LOGE("%s", INVALID_CONNECTION.c_str());
820         return DB_ERROR;
821     }
822 
823     int errCode = conn_->Delete(option, key);
824     if (errCode == E_OK || errCode == -E_NOT_FOUND) {
825         return OK;
826     }
827 
828     LOGE("[KvStoreNbDelegate] Delete the data failed:%d", errCode);
829     return TransferDBErrno(errCode);
830 }
831 
OnSyncComplete(const std::map<std::string,int> & statuses,const std::function<void (const std::map<std::string,DBStatus> & devicesMap)> & onComplete) const832 void KvStoreNbDelegateImpl::OnSyncComplete(const std::map<std::string, int> &statuses,
833     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete) const
834 {
835     const auto &statusMap = SyncOperation::DBStatusTransMap();
836     std::map<std::string, DBStatus> result;
837     for (const auto &pair : statuses) {
838         DBStatus status = DB_ERROR;
839         auto iter = statusMap.find(pair.second);
840         if (iter != statusMap.end()) {
841             status = iter->second;
842         }
843         result.insert(std::pair<std::string, DBStatus>(pair.first, status));
844     }
845     if (onComplete) {
846         onComplete(result);
847     }
848 }
849 
SetEqualIdentifier(const std::string & identifier,const std::vector<std::string> & targets)850 DBStatus KvStoreNbDelegateImpl::SetEqualIdentifier(const std::string &identifier,
851     const std::vector<std::string> &targets)
852 {
853     if (conn_ == nullptr) {
854         LOGE("%s", INVALID_CONNECTION.c_str());
855         return DB_ERROR;
856     }
857 
858     PragmaSetEqualIdentifier pragma(identifier, targets);
859     int errCode = conn_->Pragma(PRAGMA_ADD_EQUAL_IDENTIFIER, reinterpret_cast<void *>(&pragma));
860     if (errCode != E_OK) {
861         LOGE("[KvStoreNbDelegate] Set store equal identifier failed : %d", errCode);
862     }
863 
864     return TransferDBErrno(errCode);
865 }
866 
SetPushDataInterceptor(const PushDataInterceptor & interceptor)867 DBStatus KvStoreNbDelegateImpl::SetPushDataInterceptor(const PushDataInterceptor &interceptor)
868 {
869     if (conn_ == nullptr) {
870         LOGE("%s", INVALID_CONNECTION.c_str());
871         return DB_ERROR;
872     }
873 
874     PushDataInterceptor notify = interceptor;
875     int errCode = conn_->Pragma(PRAGMA_INTERCEPT_SYNC_DATA, static_cast<void *>(&notify));
876     if (errCode != E_OK) {
877         LOGE("[KvStoreNbDelegate] Set data interceptor notify failed : %d", errCode);
878     }
879     return TransferDBErrno(errCode);
880 }
881 
SubscribeRemoteQuery(const std::vector<std::string> & devices,const std::function<void (const std::map<std::string,DBStatus> & devicesMap)> & onComplete,const Query & query,bool wait)882 DBStatus KvStoreNbDelegateImpl::SubscribeRemoteQuery(const std::vector<std::string> &devices,
883     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete,
884     const Query &query, bool wait)
885 {
886     if (conn_ == nullptr) {
887         LOGE("%s", INVALID_CONNECTION.c_str());
888         return DB_ERROR;
889     }
890 
891     QuerySyncObject querySyncObj(query);
892     if (querySyncObj.GetSortType() != SortType::NONE) {
893         LOGE("not support order by timestamp");
894         return NOT_SUPPORT;
895     }
896     PragmaSync pragmaData(devices, SyncModeType::SUBSCRIBE_QUERY, querySyncObj,
897         std::bind(&KvStoreNbDelegateImpl::OnSyncComplete, this, std::placeholders::_1, onComplete), wait);
898     int errCode = conn_->Pragma(PRAGMA_SUBSCRIBE_QUERY, &pragmaData);
899     if (errCode < E_OK) {
900         LOGE("[KvStoreNbDelegate] Subscribe remote data with query failed:%d", errCode);
901         return TransferDBErrno(errCode);
902     }
903     return OK;
904 }
905 
UnSubscribeRemoteQuery(const std::vector<std::string> & devices,const std::function<void (const std::map<std::string,DBStatus> & devicesMap)> & onComplete,const Query & query,bool wait)906 DBStatus KvStoreNbDelegateImpl::UnSubscribeRemoteQuery(const std::vector<std::string> &devices,
907     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete,
908     const Query &query, bool wait)
909 {
910     if (conn_ == nullptr) {
911         LOGE("%s", INVALID_CONNECTION.c_str());
912         return DB_ERROR;
913     }
914 
915     QuerySyncObject querySyncObj(query);
916     if (querySyncObj.GetSortType() != SortType::NONE) {
917         LOGE("not support order by timestamp");
918         return NOT_SUPPORT;
919     }
920     PragmaSync pragmaData(devices, SyncModeType::UNSUBSCRIBE_QUERY, querySyncObj,
921         std::bind(&KvStoreNbDelegateImpl::OnSyncComplete, this, std::placeholders::_1, onComplete), wait);
922     int errCode = conn_->Pragma(PRAGMA_SUBSCRIBE_QUERY, &pragmaData);
923     if (errCode < E_OK) {
924         LOGE("[KvStoreNbDelegate] Unsubscribe remote data with query failed:%d", errCode);
925         return TransferDBErrno(errCode);
926     }
927     return OK;
928 }
929 
RemoveDeviceData()930 DBStatus KvStoreNbDelegateImpl::RemoveDeviceData()
931 {
932     return OK;
933 }
934 } // namespace DistributedDB
935