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