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