• 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 "sqlite_single_ver_natural_store_connection.h"
17 
18 #include "db_constant.h"
19 #include "db_dfx_adapter.h"
20 #include "db_errno.h"
21 #include "log_print.h"
22 #include "kvdb_pragma.h"
23 #include "sqlite_single_ver_natural_store.h"
24 #include "kvdb_observer_handle.h"
25 #include "store_types.h"
26 #include "db_common.h"
27 #include "sqlite_single_ver_result_set.h"
28 #include "sqlite_single_ver_forward_cursor.h"
29 
30 namespace DistributedDB {
31 namespace {
32     enum class LocalOperType {
33         LOCAL_OPR_NONE = 0,
34         LOCAL_OPR_DEL = 1,
35         LOCAL_OPR_PUT = 2
36     };
37     const uint32_t MAX_AUTO_LIFE_CYCLE = 1800000; // half an hour.
38     const uint32_t MIN_AUTO_LIFE_CYCLE = 5000; // 5s.
39 }
40 
SQLiteSingleVerNaturalStoreConnection(SQLiteSingleVerNaturalStore * kvDB)41 SQLiteSingleVerNaturalStoreConnection::SQLiteSingleVerNaturalStoreConnection(SQLiteSingleVerNaturalStore *kvDB)
42     : SyncAbleKvDBConnection(kvDB),
43       cacheMaxSizeForNewResultSet_(DEFAULT_RESULT_SET_CACHE_MAX_SIZE),
44       conflictType_(0),
45       transactionEntrySize_(0),
46       currentMaxTimestamp_(0),
47       committedData_(nullptr),
48       localCommittedData_(nullptr),
49       transactionExeFlag_(false),
50       conflictListener_(nullptr),
51       writeHandle_(nullptr)
52 {}
53 
~SQLiteSingleVerNaturalStoreConnection()54 SQLiteSingleVerNaturalStoreConnection::~SQLiteSingleVerNaturalStoreConnection()
55 {
56     if (conflictListener_ != nullptr) {
57         conflictListener_->Drop(true);
58         conflictListener_ = nullptr;
59     }
60 }
61 
IsFileAccessControlled() const62 inline bool SQLiteSingleVerNaturalStoreConnection::IsFileAccessControlled() const
63 {
64     return RuntimeContext::GetInstance()->IsAccessControlled() &&
65            kvDB_->GetMyProperties().GetSecLabel() > SecurityLabel::S2;
66 }
67 
CheckReadDataControlled() const68 int SQLiteSingleVerNaturalStoreConnection::CheckReadDataControlled() const
69 {
70     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
71     if (naturalStore == nullptr) {
72         LOGE("[SingleVerConnection] natural store is nullptr in CheckReadDataControlled.");
73         return E_OK;
74     }
75     return naturalStore->CheckReadDataControlled();
76 }
77 
Get(const IOption & option,const Key & key,Value & value) const78 int SQLiteSingleVerNaturalStoreConnection::Get(const IOption &option, const Key &key, Value &value) const
79 {
80     if (key.size() > DBConstant::MAX_KEY_SIZE || key.empty()) {
81         return -E_INVALID_ARGS;
82     }
83 
84     SingleVerDataType dataType;
85     if (option.dataType == IOption::LOCAL_DATA) {
86         dataType = SingleVerDataType::LOCAL_TYPE;
87     } else if (option.dataType == IOption::SYNC_DATA) {
88         dataType = SingleVerDataType::SYNC_TYPE;
89     } else {
90         return -E_NOT_SUPPORT;
91     }
92 
93     int errCode = CheckReadDataControlled();
94     if (errCode != E_OK) {
95         LOGE("[Get] Existed cache database can not read data, errCode = [%d]!", errCode);
96         return errCode;
97     }
98 
99     DBDfxAdapter::StartTraceSQL();
100     {
101         // need to check if the transaction started
102         std::lock_guard<std::mutex> lock(transactionMutex_);
103         if (writeHandle_ != nullptr) {
104             LOGD("Transaction started already.");
105             Timestamp recordTimestamp;
106             errCode = writeHandle_->GetKvData(dataType, key, value, recordTimestamp);
107             DBDfxAdapter::FinishTraceSQL();
108             return errCode;
109         }
110     }
111 
112     SQLiteSingleVerStorageExecutor *handle = GetExecutor(false, errCode);
113     if (handle == nullptr) {
114         DBDfxAdapter::FinishTraceSQL();
115         return errCode;
116     }
117 
118     Timestamp timestamp;
119     errCode = handle->GetKvData(dataType, key, value, timestamp);
120     ReleaseExecutor(handle);
121     DBDfxAdapter::FinishTraceSQL();
122     return errCode;
123 }
124 
Put(const IOption & option,const Key & key,const Value & value)125 int SQLiteSingleVerNaturalStoreConnection::Put(const IOption &option, const Key &key, const Value &value)
126 {
127     std::vector<Entry> entries;
128     Entry entry{key, value};
129     entries.emplace_back(std::move(entry));
130 
131     return PutBatch(option, entries);
132 }
133 
Delete(const IOption & option,const Key & key)134 int SQLiteSingleVerNaturalStoreConnection::Delete(const IOption &option, const Key &key)
135 {
136     std::vector<Key> keys;
137     keys.push_back(key);
138 
139     return DeleteBatch(option, keys);
140 }
141 
Clear(const IOption & option)142 int SQLiteSingleVerNaturalStoreConnection::Clear(const IOption &option)
143 {
144     return -E_NOT_SUPPORT;
145 }
146 
GetEntries(const IOption & option,const Key & keyPrefix,std::vector<Entry> & entries) const147 int SQLiteSingleVerNaturalStoreConnection::GetEntries(const IOption &option, const Key &keyPrefix,
148     std::vector<Entry> &entries) const
149 {
150     if (keyPrefix.size() > DBConstant::MAX_KEY_SIZE) {
151         return -E_INVALID_ARGS;
152     }
153 
154     SingleVerDataType type;
155     if (option.dataType == IOption::LOCAL_DATA) {
156         type = SingleVerDataType::LOCAL_TYPE;
157     } else if (option.dataType == IOption::SYNC_DATA) {
158         type = SingleVerDataType::SYNC_TYPE;
159     } else {
160         return -E_INVALID_ARGS;
161     }
162 
163     int errCode = CheckReadDataControlled();
164     if (errCode != E_OK) {
165         LOGE("[GetEntries] Existed cache database can not read data, errCode = [%d]!", errCode);
166         return errCode;
167     }
168 
169     DBDfxAdapter::StartTraceSQL();
170     {
171         std::lock_guard<std::mutex> lock(transactionMutex_);
172         if (writeHandle_ != nullptr) {
173             LOGD("Transaction started already.");
174             errCode = writeHandle_->GetEntries(type, keyPrefix, entries);
175             DBDfxAdapter::FinishTraceSQL();
176             return errCode;
177         }
178     }
179 
180     SQLiteSingleVerStorageExecutor *handle = GetExecutor(false, errCode);
181     if (handle == nullptr) {
182         LOGE("[Connection]::[GetEntries] Get executor failed, errCode = [%d]", errCode);
183         DBDfxAdapter::FinishTraceSQL();
184         return errCode;
185     }
186 
187     errCode = handle->GetEntries(type, keyPrefix, entries);
188     ReleaseExecutor(handle);
189     DBDfxAdapter::FinishTraceSQL();
190     return errCode;
191 }
192 
GetEntries(const IOption & option,const Query & query,std::vector<Entry> & entries) const193 int SQLiteSingleVerNaturalStoreConnection::GetEntries(const IOption &option, const Query &query,
194     std::vector<Entry> &entries) const
195 {
196     if (option.dataType != IOption::SYNC_DATA) {
197         return -E_NOT_SUPPORT;
198     }
199     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
200     if (naturalStore == nullptr) {
201         return -E_INVALID_DB;
202     }
203     int errCode = CheckReadDataControlled();
204     if (errCode != E_OK) {
205         LOGE("[GetEntries] Existed cache database can not read data, errCode = [%d]!", errCode);
206         return errCode;
207     }
208     QueryObject queryObj(query);
209     if ((queryObj.GetSortType() != SortType::NONE) && !queryObj.IsQueryOnlyByKey()) {
210         LOGE("[GetEntries][query] timestamp sort only support prefixKey");
211         return -E_NOT_SUPPORT;
212     }
213 
214     // In readOnly mode, forbidden all schema related query
215     if (CheckWritePermission() == E_OK) {
216         const SchemaObject &schemaObjRef = naturalStore->GetSchemaObjectConstRef();
217         queryObj.SetSchema(schemaObjRef);
218     }
219     DBDfxAdapter::StartTraceSQL();
220     {
221         std::lock_guard<std::mutex> lock(transactionMutex_);
222         if (writeHandle_ != nullptr) {
223             LOGD("Transaction started already.");
224             errCode = writeHandle_->GetEntries(queryObj, entries);
225             DBDfxAdapter::FinishTraceSQL();
226             return errCode;
227         }
228     }
229 
230     SQLiteSingleVerStorageExecutor *handle = GetExecutor(false, errCode);
231     if (handle == nullptr) {
232         DBDfxAdapter::FinishTraceSQL();
233         return errCode;
234     }
235 
236     errCode = handle->GetEntries(queryObj, entries);
237     ReleaseExecutor(handle);
238     DBDfxAdapter::FinishTraceSQL();
239     return errCode;
240 }
241 
GetCount(const IOption & option,const Query & query,int & count) const242 int SQLiteSingleVerNaturalStoreConnection::GetCount(const IOption &option, const Query &query, int &count) const
243 {
244     if (option.dataType != IOption::SYNC_DATA) {
245         return -E_NOT_SUPPORT;
246     }
247     int errCode = CheckReadDataControlled();
248     if (errCode != E_OK) {
249         LOGE("[GetCount] Existed cache database can not read data, errCode = [%d]!", errCode);
250         return errCode;
251     }
252 
253     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
254     if (naturalStore == nullptr) {
255         return -E_INVALID_DB;
256     }
257     QueryObject queryObj(query);
258     if ((queryObj.GetSortType() != SortType::NONE) && !queryObj.IsQueryOnlyByKey()) {
259         LOGE("[GetCount] get count query invalid");
260         return -E_NOT_SUPPORT;
261     }
262     // In readOnly mode, forbidden all schema related query
263     if (CheckWritePermission() == E_OK) {
264         const SchemaObject &schemaObjRef = naturalStore->GetSchemaObjectConstRef();
265         queryObj.SetSchema(schemaObjRef);
266     }
267     DBDfxAdapter::StartTraceSQL();
268     {
269         std::lock_guard<std::mutex> lock(transactionMutex_);
270         if (writeHandle_ != nullptr) {
271             LOGD("Transaction started already.");
272             errCode = writeHandle_->GetCount(queryObj, count);
273             DBDfxAdapter::FinishTraceSQL();
274             return errCode;
275         }
276     }
277 
278     SQLiteSingleVerStorageExecutor *handle = GetExecutor(false, errCode);
279     if (handle == nullptr) {
280         DBDfxAdapter::FinishTraceSQL();
281         return errCode;
282     }
283     errCode = handle->GetCount(queryObj, count);
284     ReleaseExecutor(handle);
285     DBDfxAdapter::FinishTraceSQL();
286     return errCode;
287 }
288 
PutBatch(const IOption & option,const std::vector<Entry> & entries)289 int SQLiteSingleVerNaturalStoreConnection::PutBatch(const IOption &option, const std::vector<Entry> &entries)
290 {
291     LOGD("[PutBatch] entries size is : %zu, dataType : %d", entries.size(), option.dataType);
292     if (option.dataType == IOption::LOCAL_DATA) {
293         int retCode = CheckLocalEntriesValid(entries);
294         if (retCode != E_OK) {
295             return retCode;
296         }
297         return PutBatchInner(option, entries);
298     }
299 
300     if (option.dataType == IOption::SYNC_DATA) {
301         int errCode = CheckSyncEntriesValid(entries);
302         if (errCode != E_OK) {
303             return errCode;
304         }
305         return PutBatchInner(option, entries);
306     }
307 
308     return -E_NOT_SUPPORT;
309 }
310 
DeleteBatch(const IOption & option,const std::vector<Key> & keys)311 int SQLiteSingleVerNaturalStoreConnection::DeleteBatch(const IOption &option, const std::vector<Key> &keys)
312 {
313     LOGD("[DeleteBatch] keys size is : %zu, dataType : %d", keys.size(), option.dataType);
314     if (option.dataType == IOption::LOCAL_DATA) {
315         int retCode = CheckLocalKeysValid(keys);
316         if (retCode != E_OK) {
317             return retCode;
318         }
319         return DeleteBatchInner(option, keys);
320     }
321 
322     if (option.dataType == IOption::SYNC_DATA) {
323         int errCode = CheckSyncKeysValid(keys);
324         if (errCode != E_OK) {
325             return errCode;
326         }
327         return DeleteBatchInner(option, keys);
328     }
329 
330     return -E_NOT_SUPPORT;
331 }
332 
GetSnapshot(IKvDBSnapshot * & snapshot) const333 int SQLiteSingleVerNaturalStoreConnection::GetSnapshot(IKvDBSnapshot *&snapshot) const
334 {
335     return -E_NOT_SUPPORT;
336 }
337 
ReleaseSnapshot(IKvDBSnapshot * & snapshot)338 void SQLiteSingleVerNaturalStoreConnection::ReleaseSnapshot(IKvDBSnapshot *&snapshot)
339 {}
340 
StartTransaction()341 int SQLiteSingleVerNaturalStoreConnection::StartTransaction()
342 {
343     std::lock_guard<std::mutex> lock(transactionMutex_);
344     if (writeHandle_ != nullptr) {
345         LOGD("Transaction started already.");
346         return -E_TRANSACT_STATE;
347     }
348 
349     int errCode = StartTransactionInner();
350     if (errCode == E_OK) {
351         transactionExeFlag_.store(true);
352     }
353     return errCode;
354 }
355 
Commit()356 int SQLiteSingleVerNaturalStoreConnection::Commit()
357 {
358     std::lock_guard<std::mutex> lock(transactionMutex_);
359     if (writeHandle_ == nullptr) {
360         LOGE("single version database is null or the transaction has not been started");
361         return -E_INVALID_DB;
362     }
363 
364     int errCode = CommitInner();
365     if (errCode == E_OK) {
366         transactionExeFlag_.store(false);
367     }
368     return errCode;
369 }
370 
RollBack()371 int SQLiteSingleVerNaturalStoreConnection::RollBack()
372 {
373     std::lock_guard<std::mutex> lock(transactionMutex_);
374     if (writeHandle_ == nullptr) {
375         LOGE("Invalid handle for rollback or the transaction has not been started.");
376         return -E_INVALID_DB;
377     }
378 
379     int errCode = RollbackInner();
380     if (errCode == E_OK) {
381         transactionExeFlag_.store(false);
382     }
383     return errCode;
384 }
385 
IsTransactionStarted() const386 bool SQLiteSingleVerNaturalStoreConnection::IsTransactionStarted() const
387 {
388     return transactionExeFlag_.load();
389 }
390 
Pragma(int cmd,void * parameter)391 int SQLiteSingleVerNaturalStoreConnection::Pragma(int cmd, void *parameter)
392 {
393     int errCode = E_OK;
394     switch (cmd) {
395         case PRAGMA_RM_DEVICE_DATA: {
396             SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
397             if (naturalStore == nullptr) {
398                 return -E_INVALID_DB;
399             }
400             auto deviceName = static_cast<std::string *>(parameter);
401             errCode = naturalStore->RemoveDeviceData(*deviceName, false, false);
402             break;
403         }
404         case PRAGMA_GET_IDENTIFIER_OF_DEVICE: {
405             if (parameter == nullptr) {
406                 return -E_INVALID_ARGS;
407             }
408             return CalcHashDevID(*(static_cast<PragmaDeviceIdentifier *>(parameter)));
409         }
410         case PRAGMA_GET_DEVICE_IDENTIFIER_OF_ENTRY:
411             return GetDeviceIdentifier(static_cast<PragmaEntryDeviceIdentifier *>(parameter));
412         case PRAGMA_PUBLISH_LOCAL:
413             return PragmaPublish(parameter);
414         case PRAGMA_UNPUBLISH_SYNC:
415             errCode = PragmaUnpublish(parameter);
416             break;
417         case PRAGMA_SET_AUTO_LIFE_CYCLE:
418             return PragmaSetAutoLifeCycle(static_cast<uint32_t *>(parameter));
419         case PRAGMA_RESULT_SET_CACHE_MODE:
420             return PragmaResultSetCacheMode(parameter);
421         case PRAGMA_RESULT_SET_CACHE_MAX_SIZE:
422             return PragmaResultSetCacheMaxSize(parameter);
423         case PRAGMA_TRIGGER_TO_MIGRATE_DATA:
424             return PragmaTriggerToMigrateData(*static_cast<SecurityOption *>(parameter));
425         case PRAGMA_SET_MAX_LOG_LIMIT:
426             return PragmaSetMaxLogSize(static_cast<uint64_t *>(parameter));
427         case PRAGMA_EXEC_CHECKPOINT:
428             return ForceCheckPoint();
429         default:
430             // Call Pragma() of super class.
431             errCode = SyncAbleKvDBConnection::Pragma(cmd, parameter);
432             break;
433     }
434 
435     return errCode;
436 }
437 
TranslateObserverModeToEventTypes(unsigned mode,std::list<int> & eventTypes) const438 int SQLiteSingleVerNaturalStoreConnection::TranslateObserverModeToEventTypes(unsigned mode,
439     std::list<int> &eventTypes) const
440 {
441     int errCode = E_OK;
442     switch (mode) {
443         case static_cast<unsigned>(SQLITE_GENERAL_NS_PUT_EVENT):
444             eventTypes.push_back(SQLITE_GENERAL_NS_PUT_EVENT);
445             break;
446         case static_cast<unsigned>(SQLITE_GENERAL_NS_SYNC_EVENT):
447             eventTypes.push_back(SQLITE_GENERAL_NS_SYNC_EVENT);
448             break;
449         case (static_cast<unsigned>(SQLITE_GENERAL_NS_PUT_EVENT)
450             | static_cast<unsigned>(SQLITE_GENERAL_NS_SYNC_EVENT)):
451             eventTypes.push_back(SQLITE_GENERAL_NS_PUT_EVENT);
452             eventTypes.push_back(SQLITE_GENERAL_NS_SYNC_EVENT);
453             break;
454         case static_cast<unsigned>(SQLITE_GENERAL_NS_LOCAL_PUT_EVENT):
455             eventTypes.push_back(SQLITE_GENERAL_NS_LOCAL_PUT_EVENT);
456             break;
457         default:
458             errCode = -E_NOT_SUPPORT;
459             break;
460     }
461     return errCode;
462 }
463 
ClearConflictNotifierCount()464 void SQLiteSingleVerNaturalStoreConnection::ClearConflictNotifierCount()
465 {
466     uint32_t conflictType = static_cast<unsigned>(conflictType_);
467     if ((conflictType & static_cast<unsigned>(SQLITE_GENERAL_NS_FOREIGN_KEY_ONLY)) != 0) {
468         (void)kvDB_->UnregisterFunction(CONFLICT_SINGLE_VERSION_NS_FOREIGN_KEY_ONLY);
469     }
470     if ((conflictType & static_cast<unsigned>(SQLITE_GENERAL_NS_FOREIGN_KEY_ORIG)) != 0) {
471         (void)kvDB_->UnregisterFunction(CONFLICT_SINGLE_VERSION_NS_FOREIGN_KEY_ORIG);
472     }
473     if ((conflictType & static_cast<unsigned>(SQLITE_GENERAL_NS_NATIVE_ALL)) != 0) {
474         (void)kvDB_->UnregisterFunction(CONFLICT_SINGLE_VERSION_NS_NATIVE_ALL);
475     }
476     return;
477 }
478 
ResetConflictNotifierCount(int target)479 void SQLiteSingleVerNaturalStoreConnection::ResetConflictNotifierCount(int target)
480 {
481     // Clear the old conflict type function.
482     ClearConflictNotifierCount();
483 
484     LOGD("Conflict type:%d to %d", conflictType_, target);
485     // Add the new conflict type function.
486     AddConflictNotifierCount(target);
487     conflictType_ = target;
488 }
489 
AddConflictNotifierCount(int target)490 void SQLiteSingleVerNaturalStoreConnection::AddConflictNotifierCount(int target)
491 {
492     LOGD("Conflict type:%u vs %u", conflictType_, target);
493     // Add the new conflict type function.
494     uint32_t targetTemp = static_cast<uint32_t>(target);
495     if ((targetTemp & static_cast<uint32_t>(SQLITE_GENERAL_NS_FOREIGN_KEY_ONLY)) != 0) {
496         (void)kvDB_->RegisterFunction(CONFLICT_SINGLE_VERSION_NS_FOREIGN_KEY_ONLY);
497     }
498     if ((targetTemp & static_cast<uint32_t>(SQLITE_GENERAL_NS_FOREIGN_KEY_ORIG)) != 0) {
499         (void)kvDB_->RegisterFunction(CONFLICT_SINGLE_VERSION_NS_FOREIGN_KEY_ORIG);
500     }
501     if ((targetTemp & static_cast<uint32_t>(SQLITE_GENERAL_NS_NATIVE_ALL)) != 0) {
502         (void)kvDB_->RegisterFunction(CONFLICT_SINGLE_VERSION_NS_NATIVE_ALL);
503     }
504 }
505 
SetConflictNotifier(int conflictType,const KvDBConflictAction & action)506 int SQLiteSingleVerNaturalStoreConnection::SetConflictNotifier(int conflictType,
507     const KvDBConflictAction &action)
508 {
509     std::lock_guard<std::mutex> lock(conflictMutex_);
510     if (!action && conflictListener_ == nullptr) {
511         return -E_INVALID_ARGS;
512     }
513     if (kvDB_ == nullptr) {
514         return -E_INVALID_DB;
515     }
516 
517     // prevent the rekey operation.
518     if (isExclusive_.load()) {
519         return -E_BUSY;
520     }
521 
522     int targetType = 0;
523     NotificationChain::Listener *listener = nullptr;
524     if (action) {
525         int errCode = E_OK;
526         Key key;
527         listener = RegisterSpecialListener(SQLITE_GENERAL_CONFLICT_EVENT, key, action, true, errCode);
528         if (listener == nullptr) {
529             LOGE("Register Conflict listener failed:'%d'.", errCode);
530             return errCode;
531         }
532         targetType = conflictType;
533     }
534 
535     ResetConflictNotifierCount(targetType);
536     // drop the old listener.
537     if (conflictListener_ != nullptr) {
538         conflictListener_->Drop(true);
539     }
540     conflictListener_ = listener;
541     return E_OK;
542 }
543 
Rekey(const CipherPassword & passwd)544 int SQLiteSingleVerNaturalStoreConnection::Rekey(const CipherPassword &passwd)
545 {
546     if (IsFileAccessControlled()) {
547         LOGE("Forbid Rekey when screen locked and security label [%d]!", kvDB_->GetMyProperties().GetSecLabel());
548         return -E_NOT_SUPPORT;
549     }
550     std::lock_guard<std::mutex> lock(rekeyMutex_);
551     int errCode = CheckMonoStatus(OperatePerm::REKEY_MONOPOLIZE_PERM);
552     if (errCode != E_OK) {
553         return errCode;
554     }
555     LOGI("Begin rekey operation");
556     errCode = kvDB_->Rekey(passwd);
557     GenericKvDBConnection::ResetExclusiveStatus();
558     kvDB_->ReEnableConnection(OperatePerm::REKEY_MONOPOLIZE_PERM);
559     EnableManualSync();
560     LOGI("End rekey operation errCode = [%d]", errCode);
561     return errCode;
562 }
563 
Export(const std::string & filePath,const CipherPassword & passwd)564 int SQLiteSingleVerNaturalStoreConnection::Export(const std::string &filePath, const CipherPassword &passwd)
565 {
566     if (kvDB_ == nullptr) {
567         return -E_INVALID_DB;
568     }
569 
570     if (IsFileAccessControlled()) {
571         LOGE("Forbid Export when screen locked and security label [%d] file lock state [%d]",
572             kvDB_->GetMyProperties().GetSecLabel(), RuntimeContext::GetInstance()->IsAccessControlled());
573         return -E_NOT_SUPPORT;
574     } // Avoid abnormal branch handling without affecting the business
575     return kvDB_->Export(filePath, passwd);
576 }
577 
Import(const std::string & filePath,const CipherPassword & passwd)578 int SQLiteSingleVerNaturalStoreConnection::Import(const std::string &filePath, const CipherPassword &passwd)
579 {
580     if (IsFileAccessControlled()) {
581         LOGE("Forbid Import when screen locked and security label [%d]!", kvDB_->GetMyProperties().GetSecLabel());
582         return -E_NOT_SUPPORT;
583     }
584 
585     std::lock_guard<std::mutex> lock(importMutex_);
586     int errCode = CheckMonoStatus(OperatePerm::IMPORT_MONOPOLIZE_PERM);
587     if (errCode != E_OK) {
588         return errCode;
589     }
590     errCode = kvDB_->Import(filePath, passwd);
591     GenericKvDBConnection::ResetExclusiveStatus();
592     kvDB_->ReEnableConnection(OperatePerm::IMPORT_MONOPOLIZE_PERM);
593     EnableManualSync();
594     return errCode;
595 }
596 
GetResultSet(const IOption & option,const Key & keyPrefix,IKvDBResultSet * & resultSet) const597 int SQLiteSingleVerNaturalStoreConnection::GetResultSet(const IOption &option, const Key &keyPrefix,
598     IKvDBResultSet *&resultSet) const
599 {
600     // need to check if the transaction started
601     if (transactionExeFlag_.load()) {
602         LOGD("Transaction started already.");
603         return -E_BUSY;
604     }
605 
606     // maximum of result set size is 4
607     std::lock_guard<std::mutex> lock(kvDbResultSetsMutex_);
608     if (kvDbResultSets_.size() >= MAX_RESULT_SET_SIZE) {
609         LOGE("Over max result set size");
610         return -E_MAX_LIMITS;
611     }
612 
613     int errCode = CheckReadDataControlled();
614     if (errCode != E_OK) {
615         LOGE("[GetResultSet][keyPrefix] Existed cache database can not read data, errCode = [%d]!", errCode);
616         return errCode;
617     }
618 
619     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
620     if (naturalStore == nullptr) {
621         return -E_INVALID_DB;
622     }
623     bool isMemDb = naturalStore->GetMyProperties().GetBoolProp(KvDBProperties::MEMORY_MODE, false);
624     resultSet = new (std::nothrow) SQLiteSingleVerResultSet(naturalStore, keyPrefix,
625         SQLiteSingleVerResultSet::Option{cacheModeForNewResultSet_.load(), cacheMaxSizeForNewResultSet_.load()});
626     if (resultSet == nullptr) {
627         LOGE("Create single version result set failed.");
628         return -E_OUT_OF_MEMORY;
629     }
630     errCode = resultSet->Open(isMemDb);
631     if (errCode != E_OK) {
632         delete resultSet;
633         resultSet = nullptr;
634         LOGE("Open result set failed.");
635         return errCode;
636     }
637     kvDbResultSets_.insert(resultSet);
638     return E_OK;
639 }
640 
GetResultSet(const IOption & option,const Query & query,IKvDBResultSet * & resultSet) const641 int SQLiteSingleVerNaturalStoreConnection::GetResultSet(const IOption &option, const Query &query,
642     IKvDBResultSet *&resultSet) const
643 {
644     // need to check if the transaction started
645     if (transactionExeFlag_.load()) {
646         LOGD("Transaction started already.");
647         return -E_BUSY;
648     }
649 
650     // maximum of result set size is 4
651     std::lock_guard<std::mutex> lock(kvDbResultSetsMutex_);
652     if (kvDbResultSets_.size() >= MAX_RESULT_SET_SIZE) {
653         LOGE("Over max result set size");
654         return -E_MAX_LIMITS;
655     }
656 
657     int errCode = CheckReadDataControlled();
658     if (errCode != E_OK) {
659         LOGE("[GetResultSet][query] Existed cache database can not read data, errCode = [%d]!", errCode);
660         return errCode;
661     }
662 
663     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>(); // Guarantee not nullptr
664     QueryObject queryObj(query);
665     // In readOnly mode, forbidden all schema related query
666     if (CheckWritePermission() == E_OK) {
667         const SchemaObject &schemaObjRef = naturalStore->GetSchemaObjectConstRef();
668         queryObj.SetSchema(schemaObjRef);
669     }
670     if ((queryObj.GetSortType() != SortType::NONE) && !queryObj.IsQueryOnlyByKey()) {
671         LOGE("[GetResultSet][query] timestamp sort only support prefixKey");
672         return -E_NOT_SUPPORT;
673     }
674     bool isMemDb = naturalStore->GetMyProperties().GetBoolProp(KvDBProperties::MEMORY_MODE, false);
675     resultSet = new (std::nothrow) SQLiteSingleVerResultSet(naturalStore, queryObj,
676         SQLiteSingleVerResultSet::Option{cacheModeForNewResultSet_.load(), cacheMaxSizeForNewResultSet_.load()});
677     if (resultSet == nullptr) {
678         LOGE("Create single version result set failed.");
679         return -E_OUT_OF_MEMORY;
680     }
681     errCode = resultSet->Open(isMemDb);
682     if (errCode != E_OK) {
683         delete resultSet;
684         resultSet = nullptr;
685         LOGE("Open result set failed.");
686         return errCode;
687     }
688     kvDbResultSets_.insert(resultSet);
689     return E_OK;
690 }
691 
ReleaseResultSet(IKvDBResultSet * & resultSet)692 void SQLiteSingleVerNaturalStoreConnection::ReleaseResultSet(IKvDBResultSet *&resultSet)
693 {
694     std::lock_guard<std::mutex> lock(kvDbResultSetsMutex_);
695     if (resultSet == nullptr) {
696         return;
697     }
698     resultSet->Close();
699     kvDbResultSets_.erase(resultSet);
700     delete resultSet;
701     resultSet = nullptr;
702     return;
703 }
704 
RegisterLifeCycleCallback(const DatabaseLifeCycleNotifier & notifier)705 int SQLiteSingleVerNaturalStoreConnection::RegisterLifeCycleCallback(const DatabaseLifeCycleNotifier &notifier)
706 {
707     if (kvDB_ == nullptr) {
708         return -E_INVALID_DB;
709     }
710     return static_cast<SQLiteSingleVerNaturalStore *>(kvDB_)->RegisterLifeCycleCallback(notifier);
711 }
712 
PreClose()713 int SQLiteSingleVerNaturalStoreConnection::PreClose()
714 {
715     // check if result set closed
716     {
717         std::lock_guard<std::mutex> kvDbResultLock(kvDbResultSetsMutex_);
718         if (kvDbResultSets_.size() > 0) {
719             LOGE("The connection have [%zu] active result set, can not close.", kvDbResultSets_.size());
720             return -E_BUSY;
721         }
722     }
723 
724     // check if transaction closed
725     {
726         std::lock_guard<std::mutex> transactionLock(transactionMutex_);
727         if (writeHandle_ != nullptr) {
728             LOGW("Transaction started, need to rollback before close.");
729             int errCode = RollbackInner();
730             if (errCode != E_OK) {
731                 LOGE("Rollback transaction failed, %d.", errCode);
732             }
733             ReleaseExecutor(writeHandle_);
734         }
735     }
736 
737     // Clear the conflict type function.
738     {
739         std::lock_guard<std::mutex> lock(conflictMutex_);
740         ClearConflictNotifierCount();
741         conflictType_ = 0;
742     }
743     return E_OK;
744 }
745 
CheckIntegrity() const746 int SQLiteSingleVerNaturalStoreConnection::CheckIntegrity() const
747 {
748     int errCode = E_OK;
749     SQLiteSingleVerStorageExecutor *handle = GetExecutor(true, errCode);
750     if (handle == nullptr) {
751         LOGW("Failed to get the executor for the integrity check.");
752         return errCode;
753     }
754 
755     errCode = handle->CheckIntegrity();
756     ReleaseExecutor(handle);
757     return errCode;
758 }
759 
PragmaSetMaxLogSize(uint64_t * limit)760 int SQLiteSingleVerNaturalStoreConnection::PragmaSetMaxLogSize(uint64_t *limit)
761 {
762     if (limit == nullptr) {
763         return -E_INVALID_ARGS;
764     }
765     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
766     if (naturalStore == nullptr) {
767         LOGE("[SingleVerConnection] db is nullptr for max log limit set.");
768         return -E_INVALID_DB;
769     }
770     if (*limit > DBConstant::MAX_LOG_SIZE_HIGH || *limit < DBConstant::MAX_LOG_SIZE_LOW) {
771         return -E_INVALID_ARGS;
772     }
773     return naturalStore->SetMaxLogSize(*limit);
774 }
775 
ForceCheckPoint() const776 int SQLiteSingleVerNaturalStoreConnection::ForceCheckPoint() const
777 {
778     int errCode = E_OK;
779     SQLiteSingleVerStorageExecutor *handle = GetExecutor(true, errCode);
780     if (handle == nullptr) {
781         LOGW("Failed to get the executor for the checkpoint.");
782         return errCode;
783     }
784 
785     errCode = handle->ForceCheckPoint();
786     ReleaseExecutor(handle);
787     return errCode;
788 }
789 
CheckMonoStatus(OperatePerm perm)790 int SQLiteSingleVerNaturalStoreConnection::CheckMonoStatus(OperatePerm perm)
791 {
792     // 1. Get the connection number
793     if (kvDB_ == nullptr) {
794         return -E_INVALID_DB;
795     }
796     int errCode = DisableManualSync();
797     if (errCode != E_OK) {
798         LOGE("In manual sync");
799         return -E_BUSY;
800     }
801 
802     // 2. check the result set number
803     {
804         std::lock_guard<std::mutex> kvDbResultLock(kvDbResultSetsMutex_);
805         if (kvDbResultSets_.size() > 0) {
806             LOGE("Active result set exist.");
807             EnableManualSync();
808             return -E_BUSY;
809         }
810     }
811     // 1. Get the connection number, and get the right to do the rekey operation.
812     errCode = kvDB_->TryToDisableConnection(perm);
813     if (errCode != E_OK) {
814         // If precheck failed, it means that there are more than one connection.
815         // No need reset the condition for the scene.
816         LOGE("More than one connection");
817         EnableManualSync();
818         return errCode;
819     }
820     // 2. Check the observer list.
821     errCode = GenericKvDBConnection::PreCheckExclusiveStatus();
822     if (errCode != E_OK) {
823         kvDB_->ReEnableConnection(perm);
824         LOGE("Observer prevents.");
825         EnableManualSync();
826         return errCode;
827     }
828 
829     // 3. Check the conflict notifier.
830     {
831         std::lock_guard<std::mutex> conflictLock(conflictMutex_);
832         if (conflictListener_ != nullptr) {
833             errCode = -E_BUSY;
834             GenericKvDBConnection::ResetExclusiveStatus();
835             kvDB_->ReEnableConnection(perm);
836             LOGE("Conflict notifier prevents");
837             EnableManualSync();
838             return errCode;
839         }
840     }
841     return E_OK;
842 }
843 
GetDeviceIdentifier(PragmaEntryDeviceIdentifier * identifier)844 int SQLiteSingleVerNaturalStoreConnection::GetDeviceIdentifier(PragmaEntryDeviceIdentifier *identifier)
845 {
846     if (identifier == nullptr) {
847         return -E_INVALID_ARGS;
848     }
849 
850     if (identifier->key.empty() || identifier->key.size() > DBConstant::MAX_VALUE_SIZE) {
851         return -E_INVALID_ARGS;
852     }
853 
854     int errCode = E_OK;
855     SQLiteSingleVerStorageExecutor *handle = GetExecutor(false, errCode);
856     if (handle == nullptr) {
857         return errCode;
858     }
859 
860     errCode = handle->GetDeviceIdentifier(identifier);
861     ReleaseExecutor(handle);
862     return errCode;
863 }
864 
PutBatchInner(const IOption & option,const std::vector<Entry> & entries)865 int SQLiteSingleVerNaturalStoreConnection::PutBatchInner(const IOption &option, const std::vector<Entry> &entries)
866 {
867     DBDfxAdapter::StartTraceSQL();
868     std::lock_guard<std::mutex> lock(transactionMutex_);
869     bool isAuto = false;
870     int errCode = E_OK;
871     if (writeHandle_ == nullptr) {
872         isAuto = true;
873         errCode = StartTransactionInner(TransactType::IMMEDIATE);
874         if (errCode != E_OK) {
875             DBDfxAdapter::FinishTraceSQL();
876             return errCode;
877         }
878     }
879 
880     if ((transactionEntrySize_ + entries.size()) > DBConstant::MAX_TRANSACTION_ENTRY_SIZE) {
881         DBDfxAdapter::FinishTraceSQL();
882         return -E_MAX_LIMITS;
883     }
884 
885     if (option.dataType == IOption::SYNC_DATA) {
886         errCode = SaveSyncEntries(entries);
887     } else {
888         errCode = SaveLocalEntries(entries);
889     }
890     if (errCode == E_OK) {
891         transactionEntrySize_ += entries.size();
892     }
893 
894     if (isAuto) {
895         if (errCode == E_OK) {
896             errCode = CommitInner();
897         } else {
898             int innerCode = RollbackInner();
899             errCode = (innerCode != E_OK) ? innerCode : errCode;
900         }
901     }
902     DBDfxAdapter::FinishTraceSQL();
903     return errCode;
904 }
905 
DeleteBatchInner(const IOption & option,const std::vector<Key> & keys)906 int SQLiteSingleVerNaturalStoreConnection::DeleteBatchInner(const IOption &option, const std::vector<Key> &keys)
907 {
908     DBDfxAdapter::StartTraceSQL();
909     std::lock_guard<std::mutex> lock(transactionMutex_);
910     bool isAuto = false;
911     int errCode = E_OK;
912 
913     if (writeHandle_ == nullptr) {
914         isAuto = true;
915         errCode = StartTransactionInner(TransactType::IMMEDIATE);
916         if (errCode != E_OK) {
917             DBDfxAdapter::FinishTraceSQL();
918             return errCode;
919         }
920     }
921 
922     if ((transactionEntrySize_ + keys.size()) > DBConstant::MAX_TRANSACTION_ENTRY_SIZE) {
923         DBDfxAdapter::FinishTraceSQL();
924         return -E_MAX_LIMITS;
925     }
926 
927     if (option.dataType == IOption::SYNC_DATA) {
928         errCode = DeleteSyncEntries(keys);
929     } else {
930         errCode = DeleteLocalEntries(keys);
931     }
932     if (errCode == E_OK) {
933         transactionEntrySize_ += keys.size();
934     }
935 
936     if (isAuto) {
937         if (errCode == E_OK) {
938             errCode = CommitInner();
939         } else {
940             int innerCode = RollbackInner();
941             errCode = (innerCode != E_OK) ? innerCode : errCode;
942         }
943     }
944     DBDfxAdapter::FinishTraceSQL();
945     return errCode;
946 }
947 
SaveSyncEntries(const std::vector<Entry> & entries)948 int SQLiteSingleVerNaturalStoreConnection::SaveSyncEntries(const std::vector<Entry> &entries)
949 {
950     int errCode = E_OK;
951     for (const auto &entry : entries) {
952         errCode = SaveEntry(entry, false);
953         if (errCode != E_OK) {
954             break;
955         }
956     }
957     return errCode;
958 }
959 
SaveLocalEntries(const std::vector<Entry> & entries)960 int SQLiteSingleVerNaturalStoreConnection::SaveLocalEntries(const std::vector<Entry> &entries)
961 {
962     int errCode = E_OK;
963     for (const auto &entry : entries) {
964         errCode = SaveLocalEntry(entry, false);
965         if (errCode != E_OK) {
966             break;
967         }
968     }
969     return errCode;
970 }
971 
DeleteSyncEntries(const std::vector<Key> & keys)972 int SQLiteSingleVerNaturalStoreConnection::DeleteSyncEntries(const std::vector<Key> &keys)
973 {
974     int errCode = E_OK;
975     for (const auto &key : keys) {
976         Entry entry;
977         DBCommon::CalcValueHash(key, entry.key);
978         errCode = SaveEntry(entry, true);
979         if ((errCode != E_OK) && (errCode != -E_NOT_FOUND)) {
980             LOGE("[DeleteSyncEntries] Delete data err:%d", errCode);
981             break;
982         }
983     }
984     return (errCode == -E_NOT_FOUND) ? E_OK : errCode;
985 }
986 
DeleteLocalEntries(const std::vector<Key> & keys)987 int SQLiteSingleVerNaturalStoreConnection::DeleteLocalEntries(const std::vector<Key> &keys)
988 {
989     int errCode = E_OK;
990     for (const auto &key : keys) {
991         Entry entry = {key, Value()};
992         errCode = SaveLocalEntry(entry, true);
993         if ((errCode != E_OK) && (errCode != -E_NOT_FOUND)) {
994             LOGE("[DeleteLocalEntries] Delete data err:%d", errCode);
995             break;
996         }
997     }
998     return (errCode == -E_NOT_FOUND) ? E_OK : errCode;
999 }
1000 
1001 // This function currently only be called in local procedure to change sync_data table, do not use in sync procedure.
1002 // It will check and amend value when need if it is a schema database. return error if some value disagree with the
1003 // schema. But in sync procedure, we just neglect the value that disagree with schema.
SaveEntry(const Entry & entry,bool isDelete,Timestamp timestamp)1004 int SQLiteSingleVerNaturalStoreConnection::SaveEntry(const Entry &entry, bool isDelete, Timestamp timestamp)
1005 {
1006     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1007     if (naturalStore == nullptr) {
1008         return -E_INVALID_DB;
1009     }
1010 
1011     DataItem dataItem;
1012     dataItem.key = entry.key;
1013     dataItem.value = entry.value;
1014     dataItem.flag = DataItem::LOCAL_FLAG;
1015     if (isDelete) {
1016         dataItem.flag |= DataItem::DELETE_FLAG;
1017     } else {
1018         int errCode = CheckAmendValueContentForLocalProcedure(dataItem.value, dataItem.value);
1019         if (errCode != E_OK) {
1020             LOGE("[SqlSinCon][SaveEntry] CheckAmendValue fail, errCode=%d.", errCode);
1021             return errCode;
1022         }
1023     }
1024 
1025     dataItem.timestamp = naturalStore->GetCurrentTimestamp();
1026     if (currentMaxTimestamp_ > dataItem.timestamp) {
1027         dataItem.timestamp = currentMaxTimestamp_;
1028     }
1029 
1030     if (timestamp != 0) {
1031         dataItem.writeTimestamp = timestamp;
1032     } else {
1033         dataItem.writeTimestamp = dataItem.timestamp;
1034     }
1035 
1036     if (IsExtendedCacheDBMode()) {
1037         uint64_t recordVersion = naturalStore->GetCacheRecordVersion();
1038         return SaveEntryInCacheMode(dataItem, recordVersion);
1039     } else {
1040         return SaveEntryNormally(dataItem);
1041     }
1042 }
1043 
SaveLocalEntry(const Entry & entry,bool isDelete)1044 int SQLiteSingleVerNaturalStoreConnection::SaveLocalEntry(const Entry &entry, bool isDelete)
1045 {
1046     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1047     if (naturalStore == nullptr) {
1048         return -E_INVALID_DB;
1049     }
1050 
1051     LocalDataItem dataItem;
1052     dataItem.key = entry.key;
1053     dataItem.value = entry.value;
1054     (void)DBCommon::CalcValueHash(entry.key, dataItem.hashKey);
1055     if (isDelete) {
1056         dataItem.flag = DataItem::DELETE_FLAG;
1057     }
1058     dataItem.timestamp = naturalStore->GetCurrentTimestamp();
1059     LOGD("Timestamp is %" PRIu64, dataItem.timestamp);
1060 
1061     if (IsCacheDBMode()) {
1062         return SaveLocalItemInCacheMode(dataItem);
1063     } else {
1064         return SaveLocalItem(dataItem);
1065     }
1066 }
1067 
SaveLocalItem(const LocalDataItem & dataItem) const1068 int SQLiteSingleVerNaturalStoreConnection::SaveLocalItem(const LocalDataItem &dataItem) const
1069 {
1070     int errCode = E_OK;
1071     if ((dataItem.flag & DataItem::DELETE_FLAG) == 0) {
1072         errCode = writeHandle_->PutKvData(SingleVerDataType::LOCAL_TYPE, dataItem.key, dataItem.value,
1073             dataItem.timestamp, localCommittedData_);
1074     } else {
1075         Value value;
1076         Timestamp localTimestamp = 0;
1077         errCode = writeHandle_->DeleteLocalKvData(dataItem.key, localCommittedData_, value, localTimestamp);
1078     }
1079     return errCode;
1080 }
1081 
SaveLocalItemInCacheMode(const LocalDataItem & dataItem) const1082 int SQLiteSingleVerNaturalStoreConnection::SaveLocalItemInCacheMode(const LocalDataItem &dataItem) const
1083 {
1084     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1085     if (naturalStore == nullptr) {
1086         return -E_INVALID_DB;
1087     }
1088 
1089     int errCode = writeHandle_->PutLocalDataToCacheDB(dataItem);
1090     if (errCode != E_OK) {
1091         LOGE("[PutLocalEntries] Put local data to cacheDB err:%d", errCode);
1092     }
1093     return errCode;
1094 }
1095 
SaveEntryNormally(DataItem & dataItem)1096 int SQLiteSingleVerNaturalStoreConnection::SaveEntryNormally(DataItem &dataItem)
1097 {
1098     int errCode = writeHandle_->PrepareForSavingData(SingleVerDataType::SYNC_TYPE);
1099     if (errCode != E_OK) {
1100         LOGE("Prepare the saving sync data failed:%d", errCode);
1101         return errCode;
1102     }
1103 
1104     Timestamp maxTimestamp = 0;
1105     DeviceInfo deviceInfo = {true, ""};
1106     errCode = writeHandle_->SaveSyncDataItem(dataItem, deviceInfo, maxTimestamp, committedData_);
1107     if (errCode == E_OK) {
1108         if (maxTimestamp > currentMaxTimestamp_) {
1109             currentMaxTimestamp_ = maxTimestamp;
1110         }
1111     } else {
1112         LOGE("Save entry failed, err:%d", errCode);
1113     }
1114     return errCode;
1115 }
1116 
SaveEntryInCacheMode(DataItem & dataItem,uint64_t recordVersion)1117 int SQLiteSingleVerNaturalStoreConnection::SaveEntryInCacheMode(DataItem &dataItem, uint64_t recordVersion)
1118 {
1119     int errCode = writeHandle_->PrepareForSavingCacheData(SingleVerDataType::SYNC_TYPE);
1120     if (errCode != E_OK) {
1121         LOGE("Prepare the saving sync data failed:%d", errCode);
1122         return errCode;
1123     }
1124 
1125     Timestamp maxTimestamp = 0;
1126     DeviceInfo deviceInfo = {true, ""};
1127     QueryObject query(Query::Select());
1128     errCode = writeHandle_->SaveSyncDataItemInCacheMode(dataItem, deviceInfo, maxTimestamp, recordVersion, query);
1129     if (errCode == E_OK) {
1130         if (maxTimestamp > currentMaxTimestamp_) {
1131             currentMaxTimestamp_ = maxTimestamp;
1132         }
1133     } else {
1134         LOGE("Save entry failed, err:%d", errCode);
1135     }
1136     return errCode;
1137 }
1138 
CheckDataStatus(const Key & key,const Value & value,bool isDelete) const1139 int SQLiteSingleVerNaturalStoreConnection::CheckDataStatus(const Key &key, const Value &value, bool isDelete) const
1140 {
1141     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1142     if (naturalStore == nullptr) {
1143         return -E_INVALID_DB;
1144     }
1145 
1146     return naturalStore->CheckDataStatus(key, value, isDelete);
1147 }
1148 
CheckWritePermission() const1149 int SQLiteSingleVerNaturalStoreConnection::CheckWritePermission() const
1150 {
1151     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1152     if (naturalStore == nullptr) {
1153         return -E_INVALID_DB;
1154     }
1155 
1156     if (!naturalStore->CheckWritePermission()) {
1157         return -E_READ_ONLY;
1158     }
1159     return E_OK;
1160 }
1161 
CheckSyncEntriesValid(const std::vector<Entry> & entries) const1162 int SQLiteSingleVerNaturalStoreConnection::CheckSyncEntriesValid(const std::vector<Entry> &entries) const
1163 {
1164     if (entries.size() > DBConstant::MAX_BATCH_SIZE) {
1165         return -E_INVALID_ARGS;
1166     }
1167 
1168     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1169     if (naturalStore == nullptr) {
1170         return -E_INVALID_DB;
1171     }
1172 
1173     if (!naturalStore->CheckWritePermission()) {
1174         return -E_READ_ONLY;
1175     }
1176 
1177     for (const auto &entry : entries) {
1178         int errCode = naturalStore->CheckDataStatus(entry.key, entry.value, false);
1179         if (errCode != E_OK) {
1180             return errCode;
1181         }
1182     }
1183     return E_OK;
1184 }
1185 
CheckSyncKeysValid(const std::vector<Key> & keys) const1186 int SQLiteSingleVerNaturalStoreConnection::CheckSyncKeysValid(const std::vector<Key> &keys) const
1187 {
1188     if (keys.size() > DBConstant::MAX_BATCH_SIZE) {
1189         return -E_INVALID_ARGS;
1190     }
1191 
1192     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1193     if (naturalStore == nullptr) {
1194         return -E_INVALID_DB;
1195     }
1196 
1197     if (!naturalStore->CheckWritePermission()) {
1198         return -E_READ_ONLY;
1199     }
1200 
1201     for (const auto &key : keys) {
1202         int errCode = naturalStore->CheckDataStatus(key, {}, true);
1203         if (errCode != E_OK) {
1204             return errCode;
1205         }
1206     }
1207     return E_OK;
1208 }
1209 
CheckLocalEntriesValid(const std::vector<Entry> & entries) const1210 int SQLiteSingleVerNaturalStoreConnection::CheckLocalEntriesValid(const std::vector<Entry> &entries) const
1211 {
1212     if (entries.size() > DBConstant::MAX_BATCH_SIZE) {
1213         return -E_INVALID_ARGS;
1214     }
1215 
1216     GenericKvDB *naturalStore = GetDB<GenericKvDB>();
1217     if (naturalStore == nullptr) {
1218         return -E_INVALID_DB;
1219     }
1220 
1221     if (!naturalStore->GenericKvDB::CheckWritePermission()) {
1222         return -E_READ_ONLY;
1223     }
1224 
1225     for (const auto &entry : entries) {
1226         int errCode = naturalStore->GenericKvDB::CheckDataStatus(entry.key, entry.value, false);
1227         if (errCode != E_OK) {
1228             return errCode;
1229         }
1230     }
1231     return E_OK;
1232 }
1233 
CheckLocalKeysValid(const std::vector<Key> & keys) const1234 int SQLiteSingleVerNaturalStoreConnection::CheckLocalKeysValid(const std::vector<Key> &keys) const
1235 {
1236     if (keys.size() > DBConstant::MAX_BATCH_SIZE) {
1237         return -E_INVALID_ARGS;
1238     }
1239 
1240     GenericKvDB *naturalStore = GetDB<GenericKvDB>();
1241     if (naturalStore == nullptr) {
1242         return -E_INVALID_DB;
1243     }
1244 
1245     if (!naturalStore->GenericKvDB::CheckWritePermission()) {
1246         return -E_READ_ONLY;
1247     }
1248 
1249     for (const auto &key : keys) {
1250         int errCode = naturalStore->GenericKvDB::CheckDataStatus(key, {}, true);
1251         if (errCode != E_OK) {
1252             return errCode;
1253         }
1254     }
1255     return E_OK;
1256 }
1257 
CommitAndReleaseNotifyData(SingleVerNaturalStoreCommitNotifyData * & committedData,bool isNeedCommit,int eventType)1258 void SQLiteSingleVerNaturalStoreConnection::CommitAndReleaseNotifyData(
1259     SingleVerNaturalStoreCommitNotifyData *&committedData, bool isNeedCommit, int eventType)
1260 {
1261     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1262     if ((naturalStore != nullptr) && (committedData != nullptr)) {
1263         if (isNeedCommit) {
1264             if (!committedData->IsChangedDataEmpty()) {
1265                 naturalStore->CommitNotify(eventType, committedData);
1266             }
1267             if (!committedData->IsConflictedDataEmpty()) {
1268                 naturalStore->CommitNotify(SQLITE_GENERAL_CONFLICT_EVENT, committedData);
1269             }
1270         }
1271     }
1272     ReleaseCommitData(committedData);
1273 }
1274 
StartTransactionInner(TransactType transType)1275 int SQLiteSingleVerNaturalStoreConnection::StartTransactionInner(TransactType transType)
1276 {
1277     if (IsExtendedCacheDBMode()) {
1278         return StartTransactionInCacheMode(transType);
1279     } else {
1280         return StartTransactionNormally(transType);
1281     }
1282 }
1283 
StartTransactionInCacheMode(TransactType transType)1284 int SQLiteSingleVerNaturalStoreConnection::StartTransactionInCacheMode(TransactType transType)
1285 {
1286     int errCode = E_OK;
1287     SQLiteSingleVerStorageExecutor *handle = GetExecutor(true, errCode);
1288     if (handle == nullptr) {
1289         return errCode;
1290     }
1291     if (CheckLogOverLimit(handle)) {
1292         LOGW("Over the log limit");
1293         ReleaseExecutor(handle);
1294         return -E_LOG_OVER_LIMITS;
1295     }
1296     errCode = handle->StartTransaction(transType);
1297     if (errCode != E_OK) {
1298         ReleaseExecutor(handle);
1299         return errCode;
1300     }
1301 
1302     writeHandle_ = handle;
1303     transactionEntrySize_ = 0;
1304     return E_OK;
1305 }
1306 
StartTransactionNormally(TransactType transType)1307 int SQLiteSingleVerNaturalStoreConnection::StartTransactionNormally(TransactType transType)
1308 {
1309     int errCode = E_OK;
1310     SQLiteSingleVerStorageExecutor *handle = GetExecutor(true, errCode);
1311     if (handle == nullptr) {
1312         return errCode;
1313     }
1314     if (CheckLogOverLimit(handle)) {
1315         LOGW("Over the log limit");
1316         ReleaseExecutor(handle);
1317         return -E_LOG_OVER_LIMITS;
1318     }
1319 
1320     if (committedData_ == nullptr) {
1321         committedData_ = new (std::nothrow) SingleVerNaturalStoreCommitNotifyData;
1322         if (committedData_ == nullptr) {
1323             ReleaseExecutor(handle);
1324             return -E_OUT_OF_MEMORY;
1325         }
1326         InitConflictNotifiedFlag();
1327     }
1328     if (localCommittedData_ == nullptr) {
1329         localCommittedData_ = new (std::nothrow) SingleVerNaturalStoreCommitNotifyData;
1330         if (localCommittedData_ == nullptr) {
1331             ReleaseExecutor(handle);
1332             ReleaseCommitData(committedData_);
1333             return -E_OUT_OF_MEMORY;
1334         }
1335     }
1336     errCode = handle->StartTransaction(transType);
1337     if (errCode != E_OK) {
1338         ReleaseExecutor(handle);
1339         ReleaseCommitData(committedData_);
1340         ReleaseCommitData(localCommittedData_);
1341         return errCode;
1342     }
1343 
1344     writeHandle_ = handle;
1345     transactionEntrySize_ = 0;
1346     return E_OK;
1347 }
1348 
InitConflictNotifiedFlag()1349 void SQLiteSingleVerNaturalStoreConnection::InitConflictNotifiedFlag()
1350 {
1351     unsigned int conflictFlag = 0;
1352     if (kvDB_->GetRegisterFunctionCount(CONFLICT_SINGLE_VERSION_NS_FOREIGN_KEY_ONLY) != 0) {
1353         conflictFlag |= static_cast<unsigned>(SQLITE_GENERAL_NS_FOREIGN_KEY_ONLY);
1354     }
1355     if (kvDB_->GetRegisterFunctionCount(CONFLICT_SINGLE_VERSION_NS_FOREIGN_KEY_ORIG) != 0) {
1356         conflictFlag |= static_cast<unsigned>(SQLITE_GENERAL_NS_FOREIGN_KEY_ORIG);
1357     }
1358     if (kvDB_->GetRegisterFunctionCount(CONFLICT_SINGLE_VERSION_NS_NATIVE_ALL) != 0) {
1359         conflictFlag |= static_cast<unsigned>(SQLITE_GENERAL_NS_NATIVE_ALL);
1360     }
1361 
1362     committedData_->SetConflictedNotifiedFlag(static_cast<int>(conflictFlag));
1363 }
1364 
CommitInner()1365 int SQLiteSingleVerNaturalStoreConnection::CommitInner()
1366 {
1367     bool isCacheOrMigrating = IsExtendedCacheDBMode();
1368 
1369     int errCode = writeHandle_->Commit();
1370     ReleaseExecutor(writeHandle_);
1371     transactionEntrySize_ = 0;
1372 
1373     if (!isCacheOrMigrating) {
1374         CommitAndReleaseNotifyData(committedData_, true, SQLITE_GENERAL_NS_PUT_EVENT);
1375         CommitAndReleaseNotifyData(localCommittedData_, true, SQLITE_GENERAL_NS_LOCAL_PUT_EVENT);
1376     }
1377     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1378     if (naturalStore == nullptr) {
1379         return -E_INVALID_DB;
1380     }
1381     naturalStore->SetMaxTimestamp(currentMaxTimestamp_);
1382 
1383     if (isCacheOrMigrating) {
1384         naturalStore->IncreaseCacheRecordVersion();
1385     }
1386     return errCode;
1387 }
1388 
RollbackInner()1389 int SQLiteSingleVerNaturalStoreConnection::RollbackInner()
1390 {
1391     int errCode = writeHandle_->Rollback();
1392     transactionEntrySize_ = 0;
1393     currentMaxTimestamp_ = 0;
1394     if (!IsExtendedCacheDBMode()) {
1395         ReleaseCommitData(committedData_);
1396         ReleaseCommitData(localCommittedData_);
1397     }
1398     ReleaseExecutor(writeHandle_);
1399     return errCode;
1400 }
1401 
GetExecutor(bool isWrite,int & errCode) const1402 SQLiteSingleVerStorageExecutor *SQLiteSingleVerNaturalStoreConnection::GetExecutor(bool isWrite, int &errCode) const
1403 {
1404     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1405     if (naturalStore == nullptr) {
1406         errCode = -E_NOT_INIT;
1407         LOGE("[SingleVerConnection] the store is null");
1408         return nullptr;
1409     }
1410     return naturalStore->GetHandle(isWrite, errCode);
1411 }
1412 
IsCacheDBMode() const1413 bool SQLiteSingleVerNaturalStoreConnection::IsCacheDBMode() const
1414 {
1415     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1416     if (naturalStore == nullptr) {
1417         LOGE("[SingleVerConnection] the store is null");
1418         return false;
1419     }
1420     return naturalStore->IsCacheDBMode();
1421 }
1422 
IsExtendedCacheDBMode() const1423 bool SQLiteSingleVerNaturalStoreConnection::IsExtendedCacheDBMode() const
1424 {
1425     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1426     if (naturalStore == nullptr) {
1427         LOGE("[SingleVerConnection] the store is null");
1428         return false;
1429     }
1430     return naturalStore->IsExtendedCacheDBMode();
1431 }
1432 
ReleaseExecutor(SQLiteSingleVerStorageExecutor * & executor) const1433 void SQLiteSingleVerNaturalStoreConnection::ReleaseExecutor(SQLiteSingleVerStorageExecutor *&executor) const
1434 {
1435     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1436     if (naturalStore != nullptr) {
1437         naturalStore->ReleaseHandle(executor);
1438     }
1439 }
1440 
PublishLocal(const Key & key,bool deleteLocal,bool updateTimestamp,const KvStoreNbPublishAction & onConflict)1441 int SQLiteSingleVerNaturalStoreConnection::PublishLocal(const Key &key, bool deleteLocal, bool updateTimestamp,
1442     const KvStoreNbPublishAction &onConflict)
1443 {
1444     int errCode = CheckWritePermission();
1445     if (errCode != E_OK) {
1446         return errCode;
1447     }
1448 
1449     bool isNeedCallback = (onConflict != nullptr);
1450     SingleVerRecord localRecord;
1451     localRecord.key = key;
1452     SingleVerRecord syncRecord;
1453     {
1454         if (IsTransactionStarted()) {
1455             return -E_NOT_SUPPORT;
1456         }
1457         std::lock_guard<std::mutex> lock(transactionMutex_);
1458         errCode = StartTransactionInner(TransactType::IMMEDIATE);
1459         if (errCode != E_OK) {
1460             return errCode;
1461         }
1462 
1463         SingleVerNaturalStoreCommitNotifyData *localCommittedData = nullptr;
1464         if (deleteLocal) {
1465             localCommittedData = new (std::nothrow) SingleVerNaturalStoreCommitNotifyData;
1466             if (localCommittedData == nullptr) {
1467                 errCode = -E_OUT_OF_MEMORY;
1468             }
1469         }
1470         if (errCode == E_OK) {
1471             errCode = PublishInner(localCommittedData, updateTimestamp, localRecord, syncRecord, isNeedCallback);
1472         }
1473 
1474         if (errCode != E_OK || isNeedCallback) {
1475             int innerCode = RollbackInner();
1476             errCode = (innerCode != E_OK) ? innerCode : errCode;
1477         } else {
1478             errCode = CommitInner();
1479             if (errCode == E_OK) {
1480                 CommitAndReleaseNotifyData(localCommittedData, true, SQLITE_GENERAL_NS_LOCAL_PUT_EVENT);
1481             }
1482         }
1483         ReleaseCommitData(localCommittedData);
1484     }
1485 
1486     // need to release the handle lock before callback invoked
1487     if (isNeedCallback) {
1488         return PublishLocalCallback(updateTimestamp, localRecord, syncRecord, onConflict);
1489     }
1490 
1491     return errCode;
1492 }
1493 
PublishLocalCallback(bool updateTimestamp,const SingleVerRecord & localRecord,const SingleVerRecord & syncRecord,const KvStoreNbPublishAction & onConflict)1494 int SQLiteSingleVerNaturalStoreConnection::PublishLocalCallback(bool updateTimestamp,
1495     const SingleVerRecord &localRecord, const SingleVerRecord &syncRecord, const KvStoreNbPublishAction &onConflict)
1496 {
1497     bool isLocalLastest = updateTimestamp ? true : (localRecord.timestamp > syncRecord.writeTimestamp);
1498     if ((syncRecord.flag & DataItem::DELETE_FLAG) == DataItem::DELETE_FLAG) {
1499         onConflict({localRecord.key, localRecord.value}, nullptr, isLocalLastest);
1500     } else {
1501         Entry syncEntry = {syncRecord.key, syncRecord.value};
1502         onConflict({localRecord.key, localRecord.value}, &syncEntry, isLocalLastest);
1503     }
1504     return E_OK;
1505 }
1506 
PublishInner(SingleVerNaturalStoreCommitNotifyData * committedData,bool updateTimestamp,SingleVerRecord & localRecord,SingleVerRecord & syncRecord,bool & isNeedCallback)1507 int SQLiteSingleVerNaturalStoreConnection::PublishInner(SingleVerNaturalStoreCommitNotifyData *committedData,
1508     bool updateTimestamp, SingleVerRecord &localRecord, SingleVerRecord &syncRecord, bool &isNeedCallback)
1509 {
1510     Key hashKey;
1511     int errCode = DBCommon::CalcValueHash(localRecord.key, hashKey);
1512     if (errCode != E_OK) {
1513         return errCode;
1514     }
1515 
1516     if (committedData != nullptr) {
1517         errCode = writeHandle_->DeleteLocalKvData(localRecord.key, committedData, localRecord.value,
1518             localRecord.timestamp);
1519         if (errCode != E_OK) {
1520             LOGE("Delete local kv data err:%d", errCode);
1521             return errCode;
1522         }
1523     } else {
1524         if (!writeHandle_->CheckIfKeyExisted(localRecord.key, true, localRecord.value, localRecord.timestamp)) {
1525             LOGE("Record not found.");
1526             return -E_NOT_FOUND;
1527         }
1528     }
1529 
1530     // begin to insert entry to sync table
1531     errCode = CheckDataStatus(localRecord.key, localRecord.value, false);
1532     if (errCode != E_OK) {
1533         return errCode;
1534     }
1535 
1536     errCode = writeHandle_->GetKvDataByHashKey(hashKey, syncRecord);
1537     if (errCode == E_OK) { // has conflict record
1538         if (isNeedCallback) {
1539             return errCode;
1540         }
1541         // fix conflict with LAST_WIN policy
1542         if (updateTimestamp) { // local win
1543             errCode = SaveEntry({localRecord.key, localRecord.value}, false);
1544         } else {
1545             if (localRecord.timestamp <= syncRecord.writeTimestamp) { // sync win
1546                 errCode = -E_STALE;
1547             } else {
1548                 errCode = SaveEntry({localRecord.key, localRecord.value}, false, localRecord.timestamp);
1549             }
1550         }
1551     } else {
1552         isNeedCallback = false;
1553         if (errCode == -E_NOT_FOUND) {
1554             errCode = SaveEntry({localRecord.key, localRecord.value}, false, localRecord.timestamp);
1555         }
1556     }
1557     return errCode;
1558 }
1559 
UnpublishToLocal(const Key & key,bool deletePublic,bool updateTimestamp)1560 int SQLiteSingleVerNaturalStoreConnection::UnpublishToLocal(const Key &key, bool deletePublic, bool updateTimestamp)
1561 {
1562     int errCode = CheckWritePermission();
1563     if (errCode != E_OK) {
1564         return errCode;
1565     }
1566 
1567     if (IsTransactionStarted()) {
1568         return -E_NOT_SUPPORT;
1569     }
1570 
1571     std::lock_guard<std::mutex> lock(transactionMutex_);
1572 
1573     errCode = StartTransactionInner(TransactType::IMMEDIATE);
1574     if (errCode != E_OK) {
1575         return errCode;
1576     }
1577 
1578     Key hashKey;
1579     int innerErrCode = E_OK;
1580     SingleVerRecord syncRecord;
1581     SingleVerNaturalStoreCommitNotifyData *localCommittedData = nullptr;
1582     errCode = DBCommon::CalcValueHash(key, hashKey);
1583     if (errCode != E_OK) {
1584         goto END;
1585     }
1586 
1587     errCode = writeHandle_->GetKvDataByHashKey(hashKey, syncRecord);
1588     if (errCode != E_OK) {
1589         goto END;
1590     }
1591 
1592     syncRecord.key = key;
1593     errCode = UnpublishInner(localCommittedData, syncRecord, updateTimestamp, innerErrCode);
1594     if (errCode != E_OK) {
1595         goto END;
1596     }
1597 
1598     if (deletePublic && (syncRecord.flag & DataItem::DELETE_FLAG) != DataItem::DELETE_FLAG) {
1599         errCode = SaveEntry({hashKey, {}}, true);
1600         if (errCode != E_OK) {
1601             goto END;
1602         }
1603     }
1604 
1605 END:
1606     // finalize
1607     if (errCode != E_OK) {
1608         int rollbackRet = RollbackInner();
1609         errCode = (rollbackRet != E_OK) ? rollbackRet : errCode;
1610     } else {
1611         errCode = CommitInner();
1612         if (errCode == E_OK) {
1613             CommitAndReleaseNotifyData(localCommittedData, true, SQLITE_GENERAL_NS_LOCAL_PUT_EVENT);
1614         }
1615     }
1616     ReleaseCommitData(localCommittedData);
1617 
1618     return (errCode == E_OK) ? innerErrCode : errCode;
1619 }
1620 
UnpublishInner(SingleVerNaturalStoreCommitNotifyData * & committedData,const SingleVerRecord & syncRecord,bool updateTimestamp,int & innerErrCode)1621 int SQLiteSingleVerNaturalStoreConnection::UnpublishInner(SingleVerNaturalStoreCommitNotifyData *&committedData,
1622     const SingleVerRecord &syncRecord, bool updateTimestamp, int &innerErrCode)
1623 {
1624     int errCode = E_OK;
1625     int localOperation = static_cast<int>(LocalOperType::LOCAL_OPR_NONE);
1626     SingleVerRecord localRecord;
1627 
1628     innerErrCode = -E_LOCAL_DEFEAT;
1629     if (writeHandle_->CheckIfKeyExisted(syncRecord.key, true, localRecord.value, localRecord.timestamp)) {
1630         if ((syncRecord.flag & DataItem::DELETE_FLAG) == DataItem::DELETE_FLAG) {
1631             if (updateTimestamp || localRecord.timestamp <= syncRecord.writeTimestamp) { // sync win
1632                 innerErrCode = -E_LOCAL_DELETED;
1633                 localOperation = static_cast<int>(LocalOperType::LOCAL_OPR_DEL);
1634             }
1635         } else if (updateTimestamp || localRecord.timestamp <= syncRecord.writeTimestamp) { // sync win
1636             innerErrCode = -E_LOCAL_COVERED;
1637             localOperation = static_cast<int>(LocalOperType::LOCAL_OPR_PUT);
1638         }
1639     } else { // no conflict entry in local
1640         innerErrCode = E_OK;
1641         if ((syncRecord.flag & DataItem::DELETE_FLAG) != DataItem::DELETE_FLAG) {
1642             localOperation = static_cast<int>(LocalOperType::LOCAL_OPR_PUT);
1643         }
1644     }
1645 
1646     if (localOperation != static_cast<int>(LocalOperType::LOCAL_OPR_NONE)) {
1647         errCode = UnpublishOper(committedData, syncRecord, updateTimestamp, localOperation);
1648     }
1649 
1650     return errCode;
1651 }
1652 
UnpublishOper(SingleVerNaturalStoreCommitNotifyData * & committedData,const SingleVerRecord & syncRecord,bool updateTimestamp,int operType)1653 int SQLiteSingleVerNaturalStoreConnection::UnpublishOper(SingleVerNaturalStoreCommitNotifyData *&committedData,
1654     const SingleVerRecord &syncRecord, bool updateTimestamp, int operType)
1655 {
1656     committedData = new (std::nothrow) SingleVerNaturalStoreCommitNotifyData;
1657     if (committedData == nullptr) {
1658         return -E_OUT_OF_MEMORY;
1659     }
1660 
1661     int errCode = E_OK;
1662     if (operType == static_cast<int>(LocalOperType::LOCAL_OPR_PUT)) {
1663         SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1664         if (naturalStore == nullptr) {
1665             return -E_INVALID_DB;
1666         }
1667 
1668         errCode = CheckDataStatus(syncRecord.key, syncRecord.value, false);
1669         if (errCode != E_OK) {
1670             return errCode;
1671         }
1672 
1673         Timestamp time = updateTimestamp ? naturalStore->GetCurrentTimestamp() : syncRecord.writeTimestamp;
1674         errCode = writeHandle_->PutKvData(SingleVerDataType::LOCAL_TYPE, syncRecord.key, syncRecord.value, time,
1675             committedData);
1676     } else if (operType == static_cast<int>(LocalOperType::LOCAL_OPR_DEL)) {
1677         Timestamp localTimestamp = 0;
1678         Value value;
1679         errCode = writeHandle_->DeleteLocalKvData(syncRecord.key, committedData, value, localTimestamp);
1680     }
1681 
1682     return errCode;
1683 }
1684 
ReleaseCommitData(SingleVerNaturalStoreCommitNotifyData * & committedData)1685 void SQLiteSingleVerNaturalStoreConnection::ReleaseCommitData(SingleVerNaturalStoreCommitNotifyData *&committedData)
1686 {
1687     if (committedData != nullptr) {
1688         committedData->DecObjRef(committedData);
1689         committedData = nullptr;
1690     }
1691 }
1692 
PragmaPublish(void * parameter)1693 int SQLiteSingleVerNaturalStoreConnection::PragmaPublish(void *parameter)
1694 {
1695     PragmaPublishInfo *info = static_cast<PragmaPublishInfo *>(parameter);
1696     if (info == nullptr) {
1697         return -E_INVALID_ARGS;
1698     }
1699     if (IsExtendedCacheDBMode()) {
1700         int err = IsCacheDBMode() ? -E_EKEYREVOKED : -E_BUSY;
1701         LOGE("[PragmaPublish]Existed cache database can not read data, errCode = [%d]!", err);
1702         return err;
1703     }
1704     return PublishLocal(info->key, info->deleteLocal, info->updateTimestamp, info->action);
1705 }
1706 
PragmaUnpublish(void * parameter)1707 int SQLiteSingleVerNaturalStoreConnection::PragmaUnpublish(void *parameter)
1708 {
1709     PragmaUnpublishInfo *info = static_cast<PragmaUnpublishInfo *>(parameter);
1710     if (info == nullptr) {
1711         return -E_INVALID_ARGS;
1712     }
1713     if (IsExtendedCacheDBMode()) {
1714         int err = IsCacheDBMode() ? -E_EKEYREVOKED : -E_BUSY;
1715         LOGE("[PragmaUnpublish]Existed cache database can not read data, errCode = [%d]!", err);
1716         return err;
1717     }
1718     return UnpublishToLocal(info->key, info->isDeleteSync, info->isUpdateTime);
1719 }
1720 
PragmaSetAutoLifeCycle(const uint32_t * lifeTime)1721 int SQLiteSingleVerNaturalStoreConnection::PragmaSetAutoLifeCycle(const uint32_t *lifeTime)
1722 {
1723     if (lifeTime == nullptr || *lifeTime > MAX_AUTO_LIFE_CYCLE || *lifeTime < MIN_AUTO_LIFE_CYCLE) {
1724         return -E_INVALID_ARGS;
1725     }
1726     if (kvDB_ == nullptr) {
1727         return -E_INVALID_DB;
1728     }
1729     return static_cast<SQLiteSingleVerNaturalStore *>(kvDB_)->SetAutoLifeCycleTime(*lifeTime);
1730 }
1731 
PragmaResultSetCacheMode(PragmaData inMode)1732 int SQLiteSingleVerNaturalStoreConnection::PragmaResultSetCacheMode(PragmaData inMode)
1733 {
1734     if (inMode == nullptr) {
1735         return -E_INVALID_ARGS;
1736     }
1737     auto mode = *(static_cast<ResultSetCacheMode *>(inMode));
1738     if (mode != ResultSetCacheMode::CACHE_FULL_ENTRY && mode != ResultSetCacheMode::CACHE_ENTRY_ID_ONLY) {
1739         return -E_INVALID_ARGS;
1740     }
1741     cacheModeForNewResultSet_.store(mode);
1742     return E_OK;
1743 }
1744 
PragmaResultSetCacheMaxSize(PragmaData inSize)1745 int SQLiteSingleVerNaturalStoreConnection::PragmaResultSetCacheMaxSize(PragmaData inSize)
1746 {
1747     if (inSize == nullptr) {
1748         return -E_INVALID_ARGS;
1749     }
1750     int size = *(static_cast<int *>(inSize));
1751     if (size < RESULT_SET_CACHE_MAX_SIZE_MIN || size > RESULT_SET_CACHE_MAX_SIZE_MAX) {
1752         return -E_INVALID_ARGS;
1753     }
1754     cacheMaxSizeForNewResultSet_.store(size);
1755     return E_OK;
1756 }
1757 
1758 // use for getkvstore migrating cache data
PragmaTriggerToMigrateData(const SecurityOption & secOption) const1759 int SQLiteSingleVerNaturalStoreConnection::PragmaTriggerToMigrateData(const SecurityOption &secOption) const
1760 {
1761     if ((secOption.securityLabel != S3) || (secOption.securityFlag != SECE)) {
1762         LOGD("Only S3 SECE data need migrate data!");
1763         return E_OK;
1764     }
1765 
1766     LOGI("Begin trigger the migration data while open the database!");
1767     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1768     if (naturalStore == nullptr) {
1769         return -E_INVALID_CONNECTION;
1770     }
1771     return naturalStore->TriggerToMigrateData();
1772 }
1773 
CheckAmendValueContentForLocalProcedure(const Value & oriValue,Value & amendValue) const1774 int SQLiteSingleVerNaturalStoreConnection::CheckAmendValueContentForLocalProcedure(const Value &oriValue,
1775     Value &amendValue) const
1776 {
1777     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1778     if (naturalStore == nullptr) { // Not Likely
1779         return -E_INVALID_DB;
1780     }
1781     bool useAmendValue = false;
1782     return naturalStore->CheckValueAndAmendIfNeed(ValueSource::FROM_LOCAL, oriValue, amendValue, useAmendValue);
1783 }
1784 
CheckLogOverLimit(SQLiteSingleVerStorageExecutor * executor) const1785 bool SQLiteSingleVerNaturalStoreConnection::CheckLogOverLimit(SQLiteSingleVerStorageExecutor *executor) const
1786 {
1787     SQLiteSingleVerNaturalStore *naturalStore = GetDB<SQLiteSingleVerNaturalStore>();
1788     if (naturalStore == nullptr || executor == nullptr) { // Not Likely
1789         return false;
1790     }
1791     uint64_t logFileSize = executor->GetLogFileSize();
1792     bool result = logFileSize > naturalStore->GetMaxLogSize();
1793     if (result) {
1794         LOGW("Log size[%" PRIu64 "] over the limit", logFileSize);
1795     }
1796     return result;
1797 }
1798 
CalcHashDevID(PragmaDeviceIdentifier & pragmaDev)1799 int SQLiteSingleVerNaturalStoreConnection::CalcHashDevID(PragmaDeviceIdentifier &pragmaDev)
1800 {
1801     if (pragmaDev.deviceID.empty()) {
1802         return -E_INVALID_ARGS;
1803     }
1804     pragmaDev.deviceIdentifier = DBCommon::TransferHashString(pragmaDev.deviceID);
1805     return E_OK;
1806 }
1807 
UpdateKey(const DistributedDB::UpdateKeyCallback & callback)1808 int SQLiteSingleVerNaturalStoreConnection::UpdateKey(const DistributedDB::UpdateKeyCallback &callback)
1809 {
1810     if (IsExtendedCacheDBMode()) {
1811         LOGE("[Connection] Not support update key in cache mode");
1812         return -E_NOT_SUPPORT;
1813     }
1814     int errCode = E_OK;
1815     {
1816         std::lock_guard<std::mutex> lock(transactionMutex_);
1817         if (writeHandle_ != nullptr) {
1818             LOGD("[Connection] Transaction started already.");
1819             errCode = writeHandle_->UpdateKey(callback);
1820             return errCode;
1821         }
1822     }
1823 
1824     SQLiteSingleVerStorageExecutor *handle = GetExecutor(true, errCode);
1825     if (handle == nullptr) {
1826         LOGE("[Connection]::[UpdateKey] Get executor failed, errCode = [%d]", errCode);
1827         return errCode;
1828     }
1829 
1830     errCode = handle->UpdateKey(callback);
1831     ReleaseExecutor(handle);
1832     return errCode;
1833 }
1834 DEFINE_OBJECT_TAG_FACILITIES(SQLiteSingleVerNaturalStoreConnection)
1835 }