• 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     if (device.empty() || device.length() > DBConstant::MAX_DEV_LENGTH) {
455         return INVALID_ARGS;
456     }
457     int errCode = conn_->Pragma(PRAGMA_RM_DEVICE_DATA,
458         const_cast<void *>(static_cast<const void *>(&device)));
459     if (errCode != E_OK) {
460         LOGE("[KvStoreNbDelegate] Remove device data failed:%d", errCode);
461         return TransferDBErrno(errCode);
462     }
463     return OK;
464 }
465 
GetStoreId() const466 std::string KvStoreNbDelegateImpl::GetStoreId() const
467 {
468     return storeId_;
469 }
470 
Sync(const std::vector<std::string> & devices,SyncMode mode,const std::function<void (const std::map<std::string,DBStatus> & devicesMap)> & onComplete,bool wait=false)471 DBStatus KvStoreNbDelegateImpl::Sync(const std::vector<std::string> &devices, SyncMode mode,
472     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete,
473     bool wait = false)
474 {
475     if (conn_ == nullptr) {
476         LOGE("%s", INVALID_CONNECTION.c_str());
477         return DB_ERROR;
478     }
479 
480     PragmaSync pragmaData(devices, mode, std::bind(&KvStoreNbDelegateImpl::OnSyncComplete,
481         this, std::placeholders::_1, onComplete), wait);
482     int errCode = conn_->Pragma(PRAGMA_SYNC_DEVICES, &pragmaData);
483     if (errCode < E_OK) {
484         LOGE("[KvStoreNbDelegate] Sync data failed:%d", errCode);
485         return TransferDBErrno(errCode);
486     }
487     return OK;
488 }
489 
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)490 DBStatus KvStoreNbDelegateImpl::Sync(const std::vector<std::string> &devices, SyncMode mode,
491     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete,
492     const Query &query, bool wait)
493 {
494     if (conn_ == nullptr) {
495         LOGE("%s", INVALID_CONNECTION.c_str());
496         return DB_ERROR;
497     }
498 
499     QuerySyncObject querySyncObj(query);
500     if (querySyncObj.GetSortType() != SortType::NONE) {
501         LOGE("not support order by timestamp");
502         return NOT_SUPPORT;
503     }
504     PragmaSync pragmaData(devices, mode, querySyncObj, std::bind(&KvStoreNbDelegateImpl::OnSyncComplete,
505         this, std::placeholders::_1, onComplete), wait);
506     int errCode = conn_->Pragma(PRAGMA_SYNC_DEVICES, &pragmaData);
507     if (errCode < E_OK) {
508         LOGE("[KvStoreNbDelegate] QuerySync data failed:%d", errCode);
509         return TransferDBErrno(errCode);
510     }
511     return OK;
512 }
513 
Pragma(PragmaCmd cmd,PragmaData & paramData)514 DBStatus KvStoreNbDelegateImpl::Pragma(PragmaCmd cmd, PragmaData &paramData)
515 {
516     if (conn_ == nullptr) {
517         LOGE("%s", INVALID_CONNECTION.c_str());
518         return DB_ERROR;
519     }
520 
521     int errCode = -E_NOT_SUPPORT;
522     for (const auto &item : g_pragmaMap) {
523         if (item.externCmd == cmd) {
524             errCode = conn_->Pragma(item.innerCmd, paramData);
525             break;
526         }
527     }
528 
529     if (errCode != E_OK) {
530         LOGE("[KvStoreNbDelegate] Pragma failed:%d", errCode);
531         return TransferDBErrno(errCode);
532     }
533     return OK;
534 }
535 
SetConflictNotifier(int conflictType,const KvStoreNbConflictNotifier & notifier)536 DBStatus KvStoreNbDelegateImpl::SetConflictNotifier(int conflictType, const KvStoreNbConflictNotifier &notifier)
537 {
538     if (conn_ == nullptr) {
539         LOGE("%s", INVALID_CONNECTION.c_str());
540         return DB_ERROR;
541     }
542 
543     if (!ParamCheckUtils::CheckConflictNotifierType(conflictType)) {
544         LOGE("%s", INVALID_CONNECTION.c_str());
545         return INVALID_ARGS;
546     }
547 
548     int errCode;
549     if (!notifier) {
550         errCode = conn_->SetConflictNotifier(conflictType, nullptr);
551         goto END;
552     }
553 
554     errCode = conn_->SetConflictNotifier(conflictType,
555         [conflictType, notifier](const KvDBCommitNotifyData &data) {
556             int resultCode;
557             const std::list<KvDBConflictEntry> entries = data.GetCommitConflicts(resultCode);
558             if (resultCode != E_OK) {
559                 LOGE("Get commit conflicted entries failed:%d!", resultCode);
560                 return;
561             }
562 
563             for (const auto &entry : entries) {
564                 // Prohibit signed numbers to perform bit operations
565                 uint32_t entryType = static_cast<uint32_t>(entry.type);
566                 uint32_t type = static_cast<uint32_t>(conflictType);
567                 if (entryType & type) {
568                     KvStoreNbConflictDataImpl dataImpl;
569                     dataImpl.SetConflictData(entry);
570                     notifier(dataImpl);
571                 }
572             }
573         });
574 
575 END:
576     if (errCode != E_OK) {
577         LOGE("[KvStoreNbDelegate] Register conflict failed:%d!", errCode);
578         return TransferDBErrno(errCode);
579     }
580     return OK;
581 }
582 
Rekey(const CipherPassword & password)583 DBStatus KvStoreNbDelegateImpl::Rekey(const CipherPassword &password)
584 {
585     if (conn_ == nullptr) {
586         LOGE("%s", INVALID_CONNECTION.c_str());
587         return DB_ERROR;
588     }
589 
590     int errCode = conn_->Rekey(password);
591     if (errCode == E_OK) {
592         return OK;
593     }
594 
595     LOGE("[KvStoreNbDelegate] Rekey failed:%d", errCode);
596     return TransferDBErrno(errCode);
597 }
598 
Export(const std::string & filePath,const CipherPassword & passwd,bool force)599 DBStatus KvStoreNbDelegateImpl::Export(const std::string &filePath, const CipherPassword &passwd, bool force)
600 {
601     if (conn_ == nullptr) {
602         LOGE("%s", INVALID_CONNECTION.c_str());
603         return DB_ERROR;
604     }
605 
606     std::string fileDir;
607     std::string fileName;
608     OS::SplitFilePath(filePath, fileDir, fileName);
609 
610     std::string canonicalUrl;
611     if (!ParamCheckUtils::CheckDataDir(fileDir, canonicalUrl)) {
612         return INVALID_ARGS;
613     }
614 
615     if (!OS::CheckPathExistence(canonicalUrl)) {
616         return NO_PERMISSION;
617     }
618 
619     canonicalUrl = canonicalUrl + "/" + fileName;
620     if (!force && OS::CheckPathExistence(canonicalUrl)) {
621         return FILE_ALREADY_EXISTED;
622     }
623 
624     int errCode = conn_->Export(canonicalUrl, passwd);
625     if (errCode == E_OK) {
626         return OK;
627     }
628     LOGE("[KvStoreNbDelegate] Export failed:%d", errCode);
629     return TransferDBErrno(errCode);
630 }
631 
Import(const std::string & filePath,const CipherPassword & passwd)632 DBStatus KvStoreNbDelegateImpl::Import(const std::string &filePath, const CipherPassword &passwd)
633 {
634     if (conn_ == nullptr) {
635         LOGE("%s", INVALID_CONNECTION.c_str());
636         return DB_ERROR;
637     }
638 
639     std::string fileDir;
640     std::string fileName;
641     OS::SplitFilePath(filePath, fileDir, fileName);
642 
643     std::string canonicalUrl;
644     if (!ParamCheckUtils::CheckDataDir(fileDir, canonicalUrl)) {
645         return INVALID_ARGS;
646     }
647 
648     canonicalUrl = canonicalUrl + "/" + fileName;
649     if (!OS::CheckPathExistence(canonicalUrl)) {
650         LOGE("Import file path err, DBStatus = INVALID_FILE errno = [%d]", errno);
651         return INVALID_FILE;
652     }
653 
654     int errCode = conn_->Import(canonicalUrl, passwd);
655     if (errCode == E_OK) {
656         LOGI("[KvStoreNbDelegate] Import ok");
657         return OK;
658     }
659 
660     LOGE("[KvStoreNbDelegate] Import failed:%d", errCode);
661     return TransferDBErrno(errCode);
662 }
663 
StartTransaction()664 DBStatus KvStoreNbDelegateImpl::StartTransaction()
665 {
666     if (conn_ == nullptr) {
667         LOGE("%s", INVALID_CONNECTION.c_str());
668         return DB_ERROR;
669     }
670 
671     int errCode = conn_->StartTransaction();
672     if (errCode != E_OK) {
673         LOGE("[KvStoreNbDelegate] StartTransaction failed:%d", errCode);
674         return TransferDBErrno(errCode);
675     }
676     return OK;
677 }
678 
Commit()679 DBStatus KvStoreNbDelegateImpl::Commit()
680 {
681     if (conn_ == nullptr) {
682         LOGE("%s", INVALID_CONNECTION.c_str());
683         return DB_ERROR;
684     }
685 
686     int errCode = conn_->Commit();
687     if (errCode != E_OK) {
688         LOGE("[KvStoreNbDelegate] Commit failed:%d", errCode);
689         return TransferDBErrno(errCode);
690     }
691     return OK;
692 }
693 
Rollback()694 DBStatus KvStoreNbDelegateImpl::Rollback()
695 {
696     if (conn_ == nullptr) {
697         LOGE("%s", INVALID_CONNECTION.c_str());
698         return DB_ERROR;
699     }
700 
701     int errCode = conn_->RollBack();
702     if (errCode != E_OK) {
703         LOGE("[KvStoreNbDelegate] Rollback failed:%d", errCode);
704         return TransferDBErrno(errCode);
705     }
706     return OK;
707 }
708 
SetReleaseFlag(bool flag)709 void KvStoreNbDelegateImpl::SetReleaseFlag(bool flag)
710 {
711     releaseFlag_ = flag;
712 }
713 
Close()714 DBStatus KvStoreNbDelegateImpl::Close()
715 {
716     if (conn_ != nullptr) {
717         int errCode = KvDBManager::ReleaseDatabaseConnection(conn_);
718         if (errCode == -E_BUSY) {
719             LOGI("[KvStoreNbDelegate] Busy for close");
720             return BUSY;
721         }
722 
723         LOGI("[KvStoreNbDelegateImpl] Database connection Close");
724         conn_ = nullptr;
725     }
726     return OK;
727 }
728 
CheckIntegrity() const729 DBStatus KvStoreNbDelegateImpl::CheckIntegrity() const
730 {
731     if (conn_ == nullptr) {
732         LOGE("%s", INVALID_CONNECTION.c_str());
733         return DB_ERROR;
734     }
735 
736     return TransferDBErrno(conn_->CheckIntegrity());
737 }
738 
GetSecurityOption(SecurityOption & option) const739 DBStatus KvStoreNbDelegateImpl::GetSecurityOption(SecurityOption &option) const
740 {
741     if (conn_ == nullptr) {
742         LOGE("%s", INVALID_CONNECTION.c_str());
743         return DB_ERROR;
744     }
745     return TransferDBErrno(conn_->GetSecurityOption(option.securityLabel, option.securityFlag));
746 }
747 
SetRemotePushFinishedNotify(const RemotePushFinishedNotifier & notifier)748 DBStatus KvStoreNbDelegateImpl::SetRemotePushFinishedNotify(const RemotePushFinishedNotifier &notifier)
749 {
750     if (conn_ == nullptr) {
751         LOGE("%s", INVALID_CONNECTION.c_str());
752         return DB_ERROR;
753     }
754 
755     PragmaRemotePushNotify notify(notifier);
756     int errCode = conn_->Pragma(PRAGMA_REMOTE_PUSH_FINISHED_NOTIFY, reinterpret_cast<void *>(&notify));
757     if (errCode != E_OK) {
758         LOGE("[KvStoreNbDelegate] Set remote push finished notify failed : %d", errCode);
759     }
760     return TransferDBErrno(errCode);
761 }
762 
GetInner(const IOption & option,const Key & key,Value & value) const763 DBStatus KvStoreNbDelegateImpl::GetInner(const IOption &option, const Key &key, Value &value) const
764 {
765     if (conn_ == nullptr) {
766         LOGE("%s", INVALID_CONNECTION.c_str());
767         return DB_ERROR;
768     }
769 
770     int errCode = conn_->Get(option, key, value);
771     if (errCode == E_OK) {
772         return OK;
773     }
774     LOGW("[KvStoreNbDelegate] Get the data failed:%d", errCode);
775     return TransferDBErrno(errCode);
776 }
777 
GetEntriesInner(const IOption & option,const Key & keyPrefix,std::vector<Entry> & entries) const778 DBStatus KvStoreNbDelegateImpl::GetEntriesInner(const IOption &option,
779     const Key &keyPrefix, std::vector<Entry> &entries) const
780 {
781     if (conn_ == nullptr) {
782         LOGE("%s", INVALID_CONNECTION.c_str());
783         return DB_ERROR;
784     }
785 
786     int errCode = conn_->GetEntries(option, keyPrefix, entries);
787     if (errCode == E_OK) {
788         return OK;
789     }
790     LOGW("[KvStoreNbDelegate] Get the batch data failed:%d", errCode);
791     return TransferDBErrno(errCode);
792 }
793 
PutInner(const IOption & option,const Key & key,const Value & value)794 DBStatus KvStoreNbDelegateImpl::PutInner(const IOption &option, const Key &key, const Value &value)
795 {
796     if (conn_ == nullptr) {
797         LOGE("%s", INVALID_CONNECTION.c_str());
798         return DB_ERROR;
799     }
800 
801     PerformanceAnalysis *performance = PerformanceAnalysis::GetInstance();
802     if (performance != nullptr) {
803         performance->StepTimeRecordStart(PT_TEST_RECORDS::RECORD_PUT_DATA);
804     }
805 
806     int errCode = conn_->Put(option, key, value);
807     if (performance != nullptr) {
808         performance->StepTimeRecordEnd(PT_TEST_RECORDS::RECORD_PUT_DATA);
809     }
810 
811     if (errCode == E_OK) {
812         return OK;
813     }
814     LOGE("[KvStoreNbDelegate] Put the data failed:%d", errCode);
815     return TransferDBErrno(errCode);
816 }
817 
DeleteInner(const IOption & option,const Key & key)818 DBStatus KvStoreNbDelegateImpl::DeleteInner(const IOption &option, const Key &key)
819 {
820     if (conn_ == nullptr) {
821         LOGE("%s", INVALID_CONNECTION.c_str());
822         return DB_ERROR;
823     }
824 
825     int errCode = conn_->Delete(option, key);
826     if (errCode == E_OK || errCode == -E_NOT_FOUND) {
827         return OK;
828     }
829 
830     LOGE("[KvStoreNbDelegate] Delete the data failed:%d", errCode);
831     return TransferDBErrno(errCode);
832 }
833 
OnSyncComplete(const std::map<std::string,int> & statuses,const std::function<void (const std::map<std::string,DBStatus> & devicesMap)> & onComplete) const834 void KvStoreNbDelegateImpl::OnSyncComplete(const std::map<std::string, int> &statuses,
835     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete) const
836 {
837     const auto &statusMap = SyncOperation::DBStatusTransMap();
838     std::map<std::string, DBStatus> result;
839     for (const auto &pair : statuses) {
840         DBStatus status = DB_ERROR;
841         auto iter = statusMap.find(pair.second);
842         if (iter != statusMap.end()) {
843             status = iter->second;
844         }
845         result.insert(std::pair<std::string, DBStatus>(pair.first, status));
846     }
847     if (onComplete) {
848         onComplete(result);
849     }
850 }
851 
SetEqualIdentifier(const std::string & identifier,const std::vector<std::string> & targets)852 DBStatus KvStoreNbDelegateImpl::SetEqualIdentifier(const std::string &identifier,
853     const std::vector<std::string> &targets)
854 {
855     if (conn_ == nullptr) {
856         LOGE("%s", INVALID_CONNECTION.c_str());
857         return DB_ERROR;
858     }
859 
860     PragmaSetEqualIdentifier pragma(identifier, targets);
861     int errCode = conn_->Pragma(PRAGMA_ADD_EQUAL_IDENTIFIER, reinterpret_cast<void *>(&pragma));
862     if (errCode != E_OK) {
863         LOGE("[KvStoreNbDelegate] Set store equal identifier failed : %d", errCode);
864     }
865 
866     return TransferDBErrno(errCode);
867 }
868 
SetPushDataInterceptor(const PushDataInterceptor & interceptor)869 DBStatus KvStoreNbDelegateImpl::SetPushDataInterceptor(const PushDataInterceptor &interceptor)
870 {
871     if (conn_ == nullptr) {
872         LOGE("%s", INVALID_CONNECTION.c_str());
873         return DB_ERROR;
874     }
875 
876     PushDataInterceptor notify = interceptor;
877     int errCode = conn_->Pragma(PRAGMA_INTERCEPT_SYNC_DATA, static_cast<void *>(&notify));
878     if (errCode != E_OK) {
879         LOGE("[KvStoreNbDelegate] Set data interceptor notify failed : %d", errCode);
880     }
881     return TransferDBErrno(errCode);
882 }
883 
SubscribeRemoteQuery(const std::vector<std::string> & devices,const std::function<void (const std::map<std::string,DBStatus> & devicesMap)> & onComplete,const Query & query,bool wait)884 DBStatus KvStoreNbDelegateImpl::SubscribeRemoteQuery(const std::vector<std::string> &devices,
885     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete,
886     const Query &query, bool wait)
887 {
888     if (conn_ == nullptr) {
889         LOGE("%s", INVALID_CONNECTION.c_str());
890         return DB_ERROR;
891     }
892 
893     QuerySyncObject querySyncObj(query);
894     if (querySyncObj.GetSortType() != SortType::NONE) {
895         LOGE("not support order by timestamp");
896         return NOT_SUPPORT;
897     }
898     PragmaSync pragmaData(devices, SyncModeType::SUBSCRIBE_QUERY, querySyncObj,
899         std::bind(&KvStoreNbDelegateImpl::OnSyncComplete, this, std::placeholders::_1, onComplete), wait);
900     int errCode = conn_->Pragma(PRAGMA_SUBSCRIBE_QUERY, &pragmaData);
901     if (errCode < E_OK) {
902         LOGE("[KvStoreNbDelegate] Subscribe remote data with query failed:%d", errCode);
903         return TransferDBErrno(errCode);
904     }
905     return OK;
906 }
907 
UnSubscribeRemoteQuery(const std::vector<std::string> & devices,const std::function<void (const std::map<std::string,DBStatus> & devicesMap)> & onComplete,const Query & query,bool wait)908 DBStatus KvStoreNbDelegateImpl::UnSubscribeRemoteQuery(const std::vector<std::string> &devices,
909     const std::function<void(const std::map<std::string, DBStatus> &devicesMap)> &onComplete,
910     const Query &query, bool wait)
911 {
912     if (conn_ == nullptr) {
913         LOGE("%s", INVALID_CONNECTION.c_str());
914         return DB_ERROR;
915     }
916 
917     QuerySyncObject querySyncObj(query);
918     if (querySyncObj.GetSortType() != SortType::NONE) {
919         LOGE("not support order by timestamp");
920         return NOT_SUPPORT;
921     }
922     PragmaSync pragmaData(devices, SyncModeType::UNSUBSCRIBE_QUERY, querySyncObj,
923         std::bind(&KvStoreNbDelegateImpl::OnSyncComplete, this, std::placeholders::_1, onComplete), wait);
924     int errCode = conn_->Pragma(PRAGMA_SUBSCRIBE_QUERY, &pragmaData);
925     if (errCode < E_OK) {
926         LOGE("[KvStoreNbDelegate] Unsubscribe remote data with query failed:%d", errCode);
927         return TransferDBErrno(errCode);
928     }
929     return OK;
930 }
931 
RemoveDeviceData()932 DBStatus KvStoreNbDelegateImpl::RemoveDeviceData()
933 {
934     if (conn_ == nullptr) {
935         LOGE("%s", INVALID_CONNECTION.c_str());
936         return DB_ERROR;
937     }
938 
939     std::string device; // Empty device for remove all device data
940     int errCode = conn_->Pragma(PRAGMA_RM_DEVICE_DATA,
941                                 const_cast<void *>(static_cast<const void *>(&device)));
942     if (errCode != E_OK) {
943         LOGE("[KvStoreNbDelegate] Remove device data failed:%d", errCode);
944     }
945     return TransferDBErrno(errCode);
946 }
947 
UpdateKey(const UpdateKeyCallback & callback)948 DBStatus KvStoreNbDelegateImpl::UpdateKey(const UpdateKeyCallback &callback)
949 {
950     if (conn_ == nullptr) {
951         LOGE("%s", INVALID_CONNECTION.c_str());
952         return DB_ERROR;
953     }
954     if (callback == nullptr) {
955         return INVALID_ARGS;
956     }
957     int errCode = conn_->UpdateKey(callback);
958     if (errCode == E_OK) {
959         LOGI("[KvStoreNbDelegate] update keys success");
960         return OK;
961     }
962     LOGW("[KvStoreNbDelegate] update keys failed:%d", errCode);
963     return TransferDBErrno(errCode);
964 }
965 } // namespace DistributedDB
966