• 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.h"
17 
18 #include <algorithm>
19 #include <thread>
20 #include <chrono>
21 
22 #include "data_compression.h"
23 #include "db_common.h"
24 #include "db_constant.h"
25 #include "db_dump_helper.h"
26 #include "db_dfx_adapter.h"
27 #include "db_errno.h"
28 #include "generic_single_ver_kv_entry.h"
29 #include "intercepted_data_impl.h"
30 #include "kvdb_utils.h"
31 #include "log_print.h"
32 #include "platform_specific.h"
33 #include "schema_object.h"
34 #include "single_ver_database_oper.h"
35 #include "single_ver_utils.h"
36 #include "storage_engine_manager.h"
37 #include "sqlite_single_ver_natural_store_connection.h"
38 #include "time_helper.h"
39 #include "value_hash_calc.h"
40 
41 namespace DistributedDB {
42 namespace {
43     constexpr int WAIT_DELEGATE_CALLBACK_TIME = 100;
44 
45     constexpr int DEVICE_ID_LEN = 32;
46     const std::string CREATE_DB_TIME = "createDBTime";
47 
48     // Called when get multiple dev data.
49     // deviceID is the device which currently being getting. When getting one dev data, deviceID is "".
50     // dataItems is the DataItems which already be get from DB sorted by timestamp.
51     // token must not be null.
ProcessContinueToken(const DeviceID & deviceID,const std::vector<DataItem> & dataItems,int & errCode,SQLiteSingleVerContinueToken * & token)52     void ProcessContinueToken(const DeviceID &deviceID, const std::vector<DataItem> &dataItems, int &errCode,
53         SQLiteSingleVerContinueToken *&token)
54     {
55         if (errCode != -E_UNFINISHED) { // Error happened or get data finished. Token should be cleared.
56             delete token;
57             token = nullptr;
58             return;
59         }
60 
61         if (dataItems.empty()) {
62             errCode = -E_INTERNAL_ERROR;
63             LOGE("Get data unfinished but dataitems is empty.");
64             delete token;
65             token = nullptr;
66             return;
67         }
68 
69         Timestamp nextBeginTime = dataItems.back().timestamp + 1;
70         if (nextBeginTime > INT64_MAX) {
71             nextBeginTime = INT64_MAX;
72         }
73         token->SetNextBeginTime(deviceID, nextBeginTime);
74         return;
75     }
76 
77     // Called when get one dev data.
ProcessContinueToken(const std::vector<DataItem> & dataItems,int & errCode,SQLiteSingleVerContinueToken * & token)78     void ProcessContinueToken(const std::vector<DataItem> &dataItems, int &errCode,
79         SQLiteSingleVerContinueToken *&token)
80     {
81         ProcessContinueToken("", dataItems, errCode, token);
82     }
83 
84     // Called when get query sync data.
85     // dataItems is the DataItems which already be get from DB sorted by timestamp.
86     // token must not be null.
ProcessContinueTokenForQuerySync(const std::vector<DataItem> & dataItems,int & errCode,SQLiteSingleVerContinueToken * & token)87     void ProcessContinueTokenForQuerySync(const std::vector<DataItem> &dataItems, int &errCode,
88         SQLiteSingleVerContinueToken *&token)
89     {
90         if (errCode != -E_UNFINISHED) { // Error happened or get data finished. Token should be cleared.
91             delete token;
92             token = nullptr;
93             return;
94         }
95 
96         if (dataItems.empty()) {
97             errCode = -E_INTERNAL_ERROR;
98             LOGE("Get data unfinished but dataitems is empty.");
99             delete token;
100             token = nullptr;
101             return;
102         }
103 
104         Timestamp nextBeginTime = dataItems.back().timestamp + 1;
105         if (nextBeginTime > INT64_MAX) {
106             nextBeginTime = INT64_MAX;
107         }
108         bool getDeleteData = ((dataItems.back().flag & DataItem::DELETE_FLAG) != 0);
109         if (getDeleteData) {
110             token->FinishGetQueryData();
111             token->SetDeletedNextBeginTime("", nextBeginTime);
112         } else {
113             token->SetNextBeginTime("", nextBeginTime);
114         }
115         return;
116     }
117 
UpdateSecProperties(KvDBProperties & properties,bool isReadOnly,const SchemaObject & savedSchemaObj,const SQLiteSingleVerStorageEngine * engine)118     void UpdateSecProperties(KvDBProperties &properties, bool isReadOnly, const SchemaObject &savedSchemaObj,
119         const SQLiteSingleVerStorageEngine *engine)
120     {
121         if (isReadOnly) {
122             properties.SetSchema(savedSchemaObj);
123             properties.SetBoolProp(KvDBProperties::FIRST_OPEN_IS_READ_ONLY, true);
124         }
125         // Update the security option from the storage engine for that
126         // we will not update the security label and flag for the existed database.
127         // So the security label and flag are from the existed database.
128         if (engine == nullptr) {
129             return;
130         }
131         properties.SetIntProp(KvDBProperties::SECURITY_LABEL, engine->GetSecurityOption().securityLabel);
132         properties.SetIntProp(KvDBProperties::SECURITY_FLAG, engine->GetSecurityOption().securityFlag);
133     }
134 
GetKvEntriesByDataItems(std::vector<SingleVerKvEntry * > & entries,std::vector<DataItem> & dataItems)135     int GetKvEntriesByDataItems(std::vector<SingleVerKvEntry *> &entries, std::vector<DataItem> &dataItems)
136     {
137         int errCode = E_OK;
138         for (auto &item : dataItems) {
139             auto entry = new (std::nothrow) GenericSingleVerKvEntry();
140             if (entry == nullptr) {
141                 errCode = -E_OUT_OF_MEMORY;
142                 LOGE("GetKvEntries failed, errCode:%d", errCode);
143                 SingleVerKvEntry::Release(entries);
144                 break;
145             }
146             entry->SetEntryData(std::move(item));
147             entries.push_back(entry);
148         }
149         return errCode;
150     }
151 
CanHoldDeletedData(const std::vector<DataItem> & dataItems,const DataSizeSpecInfo & dataSizeInfo,size_t appendLen)152     bool CanHoldDeletedData(const std::vector<DataItem> &dataItems, const DataSizeSpecInfo &dataSizeInfo,
153         size_t appendLen)
154     {
155         bool reachThreshold = false;
156         size_t blockSize = 0;
157         for (size_t i = 0; !reachThreshold && i < dataItems.size(); i++) {
158             blockSize += SQLiteSingleVerStorageExecutor::GetDataItemSerialSize(dataItems[i], appendLen);
159             reachThreshold = (blockSize >= dataSizeInfo.blockSize * DBConstant::QUERY_SYNC_THRESHOLD);
160         }
161         return !reachThreshold;
162     }
163 }
164 
SQLiteSingleVerNaturalStore()165 SQLiteSingleVerNaturalStore::SQLiteSingleVerNaturalStore()
166     : storageEngine_(nullptr),
167       notificationEventsRegistered_(false),
168       notificationConflictEventsRegistered_(false),
169       isInitialized_(false),
170       isReadOnly_(false),
171       lifeCycleNotifier_(nullptr),
172       lifeTimerId_(0),
173       autoLifeTime_(DBConstant::DEF_LIFE_CYCLE_TIME),
174       createDBTime_(0),
175       pushDataInterceptor_(nullptr),
176       receiveDataInterceptor_(nullptr),
177       maxLogSize_(DBConstant::MAX_LOG_SIZE_DEFAULT),
178       abortPerm_(OperatePerm::NORMAL_PERM),
179       sqliteCloudKvStore_(nullptr)
180 {}
181 
~SQLiteSingleVerNaturalStore()182 SQLiteSingleVerNaturalStore::~SQLiteSingleVerNaturalStore()
183 {
184     ReleaseResources();
185 }
186 
SetUserVer(const KvDBProperties & kvDBProp,int version)187 int SQLiteSingleVerNaturalStore::SetUserVer(const KvDBProperties &kvDBProp, int version)
188 {
189     OpenDbProperties properties;
190     properties.uri = GetDatabasePath(kvDBProp);
191     bool isEncryptedDb = kvDBProp.GetBoolProp(KvDBProperties::ENCRYPTED_MODE, false);
192     if (isEncryptedDb) { // LCOV_EXCL_BR_LINE
193         kvDBProp.GetPassword(properties.cipherType, properties.passwd);
194     }
195 
196     int errCode = SQLiteUtils::SetUserVer(properties, version);
197     if (errCode != E_OK) { // LCOV_EXCL_BR_LINE
198         LOGE("Recover for open db failed in single version:%d", errCode);
199     }
200     return errCode;
201 }
202 
InitDatabaseContext(const KvDBProperties & kvDBProp,bool isNeedUpdateSecOpt)203 int SQLiteSingleVerNaturalStore::InitDatabaseContext(const KvDBProperties &kvDBProp, bool isNeedUpdateSecOpt)
204 {
205     int errCode = InitStorageEngine(kvDBProp, isNeedUpdateSecOpt);
206     if (errCode != E_OK) {
207         return errCode;
208     }
209     return errCode;
210 }
211 
RegisterLifeCycleCallback(const DatabaseLifeCycleNotifier & notifier)212 int SQLiteSingleVerNaturalStore::RegisterLifeCycleCallback(const DatabaseLifeCycleNotifier &notifier)
213 {
214     std::lock_guard<std::mutex> lock(lifeCycleMutex_);
215     int errCode;
216     if (!notifier) {
217         if (lifeTimerId_ == 0) {
218             return E_OK;
219         }
220         errCode = StopLifeCycleTimer();
221         if (errCode != E_OK) {
222             LOGE("Stop the life cycle timer failed:%d", errCode);
223         }
224         return E_OK;
225     }
226 
227     if (lifeTimerId_ != 0) {
228         errCode = StopLifeCycleTimer();
229         if (errCode != E_OK) { // LCOV_EXCL_BR_LINE
230             LOGE("Stop the life cycle timer failed:%d", errCode);
231         }
232     }
233     errCode = StartLifeCycleTimer(notifier);
234     if (errCode != E_OK) {
235         LOGE("Register life cycle timer failed:%d", errCode);
236     }
237     return errCode;
238 }
239 
SetAutoLifeCycleTime(uint32_t time)240 int SQLiteSingleVerNaturalStore::SetAutoLifeCycleTime(uint32_t time)
241 {
242     std::lock_guard<std::mutex> lock(lifeCycleMutex_);
243     if (lifeTimerId_ == 0) {
244         autoLifeTime_ = time;
245     } else {
246         auto runtimeCxt = RuntimeContext::GetInstance();
247         if (runtimeCxt == nullptr) {
248             return -E_INVALID_ARGS;
249         }
250         LOGI("[SingleVer] Set life cycle to %u", time);
251         int errCode = runtimeCxt->ModifyTimer(lifeTimerId_, time);
252         if (errCode != E_OK) {
253             return errCode;
254         }
255         autoLifeTime_ = time;
256     }
257     return E_OK;
258 }
259 
GetSecurityOption(SecurityOption & option) const260 int SQLiteSingleVerNaturalStore::GetSecurityOption(SecurityOption &option) const
261 {
262     bool isMemDb = GetDbProperties().GetBoolProp(KvDBProperties::MEMORY_MODE, false);
263     if (isMemDb) { // LCOV_EXCL_BR_LINE
264         LOGI("[GetSecurityOption] MemDb, no need to get security option");
265         option = SecurityOption();
266         return -E_NOT_SUPPORT;
267     }
268     if (!RuntimeContext::GetInstance()->IsProcessSystemApiAdapterValid()) { // LCOV_EXCL_BR_LINE
269         LOGI("[GetSecurityOption] Not set api adapter");
270         return -E_NOT_SUPPORT;
271     }
272     option.securityLabel = GetDbProperties().GetSecLabel();
273     option.securityFlag = GetDbProperties().GetSecFlag();
274 
275     return E_OK;
276 }
277 
278 namespace {
OriValueCanBeUse(int errCode)279 inline bool OriValueCanBeUse(int errCode)
280 {
281     return (errCode == -E_VALUE_MATCH);
282 }
283 
AmendValueShouldBeUse(int errCode)284 inline bool AmendValueShouldBeUse(int errCode)
285 {
286     return (errCode == -E_VALUE_MATCH_AMENDED);
287 }
288 
IsValueMismatched(int errCode)289 inline bool IsValueMismatched(int errCode)
290 {
291     return (errCode == -E_VALUE_MISMATCH_FEILD_COUNT ||
292         errCode == -E_VALUE_MISMATCH_FEILD_TYPE ||
293         errCode == -E_VALUE_MISMATCH_CONSTRAINT);
294 }
295 }
296 
CheckValueAndAmendIfNeed(ValueSource sourceType,const Value & oriValue,Value & amendValue,bool & useAmendValue) const297 int SQLiteSingleVerNaturalStore::CheckValueAndAmendIfNeed(ValueSource sourceType, const Value &oriValue,
298     Value &amendValue, bool &useAmendValue) const
299 {
300     // oriValue size may already be checked previously, but check here const little
301     if (oriValue.size() > GetMaxValueSize()) {
302         return -E_INVALID_ARGS;
303     }
304     const SchemaObject &schemaObjRef = MyProp().GetSchemaConstRef();
305     if (!schemaObjRef.IsSchemaValid()) {
306         // Not a schema database, do not need to check more
307         return E_OK;
308     }
309     if (schemaObjRef.GetSchemaType() == SchemaType::JSON) { // LCOV_EXCL_BR_LINE
310         ValueObject valueObj;
311         int errCode = valueObj.Parse(oriValue.data(), oriValue.data() + oriValue.size(), schemaObjRef.GetSkipSize());
312         if (errCode != E_OK) {
313             return -E_INVALID_FORMAT;
314         }
315         errCode = schemaObjRef.CheckValueAndAmendIfNeed(sourceType, valueObj);
316         if (OriValueCanBeUse(errCode)) {
317             useAmendValue = false;
318             return E_OK;
319         }
320         if (AmendValueShouldBeUse(errCode)) {
321             std::string amended = valueObj.ToString();
322             if (amended.size() > GetMaxValueSize()) {
323                 LOGE("[SqlSinStore][CheckAmendValue] ValueSize=%zu exceed limit after amend.", amended.size());
324                 return -E_INVALID_FORMAT;
325             }
326             amendValue.clear();
327             amendValue.assign(amended.begin(), amended.end());
328             useAmendValue = true;
329             return E_OK;
330         }
331         if (IsValueMismatched(errCode)) {
332             return errCode;
333         }
334     } else {
335         int errCode = schemaObjRef.VerifyValue(sourceType, oriValue);
336         if (errCode == E_OK) { // LCOV_EXCL_BR_LINE
337             useAmendValue = false;
338             return E_OK;
339         }
340     }
341     // Any unexpected wrong
342     return -E_INVALID_FORMAT;
343 }
344 
CheckDatabaseRecovery(const KvDBProperties & kvDBProp)345 int SQLiteSingleVerNaturalStore::CheckDatabaseRecovery(const KvDBProperties &kvDBProp)
346 {
347     if (kvDBProp.GetBoolProp(KvDBProperties::MEMORY_MODE, false)) { // memory status not need recovery
348         return E_OK;
349     }
350     std::unique_ptr<SingleVerDatabaseOper> operation = std::make_unique<SingleVerDatabaseOper>(this, nullptr);
351     (void)operation->ClearExportedTempFiles(kvDBProp);
352     int errCode = operation->RekeyRecover(kvDBProp);
353     if (errCode != E_OK) {
354         LOGE("Recover from rekey failed in single version:%d", errCode);
355         return errCode;
356     }
357 
358     errCode = operation->ClearImportTempFile(kvDBProp);
359     if (errCode != E_OK) {
360         LOGE("Clear imported temp db failed in single version:%d", errCode);
361         return errCode;
362     }
363 
364     // Currently, Design for the consistency of directory and file setting secOption
365     errCode = ClearIncompleteDatabase(kvDBProp);
366     if (errCode != E_OK) {
367         LOGE("Clear incomplete database failed in single version:%d", errCode);
368         return errCode;
369     }
370     const std::string dataDir = kvDBProp.GetStringProp(KvDBProperties::DATA_DIR, "");
371     const std::string identifierDir = kvDBProp.GetStringProp(KvDBProperties::IDENTIFIER_DIR, "");
372     bool isCreate = kvDBProp.GetBoolProp(KvDBProperties::CREATE_IF_NECESSARY, true);
373     bool isMemoryDb = kvDBProp.GetBoolProp(KvDBProperties::MEMORY_MODE, false);
374     if (!isMemoryDb) { // LCOV_EXCL_BR_LINE
375         errCode = DBCommon::CreateStoreDirectory(dataDir, identifierDir, DBConstant::SINGLE_SUB_DIR, isCreate);
376         if (errCode != E_OK) {
377             LOGE("Create single version natural store directory failed:%d", errCode);
378         }
379     }
380     return errCode;
381 }
382 
GetAndInitStorageEngine(const KvDBProperties & kvDBProp)383 int SQLiteSingleVerNaturalStore::GetAndInitStorageEngine(const KvDBProperties &kvDBProp)
384 {
385     int errCode = E_OK;
386     {
387         std::unique_lock<std::shared_mutex> lock(engineMutex_);
388         storageEngine_ =
389             static_cast<SQLiteSingleVerStorageEngine *>(StorageEngineManager::GetStorageEngine(kvDBProp, errCode));
390         if (storageEngine_ == nullptr) {
391             return errCode;
392         }
393     }
394 
395     if (storageEngine_->IsEngineCorrupted()) { // LCOV_EXCL_BR_LINE
396         LOGE("[SqlSinStore][GetAndInitStorageEngine] database engine is corrupted or invalid key, stop open!");
397         return -E_INVALID_PASSWD_OR_CORRUPTED_DB;
398     }
399 
400     errCode = InitDatabaseContext(kvDBProp);
401     if (errCode != E_OK) {
402         LOGE("[SqlSinStore][GetAndInitStorageEngine] Init database context fail! errCode = [%d]", errCode);
403     }
404     return errCode;
405 }
406 
Open(const KvDBProperties & kvDBProp)407 int SQLiteSingleVerNaturalStore::Open(const KvDBProperties &kvDBProp)
408 {
409     std::lock_guard<std::mutex> lock(initialMutex_);
410     if (isInitialized_) { // LCOV_EXCL_BR_LINE
411         return E_OK; // avoid the reopen operation.
412     }
413 
414     int errCode = CheckDatabaseRecovery(kvDBProp);
415     if (errCode != E_OK) {
416         return errCode;
417     }
418 
419     bool isReadOnly = false;
420     SchemaObject savedSchemaObj;
421 
422     errCode = GetAndInitStorageEngine(kvDBProp);
423     if (errCode != E_OK) {
424         goto ERROR;
425     }
426 
427     errCode = RegisterNotification();
428     if (errCode != E_OK) {
429         LOGE("Register notification failed:%d", errCode);
430         goto ERROR;
431     }
432 
433     errCode = RemoveAllSubscribe();
434     if (errCode != E_OK) {
435         LOGE("[SqlSinStore][Open] remove subscribe fail! errCode = [%d]", errCode);
436         goto ERROR;
437     }
438 
439     // Here, the dbfile is created or opened, and upgrade of table structure has done.
440     // More, Upgrade of schema is also done in upgrader call in InitDatabaseContext, schema in dbfile updated if need.
441     // If inputSchema is empty, upgrader do nothing of schema, isReadOnly will be true if dbfile contain schema before.
442     // In this case, we should load the savedSchema for checking value from sync which not restricted by readOnly.
443     // If inputSchema not empty, isReadOnly will not be true, we should do nothing more.
444     errCode = DecideReadOnlyBaseOnSchema(kvDBProp, isReadOnly, savedSchemaObj);
445     if (errCode != E_OK) {
446         LOGE("[SqlSinStore][Open] DecideReadOnlyBaseOnSchema failed=%d", errCode);
447         goto ERROR;
448     }
449     // Set KvDBProperties and set Schema
450     MyProp() = kvDBProp;
451     UpdateSecProperties(MyProp(), isReadOnly, savedSchemaObj, storageEngine_);
452 
453     StartSyncer();
454     OnKill([this]() { ReleaseResources(); });
455 
456     errCode = SaveCreateDBTimeIfNotExisted();
457     if (errCode != E_OK) {
458         goto ERROR;
459     }
460 
461     InitialLocalDataTimestamp();
462     storageEngine_->UpgradeLocalMetaData();
463     isInitialized_ = true;
464     isReadOnly_ = isReadOnly;
465     return E_OK;
466 ERROR:
467     ReleaseResources();
468     return errCode;
469 }
470 
Close()471 void SQLiteSingleVerNaturalStore::Close()
472 {
473     ReleaseResources();
474 }
475 
NewConnection(int & errCode)476 GenericKvDBConnection *SQLiteSingleVerNaturalStore::NewConnection(int &errCode)
477 {
478     SQLiteSingleVerNaturalStoreConnection *connection = new (std::nothrow) SQLiteSingleVerNaturalStoreConnection(this);
479     if (connection == nullptr) {
480         errCode = -E_OUT_OF_MEMORY;
481         return nullptr;
482     }
483     errCode = E_OK;
484     return connection;
485 }
486 
487 // Get interface type of this kvdb.
GetInterfaceType() const488 int SQLiteSingleVerNaturalStore::GetInterfaceType() const
489 {
490     return SYNC_SVD;
491 }
492 
493 // Get the interface ref-count, in order to access asynchronously.
IncRefCount()494 void SQLiteSingleVerNaturalStore::IncRefCount()
495 {
496     IncObjRef(this);
497 }
498 
499 // Drop the interface ref-count.
DecRefCount()500 void SQLiteSingleVerNaturalStore::DecRefCount()
501 {
502     DecObjRef(this);
503 }
504 
505 // Get the identifier of this kvdb.
GetIdentifier() const506 std::vector<uint8_t> SQLiteSingleVerNaturalStore::GetIdentifier() const
507 {
508     std::string identifier = MyProp().GetStringProp(KvDBProperties::IDENTIFIER_DATA, "");
509     std::vector<uint8_t> identifierVect(identifier.begin(), identifier.end());
510     return identifierVect;
511 }
512 
GetDualTupleIdentifier() const513 std::vector<uint8_t> SQLiteSingleVerNaturalStore::GetDualTupleIdentifier() const
514 {
515     std::string identifier = MyProp().GetStringProp(KvDBProperties::DUAL_TUPLE_IDENTIFIER_DATA, "");
516     std::vector<uint8_t> identifierVect(identifier.begin(), identifier.end());
517     return identifierVect;
518 }
519 
520 // Get interface for syncer.
GetSyncInterface()521 IKvDBSyncInterface *SQLiteSingleVerNaturalStore::GetSyncInterface()
522 {
523     return this;
524 }
525 
GetMetaData(const Key & key,Value & value) const526 int SQLiteSingleVerNaturalStore::GetMetaData(const Key &key, Value &value) const
527 {
528     if (storageEngine_ == nullptr) {
529         return -E_INVALID_DB;
530     }
531     if (key.size() > DBConstant::MAX_KEY_SIZE) {
532         return -E_INVALID_ARGS;
533     }
534 
535     int errCode = E_OK;
536     SecurityOption option;
537     errCode = GetSecurityOption(option);
538     if (errCode != E_OK) {
539         LOGW("Get security option failed when get meta data: %d", errCode);
540     }
541     bool isWrite = (option.securityLabel >= S3) && (option.securityFlag == SECE);
542     // meta in S3 SECE open meta.db, should use write handle
543     auto handle = GetHandle(isWrite, errCode);
544     if (handle == nullptr) {
545         return errCode;
546     }
547 
548     Timestamp timestamp;
549     errCode = handle->GetKvData(SingleVerDataType::META_TYPE, key, value, timestamp);
550     ReleaseHandle(handle);
551     HeartBeatForLifeCycle();
552     return errCode;
553 }
554 
GetMetaDataByPrefixKey(const Key & keyPrefix,std::map<Key,Value> & data) const555 int SQLiteSingleVerNaturalStore::GetMetaDataByPrefixKey(const Key &keyPrefix, std::map<Key, Value> &data) const
556 {
557     if (storageEngine_ == nullptr) {
558         return -E_INVALID_DB;
559     }
560     if (keyPrefix.size() > DBConstant::MAX_KEY_SIZE) {
561         return -E_INVALID_ARGS;
562     }
563 
564     int errCode = E_OK;
565     SecurityOption option;
566     errCode = GetSecurityOption(option);
567     if (errCode != E_OK) {
568         LOGW("Get security option failed when get meta data by prefix key: %d", errCode);
569     }
570     bool isWrite = (option.securityLabel >= S3) && (option.securityFlag == SECE);
571     // meta in S3 SECE open meta.db, should use write handle
572     auto handle = GetHandle(isWrite, errCode);
573     if (handle == nullptr) {
574         return errCode;
575     }
576 
577     errCode = handle->GetMetaDataByPrefixKey(keyPrefix, data);
578     ReleaseHandle(handle);
579     HeartBeatForLifeCycle();
580     return errCode;
581 }
582 
PutMetaData(const Key & key,const Value & value,bool isInTransaction)583 int SQLiteSingleVerNaturalStore::PutMetaData(const Key &key, const Value &value, bool isInTransaction)
584 {
585     (void)isInTransaction;
586     int errCode = SQLiteSingleVerNaturalStore::CheckDataStatus(key, value, false);
587     if (errCode != E_OK) {
588         return errCode;
589     }
590 
591     SQLiteSingleVerStorageExecutor *handle = GetHandle(true, errCode);
592     if (handle == nullptr) {
593         return errCode;
594     }
595 
596     errCode = handle->PutKvData(SingleVerDataType::META_TYPE, key, value, 0, nullptr); // meta doesn't need time.
597     if (errCode != E_OK) {
598         LOGE("Put kv data err:%d", errCode);
599     }
600 
601     HeartBeatForLifeCycle();
602     ReleaseHandle(handle);
603     return errCode;
604 }
605 
606 // Delete multiple meta data records in a transaction.
DeleteMetaData(const std::vector<Key> & keys)607 int SQLiteSingleVerNaturalStore::DeleteMetaData(const std::vector<Key> &keys)
608 {
609     for (const auto &key : keys) {
610         if (key.empty() || key.size() > DBConstant::MAX_KEY_SIZE) {
611             return -E_INVALID_ARGS;
612         }
613     }
614     int errCode = E_OK;
615     auto handle = GetHandle(true, errCode);
616     if (handle == nullptr) {
617         return errCode;
618     }
619 
620     handle->StartTransaction(TransactType::IMMEDIATE);
621     errCode = handle->DeleteMetaData(keys);
622     if (errCode != E_OK) {
623         handle->Rollback();
624         LOGE("[SinStore] DeleteMetaData failed, errCode = %d", errCode);
625     } else {
626         handle->Commit();
627     }
628 
629     ReleaseHandle(handle);
630     HeartBeatForLifeCycle();
631     return errCode;
632 }
633 
GetAllMetaKeys(std::vector<Key> & keys) const634 int SQLiteSingleVerNaturalStore::GetAllMetaKeys(std::vector<Key> &keys) const
635 {
636     if (storageEngine_ == nullptr) {
637         return -E_INVALID_DB;
638     }
639     int errCode = E_OK;
640     SQLiteSingleVerStorageExecutor *handle = GetHandle(true, errCode);
641     if (handle == nullptr) {
642         return errCode;
643     }
644 
645     errCode = handle->GetAllMetaKeys(keys);
646     ReleaseHandle(handle);
647     return errCode;
648 }
649 
GetSyncData(Timestamp begin,Timestamp end,std::vector<SingleVerKvEntry * > & entries,ContinueToken & continueStmtToken,const DataSizeSpecInfo & dataSizeInfo) const650 int SQLiteSingleVerNaturalStore::GetSyncData(Timestamp begin, Timestamp end, std::vector<SingleVerKvEntry *> &entries,
651     ContinueToken &continueStmtToken, const DataSizeSpecInfo &dataSizeInfo) const
652 {
653     int errCode = CheckReadDataControlled();
654     if (errCode != E_OK) {
655         LOGE("[GetSyncData] Existed cache database can not read data, errCode = [%d]!", errCode);
656         return errCode;
657     }
658 
659     std::vector<DataItem> dataItems;
660     errCode = GetSyncData(begin, end, dataItems, continueStmtToken, dataSizeInfo);
661     if (errCode != E_OK && errCode != -E_UNFINISHED) {
662         LOGE("GetSyncData errCode:%d", errCode);
663         goto ERROR;
664     }
665 
666     for (auto &item : dataItems) {
667         GenericSingleVerKvEntry *entry = new (std::nothrow) GenericSingleVerKvEntry();
668         if (entry == nullptr) {
669             errCode = -E_OUT_OF_MEMORY;
670             LOGE("GetSyncData errCode:%d", errCode);
671             goto ERROR;
672         }
673         entry->SetEntryData(std::move(item));
674         entries.push_back(entry);
675     }
676 
677 ERROR:
678     if (errCode != E_OK && errCode != -E_UNFINISHED) {
679         SingleVerKvEntry::Release(entries);
680     }
681     HeartBeatForLifeCycle();
682     return errCode;
683 }
684 
GetSyncData(Timestamp begin,Timestamp end,std::vector<DataItem> & dataItems,ContinueToken & continueStmtToken,const DataSizeSpecInfo & dataSizeInfo) const685 int SQLiteSingleVerNaturalStore::GetSyncData(Timestamp begin, Timestamp end, std::vector<DataItem> &dataItems,
686     ContinueToken &continueStmtToken, const DataSizeSpecInfo &dataSizeInfo) const
687 {
688     if (begin >= end || dataSizeInfo.blockSize > DBConstant::MAX_SYNC_BLOCK_SIZE) {
689         return -E_INVALID_ARGS;
690     }
691 
692     auto token = new (std::nothrow) SQLiteSingleVerContinueToken(begin, end);
693     if (token == nullptr) {
694         LOGE("[SQLiteSingleVerNaturalStore][NewToken] Bad alloc.");
695         return -E_OUT_OF_MEMORY;
696     }
697 
698     int errCode = E_OK;
699     SQLiteSingleVerStorageExecutor *handle = GetHandle(false, errCode);
700     if (handle == nullptr) {
701         goto ERROR;
702     }
703 
704     errCode = handle->GetSyncDataByTimestamp(dataItems, GetAppendedLen(), begin, end, dataSizeInfo);
705     if (errCode == -E_FINISHED) {
706         errCode = E_OK;
707     }
708 
709 ERROR:
710     if (errCode != -E_UNFINISHED  && errCode != E_OK) {
711         dataItems.clear();
712     }
713     ProcessContinueToken(dataItems, errCode, token);
714     continueStmtToken = static_cast<ContinueToken>(token);
715 
716     ReleaseHandle(handle);
717     return errCode;
718 }
719 
GetSyncData(QueryObject & query,const SyncTimeRange & timeRange,const DataSizeSpecInfo & dataSizeInfo,ContinueToken & continueStmtToken,std::vector<SingleVerKvEntry * > & entries) const720 int SQLiteSingleVerNaturalStore::GetSyncData(QueryObject &query, const SyncTimeRange &timeRange,
721     const DataSizeSpecInfo &dataSizeInfo, ContinueToken &continueStmtToken,
722     std::vector<SingleVerKvEntry *> &entries) const
723 {
724     if (!timeRange.IsValid()) {
725         return -E_INVALID_ARGS;
726     }
727     int errCode = CheckReadDataControlled();
728     if (errCode != E_OK) {
729         LOGE("[GetEntries] Existed cache prevents the reading from query sync[%d]!", errCode);
730         return errCode;
731     }
732 
733     query.SetSchema(GetSchemaObject());
734     auto token = new (std::nothrow) SQLiteSingleVerContinueToken(timeRange, query);
735     if (token == nullptr) {
736         LOGE("[SingleVerNStore] Allocate continue token failed.");
737         return -E_OUT_OF_MEMORY;
738     }
739 
740     int innerCode;
741     std::vector<DataItem> dataItems;
742     errCode = GetSyncDataForQuerySync(dataItems, token, dataSizeInfo);
743     if (errCode != E_OK && errCode != -E_UNFINISHED) { // The code need be sent to outside except new error happened.
744         goto ERROR;
745     }
746 
747     innerCode = GetKvEntriesByDataItems(entries, dataItems);
748     if (innerCode != E_OK) {
749         errCode = innerCode;
750         delete token;
751         token = nullptr;
752     }
753 
754 ERROR:
755     continueStmtToken = static_cast<ContinueToken>(token);
756     return errCode;
757 }
758 
759 /**
760  * Caller must ensure that parameter continueStmtToken is valid.
761  * If error happened, token will be deleted here.
762  */
GetSyncDataForQuerySync(std::vector<DataItem> & dataItems,SQLiteSingleVerContinueToken * & continueStmtToken,const DataSizeSpecInfo & dataSizeInfo) const763 int SQLiteSingleVerNaturalStore::GetSyncDataForQuerySync(std::vector<DataItem> &dataItems,
764     SQLiteSingleVerContinueToken *&continueStmtToken, const DataSizeSpecInfo &dataSizeInfo) const
765 {
766     int errCode = E_OK;
767     SQLiteSingleVerStorageExecutor *handle = GetHandle(false, errCode);
768     if (handle == nullptr) {
769         goto ERROR;
770     }
771 
772     errCode = handle->StartTransaction(TransactType::DEFERRED);
773     if (errCode != E_OK) {
774         LOGE("[SingleVerNStore] Start transaction for get sync data failed. err=%d", errCode);
775         goto ERROR;
776     }
777 
778     // Get query data.
779     if (!continueStmtToken->IsGetQueryDataFinished()) {
780         LOGD("[SingleVerNStore] Get query data between %" PRIu64 " and %" PRIu64 ".",
781             continueStmtToken->GetQueryBeginTime(), continueStmtToken->GetQueryEndTime());
782         errCode = handle->GetSyncDataWithQuery(continueStmtToken->GetQuery(), GetAppendedLen(), dataSizeInfo,
783             std::make_pair(continueStmtToken->GetQueryBeginTime(), continueStmtToken->GetQueryEndTime()), dataItems);
784     }
785 
786     // Get query data finished.
787     if (errCode == E_OK || errCode == -E_FINISHED) {
788         // Clear query timeRange.
789         continueStmtToken->FinishGetQueryData();
790         if (!continueStmtToken->IsGetDeletedDataFinished()) {
791             errCode = -E_UNFINISHED;
792             // Get delete time next.
793             if (CanHoldDeletedData(dataItems, dataSizeInfo, GetAppendedLen())) {
794                 LOGD("[SingleVerNStore] Get deleted data between %" PRIu64 " and %" PRIu64 ".",
795                     continueStmtToken->GetDeletedBeginTime(), continueStmtToken->GetDeletedEndTime());
796                 errCode = handle->GetDeletedSyncDataByTimestamp(dataItems, GetAppendedLen(),
797                     continueStmtToken->GetDeletedBeginTime(), continueStmtToken->GetDeletedEndTime(), dataSizeInfo);
798             }
799         }
800     }
801 
802     (void)handle->Rollback(); // roll back query statement
803     if (errCode == -E_FINISHED) {
804         errCode = E_OK;
805     }
806 
807 ERROR:
808     if (errCode != -E_UNFINISHED && errCode != E_OK) { // Error happened.
809         dataItems.clear();
810     }
811     ProcessContinueTokenForQuerySync(dataItems, errCode, continueStmtToken);
812     ReleaseHandle(handle);
813     return errCode;
814 }
815 
GetSyncDataNext(std::vector<SingleVerKvEntry * > & entries,ContinueToken & continueStmtToken,const DataSizeSpecInfo & dataSizeInfo) const816 int SQLiteSingleVerNaturalStore::GetSyncDataNext(std::vector<SingleVerKvEntry *> &entries,
817     ContinueToken &continueStmtToken, const DataSizeSpecInfo &dataSizeInfo) const
818 {
819     int errCode = CheckReadDataControlled();
820     if (errCode != E_OK) {
821         LOGE("[GetSyncDataNext] Existed cache database can not read data, errCode = [%d]!", errCode);
822         return errCode;
823     }
824 
825     std::vector<DataItem> dataItems;
826     auto token = static_cast<SQLiteSingleVerContinueToken *>(continueStmtToken);
827     if (token == nullptr) {
828         LOGE("[SingleVerNStore] Allocate continue stmt token failed.");
829         return -E_OUT_OF_MEMORY;
830     }
831     if (token->IsQuerySync()) {
832         errCode = GetSyncDataForQuerySync(dataItems, token, dataSizeInfo);
833         continueStmtToken = static_cast<ContinueToken>(token);
834     } else {
835         errCode = GetSyncDataNext(dataItems, continueStmtToken, dataSizeInfo);
836     }
837 
838     if (errCode != E_OK && errCode != -E_UNFINISHED) {
839         LOGE("GetSyncDataNext errCode:%d", errCode);
840         return errCode;
841     }
842 
843     int innerErrCode = GetKvEntriesByDataItems(entries, dataItems);
844     if (innerErrCode != E_OK) {
845         errCode = innerErrCode;
846         ReleaseContinueToken(continueStmtToken);
847     }
848     return errCode;
849 }
850 
GetSyncDataNext(std::vector<DataItem> & dataItems,ContinueToken & continueStmtToken,const DataSizeSpecInfo & dataSizeInfo) const851 int SQLiteSingleVerNaturalStore::GetSyncDataNext(std::vector<DataItem> &dataItems, ContinueToken &continueStmtToken,
852     const DataSizeSpecInfo &dataSizeInfo) const
853 {
854     if (dataSizeInfo.blockSize > DBConstant::MAX_SYNC_BLOCK_SIZE) {
855         return -E_INVALID_ARGS;
856     }
857 
858     auto token = static_cast<SQLiteSingleVerContinueToken *>(continueStmtToken);
859     if (token == nullptr || !(token->CheckValid())) {
860         LOGE("[SingleVerNaturalStore][GetSyncDataNext] invalid continue token.");
861         return -E_INVALID_ARGS;
862     }
863 
864     int errCode = E_OK;
865     SQLiteSingleVerStorageExecutor *handle = GetHandle(false, errCode);
866     if (handle == nullptr) {
867         ReleaseContinueToken(continueStmtToken);
868         return errCode;
869     }
870 
871     errCode = handle->GetSyncDataByTimestamp(dataItems, GetAppendedLen(), token->GetQueryBeginTime(),
872         token->GetQueryEndTime(), dataSizeInfo);
873     if (errCode == -E_FINISHED) {
874         errCode = E_OK;
875     }
876 
877     ProcessContinueToken(dataItems, errCode, token);
878     continueStmtToken = static_cast<ContinueToken>(token);
879 
880     ReleaseHandle(handle);
881     return errCode;
882 }
883 
GetUnSyncTotal(Timestamp begin,Timestamp end,uint32_t & total) const884 int SQLiteSingleVerNaturalStore::GetUnSyncTotal(Timestamp begin, Timestamp end, uint32_t &total) const
885 {
886     if (begin >= end) {
887         return -E_INVALID_ARGS;
888     }
889 
890     int errCode = E_OK;
891     SQLiteSingleVerStorageExecutor *handle = GetHandle(false, errCode);
892     if (handle == nullptr) {
893         return errCode;
894     }
895 
896     errCode = handle->GetUnSyncTotalByTimestamp(begin, end, total);
897     ReleaseHandle(handle);
898     return errCode;
899 }
900 
GetUnSyncTotal(QueryObject & query,const SyncTimeRange & timeRange,uint32_t & total) const901 int SQLiteSingleVerNaturalStore::GetUnSyncTotal(QueryObject &query, const SyncTimeRange &timeRange,
902     uint32_t &total) const
903 {
904     if (!timeRange.IsValid()) {
905         return -E_INVALID_ARGS;
906     }
907     int errCode = CheckReadDataControlled();
908     if (errCode != E_OK) {
909         LOGE("[GetEntries] Existed cache prevents the reading from query sync total[%d]!", errCode);
910         return errCode;
911     }
912 
913     query.SetSchema(GetSchemaObject());
914     SQLiteSingleVerStorageExecutor *handle = GetHandle(false, errCode);
915     if (handle == nullptr) {
916         return -E_ALREADY_REGISTER;
917     }
918 
919     uint32_t delTotal = 0u;
920     errCode = handle->GetSyncTotalWithQuery(query, std::make_pair(timeRange.beginTime, timeRange.endTime), total);
921     if (errCode != E_OK) {
922         LOGE("[SQLiteSingleVerNaturalStore][GetUnSyncTotal] Get query count failed.");
923         ReleaseHandle(handle);
924         return errCode;
925     }
926 
927     errCode = handle->GetDeletedSyncTotalByTimestamp(timeRange.deleteBeginTime, timeRange.deleteEndTime, delTotal);
928     ReleaseHandle(handle);
929     if (errCode != E_OK) {
930         LOGE("[SQLiteSingleVerNaturalStore][GetUnSyncTotal] Get del count failed.");
931         return errCode;
932     }
933 
934     total += delTotal;
935     return errCode;
936 }
937 
ReleaseContinueToken(ContinueToken & continueStmtToken) const938 void SQLiteSingleVerNaturalStore::ReleaseContinueToken(ContinueToken &continueStmtToken) const
939 {
940     auto token = static_cast<SQLiteSingleVerContinueToken *>(continueStmtToken);
941     if (token == nullptr || !(token->CheckValid())) {
942         LOGE("[SQLiteSingleVerNaturalStore][ReleaseContinueToken] Input is not a continue token.");
943         return;
944     }
945     delete token;
946     continueStmtToken = nullptr;
947 }
948 
PutSyncDataWithQuery(const QueryObject & query,const std::vector<SingleVerKvEntry * > & entries,const std::string & deviceName)949 int SQLiteSingleVerNaturalStore::PutSyncDataWithQuery(const QueryObject &query,
950     const std::vector<SingleVerKvEntry *> &entries, const std::string &deviceName)
951 {
952     if (deviceName.length() > DBConstant::MAX_DEV_LENGTH) {
953         LOGW("Device length is invalid for sync put");
954         return -E_INVALID_ARGS;
955     }
956     HeartBeatForLifeCycle();
957     DeviceInfo deviceInfo = {false, deviceName};
958     if (deviceName.empty()) {
959         deviceInfo.deviceName = "Unknown";
960     }
961 
962     std::vector<DataItem> dataItems;
963     for (const auto itemEntry : entries) {
964         auto *entry = static_cast<GenericSingleVerKvEntry *>(itemEntry);
965         if (entry != nullptr) {
966             DataItem item;
967             item.origDev = entry->GetOrigDevice();
968             item.flag = entry->GetFlag();
969             item.timestamp = entry->GetTimestamp();
970             item.writeTimestamp = entry->GetWriteTimestamp();
971             entry->GetKey(item.key);
972             entry->GetValue(item.value);
973             dataItems.push_back(item);
974         }
975     }
976 
977     int errCode = SaveSyncDataItems(query, dataItems, deviceInfo, true); // Current is true to check value content
978     if (errCode != E_OK) {
979         LOGE("PutSyncData failed:%d", errCode);
980     }
981 
982     return errCode;
983 }
984 
GetMaxTimestamp(Timestamp & stamp) const985 void SQLiteSingleVerNaturalStore::GetMaxTimestamp(Timestamp &stamp) const
986 {
987     if (storageEngine_ == nullptr) {
988         return;
989     }
990     int errCode = E_OK;
991     SQLiteSingleVerStorageExecutor *handle = GetHandle(false, errCode);
992     if (handle == nullptr) {
993         return;
994     }
995     handle->InitCurrentMaxStamp(stamp);
996     LOGD("Get max timestamp from db:%" PRIu64, stamp);
997     ReleaseHandle(handle);
998 }
999 
1000 // In sync procedure, call this function
RemoveDeviceData(const std::string & deviceName,bool isNeedNotify)1001 int SQLiteSingleVerNaturalStore::RemoveDeviceData(const std::string &deviceName, bool isNeedNotify)
1002 {
1003     if (deviceName.empty() || deviceName.length() > DBConstant::MAX_DEV_LENGTH) {
1004         return -E_INVALID_ARGS;
1005     }
1006     LOGI("[RemoveDeviceData] %s{private} rebuild, clear history data", deviceName.c_str());
1007     return RemoveDeviceData(deviceName, isNeedNotify, true);
1008 }
1009 
GetExistsDeviceList(std::set<std::string> & devices) const1010 int SQLiteSingleVerNaturalStore::GetExistsDeviceList(std::set<std::string> &devices) const
1011 {
1012     int errCode = E_OK;
1013     SQLiteSingleVerStorageExecutor *handle = GetHandle(true, errCode);
1014     if (handle == nullptr) {
1015         LOGE("[SingleVerNStore] GetExistsDeviceList get handle failed:%d", errCode);
1016         return errCode;
1017     }
1018     errCode = handle->GetExistsDevicesFromMeta(devices);
1019     if (errCode != E_OK) {
1020         LOGE("[SingleVerNStore] Get remove device list from meta failed. err=%d", errCode);
1021     }
1022     ReleaseHandle(handle);
1023     return errCode;
1024 }
1025 
1026 // In local procedure, call this function
RemoveDeviceData(const std::string & deviceName,bool isNeedNotify,bool isInSync)1027 int SQLiteSingleVerNaturalStore::RemoveDeviceData(const std::string &deviceName, bool isNeedNotify, bool isInSync)
1028 {
1029     if (!isInSync && !CheckWritePermission()) {
1030         return -E_NOT_PERMIT;
1031     }
1032     std::string hashDeviceId;
1033     bool hash = false;
1034     do {
1035         if (!deviceName.empty() && !isInSync) {
1036             int errCode = GetHashDeviceId(deviceName, hashDeviceId);
1037             if (errCode == -E_NOT_SUPPORT) {
1038                 break;
1039             }
1040             if (errCode != E_OK) {
1041                 return errCode;
1042             }
1043             hash = true;
1044         }
1045     } while (false);
1046     if (!hash) { // LCOV_EXCL_BR_LINE
1047         hashDeviceId = DBCommon::TransferHashString(deviceName);
1048     }
1049     auto removeFunc = RemoveDeviceDataInner(hashDeviceId, isNeedNotify);
1050     int errCode = E_OK;
1051     auto syncer = GetAndIncCloudSyncer();
1052     if (syncer == nullptr) {
1053         errCode = removeFunc();
1054     } else {
1055 #ifdef USE_DISTRIBUTEDDB_CLOUD
1056         errCode = syncer->StopSyncTask(removeFunc);
1057         DecObjRef(syncer);
1058 #endif
1059     }
1060     if (errCode != E_OK) {
1061         LOGE("[SingleVerNStore] StopSyncTask with notify failed:%d", errCode);
1062     }
1063     return errCode;
1064 }
1065 
1066 // In sync procedure, call this function
RemoveDeviceData(const std::string & deviceName,ClearMode mode)1067 int SQLiteSingleVerNaturalStore::RemoveDeviceData(const std::string &deviceName, ClearMode mode)
1068 {
1069     auto removeFunc = RemoveDeviceDataInner(DBCommon::TransferHashString(deviceName), mode);
1070     int errCode = E_OK;
1071     auto syncer = GetAndIncCloudSyncer();
1072     if (syncer == nullptr) {
1073         errCode = removeFunc();
1074     } else {
1075 #ifdef USE_DISTRIBUTEDDB_CLOUD
1076         errCode = syncer->StopSyncTask(removeFunc);
1077         DecObjRef(syncer);
1078 #endif
1079     }
1080     if (errCode != E_OK) {
1081         LOGE("[SingleVerNStore] StopSyncTask with mode [%d] failed:%d", mode, errCode);
1082         return errCode;
1083     }
1084 #ifdef USE_DISTRIBUTEDDB_CLOUD
1085     CleanAllWaterMark();
1086 #endif
1087     errCode = EraseAllDeviceWaterMark(DBCommon::TransferHashString(deviceName));
1088     if (errCode != E_OK) {
1089         LOGE("[SingleVerNStore] Erase all device water mark failed %d with mode [%d]", errCode, mode);
1090     }
1091     return errCode;
1092 }
1093 
1094 // In sync procedure, call this function
RemoveDeviceData(const std::string & deviceName,const std::string & user,ClearMode mode)1095 int SQLiteSingleVerNaturalStore::RemoveDeviceData(const std::string &deviceName, const std::string &user,
1096     ClearMode mode)
1097 {
1098     auto removeFunc = RemoveDeviceDataInner(DBCommon::TransferHashString(deviceName), user, mode);
1099     int errCode = E_OK;
1100     auto syncer = GetAndIncCloudSyncer();
1101     if (syncer == nullptr) {
1102         errCode = removeFunc();
1103     } else {
1104 #ifdef USE_DISTRIBUTEDDB_CLOUD
1105         errCode = syncer->StopSyncTask(removeFunc);
1106         DecObjRef(syncer);
1107 #endif
1108     }
1109     if (errCode != E_OK) {
1110         LOGE("[SingleVerNStore] StopSyncTask with user and mode [%d] failed:%d", mode, errCode);
1111         return errCode;
1112     }
1113 #ifdef USE_DISTRIBUTEDDB_CLOUD
1114     CleanAllWaterMark();
1115 #endif
1116     errCode = EraseAllDeviceWaterMark(DBCommon::TransferHashString(deviceName));
1117     if (errCode != E_OK) {
1118         LOGE("[SingleVerNStore] Erase all device water mark failed %d with user and mode [%d]", errCode, mode);
1119     }
1120     return errCode;
1121 }
1122 
RemoveDeviceDataInCacheMode(const std::string & hashDev,bool isNeedNotify) const1123 int SQLiteSingleVerNaturalStore::RemoveDeviceDataInCacheMode(const std::string &hashDev, bool isNeedNotify) const
1124 {
1125     int errCode = E_OK;
1126     SQLiteSingleVerStorageExecutor *handle = GetHandle(true, errCode);
1127     if (handle == nullptr) {
1128         LOGE("[SingleVerNStore] RemoveDeviceData get handle failed:%d", errCode);
1129         return errCode;
1130     }
1131     uint64_t recordVersion = GetAndIncreaseCacheRecordVersion();
1132     LOGI("Remove device data in cache mode isNeedNotify:%d, recordVersion:%" PRIu64, isNeedNotify, recordVersion);
1133     errCode = handle->RemoveDeviceDataInCacheMode(hashDev, isNeedNotify, recordVersion);
1134     if (errCode != E_OK) {
1135         LOGE("[SingleVerNStore] RemoveDeviceDataInCacheMode failed:%d", errCode);
1136     }
1137     ReleaseHandle(handle);
1138     return errCode;
1139 }
1140 
RemoveDeviceDataNormally(const std::string & hashDev,bool isNeedNotify)1141 int SQLiteSingleVerNaturalStore::RemoveDeviceDataNormally(const std::string &hashDev, bool isNeedNotify)
1142 {
1143     int errCode = E_OK;
1144     SQLiteSingleVerStorageExecutor *handle = GetHandle(true, errCode);
1145     if (handle == nullptr) {
1146         LOGE("[SingleVerNStore] RemoveDeviceData get handle failed:%d", errCode);
1147         return errCode;
1148     }
1149 
1150     std::vector<Entry> entries;
1151     if (isNeedNotify) {
1152         handle->GetAllSyncedEntries(hashDev, entries);
1153     }
1154 
1155     LOGI("Remove device data:%d", isNeedNotify);
1156     errCode = handle->RemoveDeviceData(hashDev);
1157     ReleaseHandle(handle);
1158     if (errCode == E_OK && isNeedNotify) {
1159         NotifyRemovedData(entries);
1160     }
1161     return errCode;
1162 }
1163 
NotifyRemovedData(std::vector<Entry> & entries)1164 void SQLiteSingleVerNaturalStore::NotifyRemovedData(std::vector<Entry> &entries)
1165 {
1166     if (entries.empty() || entries.size() > MAX_TOTAL_NOTIFY_ITEM_SIZE) {
1167         return;
1168     }
1169 
1170     size_t index = 0;
1171     size_t totalSize = 0;
1172     SingleVerNaturalStoreCommitNotifyData *notifyData = nullptr;
1173     while (index < entries.size()) {
1174         if (notifyData == nullptr) {
1175             notifyData = new (std::nothrow) SingleVerNaturalStoreCommitNotifyData;
1176             if (notifyData == nullptr) {
1177                 LOGE("Failed to do commit sync removing because of OOM");
1178                 break;
1179             }
1180         }
1181 
1182         // ignore the invalid key.
1183         if (entries[index].key.size() > DBConstant::MAX_KEY_SIZE ||
1184             entries[index].value.size() > GetMaxValueSize()) {
1185             index++;
1186             continue;
1187         }
1188 
1189         if ((entries[index].key.size() + entries[index].value.size() + totalSize) > MAX_TOTAL_NOTIFY_DATA_SIZE) {
1190             CommitAndReleaseNotifyData(notifyData, true,
1191                 static_cast<int>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_SYNC_EVENT));
1192             totalSize = 0;
1193             notifyData = nullptr;
1194             continue;
1195         }
1196 
1197         totalSize += (entries[index].key.size() + entries[index].value.size());
1198         notifyData->InsertCommittedData(std::move(entries[index]), DataType::DELETE, false);
1199         index++;
1200     }
1201     if (notifyData != nullptr) {
1202         CommitAndReleaseNotifyData(notifyData, true,
1203             static_cast<int>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_SYNC_EVENT));
1204     }
1205 }
1206 
GetHandle(bool isWrite,int & errCode,OperatePerm perm) const1207 SQLiteSingleVerStorageExecutor *SQLiteSingleVerNaturalStore::GetHandle(bool isWrite, int &errCode,
1208     OperatePerm perm) const
1209 {
1210     engineMutex_.lock_shared();
1211     if (storageEngine_ == nullptr) {
1212         errCode = -E_INVALID_DB;
1213         engineMutex_.unlock_shared(); // unlock when get handle failed.
1214         return nullptr;
1215     }
1216     // Use for check database corrupted in Asynchronous task, like cache data migrate to main database
1217     if (storageEngine_->IsEngineCorrupted()) { // LCOV_EXCL_BR_LINE
1218         CorruptNotify();
1219         errCode = -E_INVALID_PASSWD_OR_CORRUPTED_DB;
1220         engineMutex_.unlock_shared(); // unlock when get handle failed.
1221         LOGI("Handle is corrupted or invalid key, can not to get! errCode = [%d]", errCode);
1222         return nullptr;
1223     }
1224 
1225     auto handle = storageEngine_->FindExecutor(isWrite, perm, errCode);
1226     if (handle == nullptr) {
1227         engineMutex_.unlock_shared(); // unlock when get handle failed.
1228     }
1229     return static_cast<SQLiteSingleVerStorageExecutor *>(handle);
1230 }
1231 
ReleaseHandle(SQLiteSingleVerStorageExecutor * & handle) const1232 void SQLiteSingleVerNaturalStore::ReleaseHandle(SQLiteSingleVerStorageExecutor *&handle) const
1233 {
1234     if (handle == nullptr) {
1235         return;
1236     }
1237 
1238     if (storageEngine_ != nullptr) {
1239         bool isCorrupted = handle->GetCorruptedStatus();
1240         StorageExecutor *databaseHandle = handle;
1241         storageEngine_->Recycle(databaseHandle);
1242         handle = nullptr;
1243         if (isCorrupted) {
1244             CorruptNotify();
1245         }
1246     }
1247     engineMutex_.unlock_shared(); // unlock after handle used up
1248 }
1249 
RegisterNotification()1250 int SQLiteSingleVerNaturalStore::RegisterNotification()
1251 {
1252     static const std::vector<int> events {
1253         static_cast<int>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_LOCAL_PUT_EVENT),
1254         static_cast<int>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_PUT_EVENT),
1255         static_cast<int>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_SYNC_EVENT),
1256         static_cast<int>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_CONFLICT_EVENT),
1257     };
1258 
1259     for (auto event = events.begin(); event != events.end(); ++event) {
1260         int errCode = RegisterNotificationEventType(*event);
1261         if (errCode == E_OK) {
1262             continue;
1263         }
1264         LOGE("Register single version event %d failed:%d!", *event, errCode);
1265         for (auto iter = events.begin(); iter != event; ++iter) {
1266             UnRegisterNotificationEventType(*iter);
1267         }
1268         return errCode;
1269     }
1270 
1271     notificationEventsRegistered_ = true;
1272     notificationConflictEventsRegistered_ = true;
1273     return E_OK;
1274 }
1275 
ReleaseResources()1276 void SQLiteSingleVerNaturalStore::ReleaseResources()
1277 {
1278     SyncAbleKvDB::Close();
1279     if (notificationEventsRegistered_) {
1280         UnRegisterNotificationEventType(
1281             static_cast<EventType>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_SYNC_EVENT));
1282         UnRegisterNotificationEventType(
1283             static_cast<EventType>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_PUT_EVENT));
1284         UnRegisterNotificationEventType(
1285             static_cast<EventType>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_LOCAL_PUT_EVENT));
1286         notificationEventsRegistered_ = false;
1287     }
1288 
1289     if (notificationConflictEventsRegistered_) {
1290         UnRegisterNotificationEventType(static_cast<EventType>(
1291             SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_CONFLICT_EVENT));
1292         notificationConflictEventsRegistered_ = false;
1293     }
1294 
1295     {
1296         std::lock_guard<std::mutex> autoLock(cloudStoreMutex_);
1297         RefObject::KillAndDecObjRef(sqliteCloudKvStore_);
1298         sqliteCloudKvStore_ = nullptr;
1299     }
1300     {
1301         std::unique_lock<std::shared_mutex> lock(engineMutex_);
1302         if (storageEngine_ != nullptr) {
1303             storageEngine_->ClearEnginePasswd();
1304             (void)StorageEngineManager::ReleaseStorageEngine(storageEngine_);
1305             storageEngine_ = nullptr;
1306         }
1307     }
1308 
1309     isInitialized_ = false;
1310 }
1311 
InitConflictNotifiedFlag(SingleVerNaturalStoreCommitNotifyData * committedData)1312 void SQLiteSingleVerNaturalStore::InitConflictNotifiedFlag(SingleVerNaturalStoreCommitNotifyData *committedData)
1313 {
1314     unsigned int conflictFlag = 0;
1315     if (GetRegisterFunctionCount(RegisterFuncType::CONFLICT_SINGLE_VERSION_NS_FOREIGN_KEY_ONLY) != 0) {
1316         conflictFlag |= static_cast<unsigned>(SQLiteGeneralNSConflictType::SQLITE_GENERAL_NS_FOREIGN_KEY_ONLY);
1317     }
1318     if (GetRegisterFunctionCount(RegisterFuncType::CONFLICT_SINGLE_VERSION_NS_FOREIGN_KEY_ORIG) != 0) {
1319         conflictFlag |= static_cast<unsigned>(SQLiteGeneralNSConflictType::SQLITE_GENERAL_NS_FOREIGN_KEY_ORIG);
1320     }
1321     if (GetRegisterFunctionCount(RegisterFuncType::CONFLICT_SINGLE_VERSION_NS_NATIVE_ALL) != 0) {
1322         conflictFlag |= static_cast<unsigned>(SQLiteGeneralNSConflictType::SQLITE_GENERAL_NS_NATIVE_ALL);
1323     }
1324     committedData->SetConflictedNotifiedFlag(static_cast<int>(conflictFlag));
1325 }
1326 
1327 // Currently this function only suitable to be call from sync in insert_record_from_sync procedure
1328 // Take attention if future coder attempt to call it in other situation procedure
SaveSyncDataItems(const QueryObject & query,std::vector<DataItem> & dataItems,const DeviceInfo & deviceInfo,bool checkValueContent)1329 int SQLiteSingleVerNaturalStore::SaveSyncDataItems(const QueryObject &query, std::vector<DataItem> &dataItems,
1330     const DeviceInfo &deviceInfo, bool checkValueContent)
1331 {
1332     // Sync procedure does not care readOnly Flag
1333     if (storageEngine_ == nullptr) {
1334         return -E_INVALID_DB;
1335     }
1336     int errCode = E_OK;
1337     auto offset = GetLocalTimeOffset();
1338     std::vector<DataItem> dataItemsRet;
1339     for (auto &item : dataItems) {
1340         // Check only the key and value size
1341         errCode = CheckDataStatus(item.key, item.value, (item.flag & DataItem::DELETE_FLAG) != 0);
1342         if (errCode != E_OK) {
1343             if (item.key.empty() || item.key.size() > DBConstant::MAX_KEY_SIZE) {
1344                 return errCode;
1345             } else {
1346                 LOGI("save sync data failed because of check data status fail errCode %d!", errCode);
1347             }
1348         }
1349         if (offset != 0) {
1350             item.modifyTime = static_cast<Timestamp>(static_cast<int64_t>(item.timestamp) - offset);
1351             item.createTime = static_cast<Timestamp>(static_cast<int64_t>(item.writeTimestamp) - offset);
1352         }
1353         dataItemsRet.push_back(item);
1354     }
1355     dataItems = dataItemsRet;
1356     if (checkValueContent) { // LCOV_EXCL_BR_LINE
1357         CheckAmendValueContentForSyncProcedure(dataItems);
1358     }
1359     QueryObject queryInner = query;
1360     queryInner.SetSchema(GetSchemaObjectConstRef());
1361     if (IsExtendedCacheDBMode()) {
1362         errCode = SaveSyncDataToCacheDB(queryInner, dataItems, deviceInfo);
1363     } else {
1364         errCode = SaveSyncDataToMain(queryInner, dataItems, deviceInfo);
1365     }
1366     if (errCode != E_OK) {
1367         LOGE("[SingleVerNStore] SaveSyncDataItems failed:%d", errCode);
1368     }
1369     return errCode;
1370 }
1371 
SaveSyncDataToMain(const QueryObject & query,std::vector<DataItem> & dataItems,const DeviceInfo & deviceInfo)1372 int SQLiteSingleVerNaturalStore::SaveSyncDataToMain(const QueryObject &query, std::vector<DataItem> &dataItems,
1373     const DeviceInfo &deviceInfo)
1374 {
1375     auto *committedData = new (std::nothrow) SingleVerNaturalStoreCommitNotifyData;
1376     if (committedData == nullptr) {
1377         LOGE("[SingleVerNStore] Failed to alloc single version notify data");
1378         return -E_OUT_OF_MEMORY;
1379     }
1380     InitConflictNotifiedFlag(committedData);
1381     Timestamp maxTimestamp = 0;
1382     bool isNeedCommit = false;
1383     int errCode = SaveSyncItems(query, dataItems, deviceInfo, maxTimestamp, committedData);
1384     if (errCode == E_OK) {
1385         isNeedCommit = true;
1386     }
1387 
1388     CommitAndReleaseNotifyData(committedData, isNeedCommit,
1389         static_cast<int>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_SYNC_EVENT));
1390     return errCode;
1391 }
1392 
1393 // Currently, this function only suitable to be call from sync in insert_record_from_sync procedure
1394 // Take attention if future coder attempt to call it in other situation procedure
SaveSyncItems(const QueryObject & query,std::vector<DataItem> & dataItems,const DeviceInfo & deviceInfo,Timestamp & maxTimestamp,SingleVerNaturalStoreCommitNotifyData * commitData) const1395 int SQLiteSingleVerNaturalStore::SaveSyncItems(const QueryObject &query, std::vector<DataItem> &dataItems,
1396     const DeviceInfo &deviceInfo, Timestamp &maxTimestamp, SingleVerNaturalStoreCommitNotifyData *commitData) const
1397 {
1398     int errCode = E_OK;
1399     int innerCode = E_OK;
1400     LOGD("[SQLiteSingleVerNaturalStore::SaveSyncData] Get write handle.");
1401     SQLiteSingleVerStorageExecutor *handle = GetHandle(true, errCode);
1402     if (handle == nullptr) {
1403         return errCode;
1404     }
1405     DBDfxAdapter::StartTracing();
1406     errCode = handle->StartTransaction(TransactType::IMMEDIATE);
1407     if (errCode != E_OK) {
1408         ReleaseHandle(handle);
1409         DBDfxAdapter::FinishTracing();
1410         return errCode;
1411     }
1412     errCode = handle->CheckDataWithQuery(query, dataItems, deviceInfo);
1413     if (errCode != E_OK) {
1414         goto END;
1415     }
1416     errCode = handle->PrepareForSavingData(SingleVerDataType::SYNC_TYPE);
1417     if (errCode != E_OK) {
1418         goto END;
1419     }
1420     for (auto &item: dataItems) {
1421         if (item.neglect) { // Do not save this record if it is neglected
1422             continue;
1423         }
1424         errCode = handle->SaveSyncDataItem(item, deviceInfo, maxTimestamp, commitData, true);
1425         if (errCode != E_OK && errCode != -E_NOT_FOUND) {
1426             break;
1427         }
1428     }
1429     if (errCode == -E_NOT_FOUND) {
1430         errCode = E_OK;
1431     }
1432     innerCode = handle->ResetForSavingData(SingleVerDataType::SYNC_TYPE);
1433     if (innerCode != E_OK) {
1434         errCode = innerCode;
1435     }
1436 END:
1437     if (errCode == E_OK) {
1438         errCode = handle->Commit();
1439     } else {
1440         (void)handle->Rollback(); // Keep the error code of the first scene
1441     }
1442     DBDfxAdapter::FinishTracing();
1443     ReleaseHandle(handle);
1444     return errCode;
1445 }
1446 
SaveSyncDataToCacheDB(const QueryObject & query,std::vector<DataItem> & dataItems,const DeviceInfo & deviceInfo)1447 int SQLiteSingleVerNaturalStore::SaveSyncDataToCacheDB(const QueryObject &query, std::vector<DataItem> &dataItems,
1448     const DeviceInfo &deviceInfo)
1449 {
1450     int errCode = E_OK;
1451     SQLiteSingleVerStorageExecutor *handle = GetHandle(true, errCode);
1452     if (handle == nullptr) {
1453         return errCode;
1454     }
1455 
1456     Timestamp maxTimestamp = 0;
1457     DBDfxAdapter::StartTracing();
1458     errCode = SaveSyncItemsInCacheMode(handle, query, dataItems, deviceInfo, maxTimestamp);
1459     if (errCode != E_OK) {
1460         LOGE("[SingleVerNStore] Failed to save sync data in cache mode, err : %d", errCode);
1461     }
1462     DBDfxAdapter::FinishTracing();
1463     ReleaseHandle(handle);
1464     return errCode;
1465 }
1466 
GetTimestampFromDB()1467 uint64_t SQLiteSingleVerNaturalStore::GetTimestampFromDB()
1468 {
1469     std::vector<uint8_t> key;
1470     std::vector<uint8_t> timeOffset;
1471     int64_t localTimeOffset = TimeHelper::BASE_OFFSET;
1472     DBCommon::StringToVector(std::string(DBConstant::LOCALTIME_OFFSET_KEY), key);
1473     int errCode = GetMetaData(key, timeOffset);
1474     if (errCode == E_OK) {
1475         std::string timeOffsetString(timeOffset.begin(), timeOffset.end());
1476         int64_t result = std::strtoll(timeOffsetString.c_str(), nullptr, DBConstant::STR_TO_LL_BY_DEVALUE);
1477         if (errno != ERANGE && result != LLONG_MIN && result != LLONG_MAX) {
1478             localTimeOffset = result;
1479         }
1480     } else {
1481         LOGW("[GetTimestampFromDB] when sync not start get metadata from db failed, err=%d", errCode);
1482     }
1483     uint64_t currentSysTime = TimeHelper::GetSysCurrentTime();
1484     if (localTimeOffset < 0 && currentSysTime >= static_cast<uint64_t>(std::abs(localTimeOffset))) {
1485         currentSysTime -= static_cast<uint64_t>(std::abs(localTimeOffset));
1486     } else if (localTimeOffset >= 0 && (UINT64_MAX - currentSysTime >= static_cast<uint64_t>(localTimeOffset))) {
1487         currentSysTime += static_cast<uint64_t>(localTimeOffset);
1488     } else {
1489         LOGW("[GetTimestampFromDB] localTimeOffset plus currentSysTime overflow");
1490     }
1491     if (currentSysTime <= lastLocalSysTime_) {
1492         currentSysTime = lastLocalSysTime_ + 1;
1493     }
1494     lastLocalSysTime_ = currentSysTime;
1495     return currentSysTime;
1496 }
1497 
GetCurrentTimestamp(bool needStartSync)1498 Timestamp SQLiteSingleVerNaturalStore::GetCurrentTimestamp(bool needStartSync)
1499 {
1500     return GetTimestamp(needStartSync);
1501 }
1502 
InitStorageEngine(const KvDBProperties & kvDBProp,bool isNeedUpdateSecOpt)1503 int SQLiteSingleVerNaturalStore::InitStorageEngine(const KvDBProperties &kvDBProp, bool isNeedUpdateSecOpt)
1504 {
1505     OpenDbProperties option;
1506     InitDataBaseOption(kvDBProp, option);
1507 
1508     bool isMemoryMode = kvDBProp.GetBoolProp(KvDBProperties::MEMORY_MODE, false);
1509     StorageEngineAttr poolSize = {1, 1, 1, 16}; // at most 1 write 16 read.
1510     if (isMemoryMode) {
1511         poolSize.minWriteNum = 1; // keep at least one connection.
1512     }
1513 
1514     storageEngine_->SetNotifiedCallback(
1515         [&](int eventType, KvDBCommitNotifyFilterAbleData *committedData) {
1516             if (eventType == static_cast<int>(
1517                 SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_FINISH_MIGRATE_EVENT)) {
1518                 return this->TriggerSync(eventType);
1519             }
1520             auto commitData = static_cast<SingleVerNaturalStoreCommitNotifyData *>(committedData);
1521             this->CommitAndReleaseNotifyData(commitData, true, eventType);
1522         }
1523     );
1524     storageEngine_->SetSchemaChangedCallback(
1525         [&]() {
1526             return this->UpgradeSchemaVerInMeta();
1527         }
1528     );
1529 
1530     std::string identifier = kvDBProp.GetStringProp(KvDBProperties::IDENTIFIER_DATA, "");
1531     storageEngine_->SetNeedUpdateSecOption(isNeedUpdateSecOpt);
1532     int errCode = storageEngine_->InitSQLiteStorageEngine(poolSize, option, identifier);
1533     if (errCode != E_OK) {
1534         LOGE("Init the sqlite storage engine failed:%d", errCode);
1535         return errCode;
1536     }
1537 
1538     std::lock_guard<std::mutex> autoLock(cloudStoreMutex_);
1539     if (sqliteCloudKvStore_ != nullptr) {
1540         return E_OK;
1541     }
1542     sqliteCloudKvStore_ = new(std::nothrow) SqliteCloudKvStore(this);
1543     if (sqliteCloudKvStore_ == nullptr) {
1544         return E_OUT_OF_MEMORY;
1545     }
1546     return E_OK;
1547 }
1548 
Rekey(const CipherPassword & passwd)1549 int SQLiteSingleVerNaturalStore::Rekey(const CipherPassword &passwd)
1550 {
1551     // Check the storage engine and try to disable the engine.
1552     if (storageEngine_ == nullptr) {
1553         return -E_INVALID_DB;
1554     }
1555 
1556     std::unique_ptr<SingleVerDatabaseOper> operation;
1557 
1558     // stop the syncer
1559     int errCode = storageEngine_->TryToDisable(false, OperatePerm::REKEY_MONOPOLIZE_PERM);
1560     if (errCode != E_OK) {
1561         return errCode;
1562     }
1563 
1564     LOGI("Stop the syncer for rekey");
1565     StopSyncer(true);
1566     std::this_thread::sleep_for(std::chrono::milliseconds(5));  // wait for 5 ms
1567     errCode = storageEngine_->TryToDisable(true, OperatePerm::REKEY_MONOPOLIZE_PERM);
1568     if (errCode != E_OK) {
1569         LOGE("[Rekey] Failed to disable the database: %d", errCode);
1570         goto END;
1571     }
1572 
1573     if (storageEngine_->GetEngineState() != EngineState::MAINDB) {
1574         LOGE("Rekey is not supported while cache exists! state = [%d]", storageEngine_->GetEngineState());
1575         errCode = (storageEngine_->GetEngineState() == EngineState::CACHEDB) ? -E_NOT_SUPPORT : -E_BUSY;
1576         goto END;
1577     }
1578 
1579     operation = std::make_unique<SingleVerDatabaseOper>(this, storageEngine_);
1580     LOGI("Operation rekey");
1581     errCode = operation->Rekey(passwd);
1582 END:
1583     // Only maindb state have existed handle, if rekey fail other state will create error cache db
1584     // Abort can forbid get new handle, requesting handle will return BUSY and nullptr handle
1585     AbortHandle();
1586     if (errCode != -E_FORBID_CACHEDB) {
1587         storageEngine_->Enable(OperatePerm::REKEY_MONOPOLIZE_PERM);
1588     } else {
1589         storageEngine_->Abort(OperatePerm::REKEY_MONOPOLIZE_PERM);
1590         errCode = E_OK;
1591     }
1592     storageEngine_->WaitWriteHandleIdle();
1593     StartSyncer();
1594     EnableHandle();
1595     return errCode;
1596 }
1597 
Export(const std::string & filePath,const CipherPassword & passwd)1598 int SQLiteSingleVerNaturalStore::Export(const std::string &filePath, const CipherPassword &passwd)
1599 {
1600     if (storageEngine_ == nullptr) {
1601         return -E_INVALID_DB;
1602     }
1603     if (MyProp().GetBoolProp(KvDBProperties::MEMORY_MODE, false)) { // LCOV_EXCL_BR_LINE
1604         return -E_NOT_SUPPORT;
1605     }
1606 
1607     // Exclusively write resources
1608     std::string localDev;
1609     GetAndResizeLocalIdentity(localDev);
1610 
1611     // The write handle is applied to prevent writing data during the export process.
1612     int errCode =  E_OK;
1613     SQLiteSingleVerStorageExecutor *handle = GetHandle(true, errCode, OperatePerm::NORMAL_PERM);
1614     if (handle == nullptr) {
1615         return errCode;
1616     }
1617 
1618     // forbid migrate by hold write handle not release
1619     if (storageEngine_->GetEngineState() != EngineState::MAINDB) {
1620         LOGE("Not support export when cacheDB existed! state = [%d]", storageEngine_->GetEngineState());
1621         errCode = (storageEngine_->GetEngineState() == EngineState::CACHEDB) ? -E_NOT_SUPPORT : -E_BUSY;
1622         ReleaseHandle(handle);
1623         return errCode;
1624     }
1625 
1626     std::unique_ptr<SingleVerDatabaseOper> operation = std::make_unique<SingleVerDatabaseOper>(this, storageEngine_);
1627     operation->SetLocalDevId(localDev);
1628     errCode = TryToDisableConnection(OperatePerm::NORMAL_WRITE);
1629     if (errCode != E_OK) {
1630         LOGE("disable connection failed! errCode %d", errCode);
1631         ReleaseHandle(handle);
1632         return errCode;
1633     }
1634     LOGD("Begin export the kv store");
1635     errCode = operation->Export(filePath, passwd);
1636 
1637     ReEnableConnection(OperatePerm::NORMAL_WRITE);
1638     ReleaseHandle(handle);
1639     return errCode;
1640 }
1641 
Import(const std::string & filePath,const CipherPassword & passwd,bool isNeedIntegrityCheck)1642 int SQLiteSingleVerNaturalStore::Import(const std::string &filePath, const CipherPassword &passwd,
1643     bool isNeedIntegrityCheck)
1644 {
1645     if (storageEngine_ == nullptr) {
1646         return -E_INVALID_DB;
1647     }
1648     if (MyProp().GetBoolProp(KvDBProperties::MEMORY_MODE, false)) { // LCOV_EXCL_BR_LINE
1649         return -E_NOT_SUPPORT;
1650     }
1651 
1652     std::string localDev;
1653     int errCode = GetLocalIdentity(localDev);
1654     if (errCode == -E_NOT_INIT) {
1655         localDev.resize(DEVICE_ID_LEN);
1656     } else if (errCode != E_OK) {
1657         LOGE("Failed to GetLocalIdentity!");
1658         localDev.resize(0);
1659     }
1660 
1661     // stop the syncer
1662     errCode = storageEngine_->TryToDisable(false, OperatePerm::IMPORT_MONOPOLIZE_PERM);
1663     if (errCode != E_OK) {
1664         return errCode;
1665     }
1666     StopSyncer(true, true);
1667     std::this_thread::sleep_for(std::chrono::milliseconds(5)); // wait for 5 ms
1668     std::unique_ptr<SingleVerDatabaseOper> operation;
1669 
1670     errCode = storageEngine_->TryToDisable(true, OperatePerm::IMPORT_MONOPOLIZE_PERM);
1671     if (errCode != E_OK) {
1672         LOGE("[Import] Failed to disable the database: %d", errCode);
1673         goto END;
1674     }
1675 
1676     if (storageEngine_->GetEngineState() != EngineState::MAINDB) {
1677         LOGE("Not support import when cacheDB existed! state = [%d]", storageEngine_->GetEngineState());
1678         errCode = (storageEngine_->GetEngineState() == EngineState::CACHEDB) ? -E_NOT_SUPPORT : -E_BUSY;
1679         goto END;
1680     }
1681 
1682     operation = std::make_unique<SingleVerDatabaseOper>(this, storageEngine_);
1683     operation->SetLocalDevId(localDev);
1684     errCode = operation->Import(filePath, passwd, isNeedIntegrityCheck);
1685     if (errCode != E_OK) {
1686         goto END;
1687     }
1688 
1689     // Save create db time.
1690     storageEngine_->Enable(OperatePerm::IMPORT_MONOPOLIZE_PERM);
1691 
1692     errCode = SaveCreateDBTime(); // This step will start syncer
1693 
1694 END:
1695     // restore the storage engine and the syncer.
1696     AbortHandle();
1697     storageEngine_->Enable(OperatePerm::IMPORT_MONOPOLIZE_PERM);
1698     storageEngine_->WaitWriteHandleIdle();
1699     StartSyncer();
1700     EnableHandle();
1701     return errCode;
1702 }
1703 
CheckWritePermission() const1704 bool SQLiteSingleVerNaturalStore::CheckWritePermission() const
1705 {
1706     return !isReadOnly_;
1707 }
1708 
GetSchemaInfo() const1709 SchemaObject SQLiteSingleVerNaturalStore::GetSchemaInfo() const
1710 {
1711     return MyProp().GetSchemaConstRef();
1712 }
1713 
GetSchemaObject() const1714 SchemaObject SQLiteSingleVerNaturalStore::GetSchemaObject() const
1715 {
1716     return MyProp().GetSchema();
1717 }
1718 
GetSchemaObjectConstRef() const1719 const SchemaObject &SQLiteSingleVerNaturalStore::GetSchemaObjectConstRef() const
1720 {
1721     return MyProp().GetSchemaConstRef();
1722 }
1723 
CheckCompatible(const std::string & schema,uint8_t type) const1724 bool SQLiteSingleVerNaturalStore::CheckCompatible(const std::string &schema, uint8_t type) const
1725 {
1726     const SchemaObject &localSchema = MyProp().GetSchemaConstRef();
1727     if (!localSchema.IsSchemaValid() || schema.empty() || ReadSchemaType(type) == SchemaType::NONE) {
1728         // If at least one of local or remote is normal-kvdb, then allow sync
1729         LOGI("IsLocalSchemaDb=%d, IsRemoteSchemaDb=%d.", localSchema.IsSchemaValid(), !schema.empty());
1730         return true;
1731     }
1732     // Here both are schema-db, check their compatibility mutually
1733     SchemaObject remoteSchema;
1734     int errCode = remoteSchema.ParseFromSchemaString(schema);
1735     if (errCode != E_OK) { // LCOV_EXCL_BR_LINE
1736         // Consider: if the parse errCode is SchemaVersionNotSupport, we can consider allow sync if schemaType equal.
1737         LOGE("Parse remote schema fail, errCode=%d.", errCode);
1738         return false;
1739     }
1740     // First, Compare remoteSchema based on localSchema
1741     errCode = localSchema.CompareAgainstSchemaObject(remoteSchema);
1742     if (errCode != -E_SCHEMA_UNEQUAL_INCOMPATIBLE) { // LCOV_EXCL_BR_LINE
1743         LOGI("Remote(Maybe newer) compatible based on local, result=%d.", errCode);
1744         return true;
1745     }
1746     // Second, Compare localSchema based on remoteSchema
1747     errCode = remoteSchema.CompareAgainstSchemaObject(localSchema);
1748     if (errCode != -E_SCHEMA_UNEQUAL_INCOMPATIBLE) { // LCOV_EXCL_BR_LINE
1749         LOGI("Local(Newer) compatible based on remote, result=%d.", errCode);
1750         return true;
1751     }
1752     LOGE("Local incompatible with remote mutually.");
1753     return false;
1754 }
1755 
InitDataBaseOption(const KvDBProperties & kvDBProp,OpenDbProperties & option)1756 void SQLiteSingleVerNaturalStore::InitDataBaseOption(const KvDBProperties &kvDBProp, OpenDbProperties &option)
1757 {
1758     std::string uri = GetDatabasePath(kvDBProp);
1759     bool isMemoryDb = kvDBProp.GetBoolProp(KvDBProperties::MEMORY_MODE, false);
1760     if (isMemoryDb) {
1761         std::string identifierDir = kvDBProp.GetStringProp(KvDBProperties::IDENTIFIER_DIR, "");
1762         uri = identifierDir + DBConstant::SQLITE_MEMDB_IDENTIFY;
1763         LOGD("Begin create memory natural store database");
1764     }
1765     std::string subDir = GetSubDirPath(kvDBProp);
1766     CipherType cipherType;
1767     CipherPassword passwd;
1768     kvDBProp.GetPassword(cipherType, passwd);
1769     std::string schemaStr = kvDBProp.GetSchema().ToSchemaString();
1770 
1771     bool isCreateNecessary = kvDBProp.GetBoolProp(KvDBProperties::CREATE_IF_NECESSARY, true);
1772     std::vector<std::string> createTableSqls;
1773 
1774     SecurityOption securityOpt;
1775     if (RuntimeContext::GetInstance()->IsProcessSystemApiAdapterValid()) {
1776         securityOpt.securityLabel = kvDBProp.GetSecLabel();
1777         securityOpt.securityFlag = kvDBProp.GetSecFlag();
1778     }
1779 
1780     option = {uri, isCreateNecessary, isMemoryDb, createTableSqls, cipherType, passwd, schemaStr, subDir, securityOpt};
1781     option.conflictReslovePolicy = kvDBProp.GetIntProp(KvDBProperties::CONFLICT_RESOLVE_POLICY, DEFAULT_LAST_WIN);
1782     option.createDirByStoreIdOnly = kvDBProp.GetBoolProp(KvDBProperties::CREATE_DIR_BY_STORE_ID_ONLY, false);
1783 }
1784 
TransObserverTypeToRegisterFunctionType(int observerType,RegisterFuncType & type) const1785 int SQLiteSingleVerNaturalStore::TransObserverTypeToRegisterFunctionType(
1786     int observerType, RegisterFuncType &type) const
1787 {
1788     static constexpr TransPair transMap[] = {
1789         { static_cast<int>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_PUT_EVENT),
1790             RegisterFuncType::OBSERVER_SINGLE_VERSION_NS_PUT_EVENT },
1791         { static_cast<int>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_SYNC_EVENT),
1792             RegisterFuncType::OBSERVER_SINGLE_VERSION_NS_SYNC_EVENT },
1793         { static_cast<int>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_NS_LOCAL_PUT_EVENT),
1794             RegisterFuncType::OBSERVER_SINGLE_VERSION_NS_LOCAL_EVENT },
1795         { static_cast<int>(SQLiteGeneralNSNotificationEventType::SQLITE_GENERAL_CONFLICT_EVENT),
1796             RegisterFuncType::OBSERVER_SINGLE_VERSION_NS_CONFLICT_EVENT },
1797     };
1798     auto funcType = GetFuncType(observerType, transMap, sizeof(transMap) / sizeof(TransPair));
1799     if (funcType == RegisterFuncType::REGISTER_FUNC_TYPE_MAX) {
1800         return -E_NOT_SUPPORT;
1801     }
1802     type = funcType;
1803     return E_OK;
1804 }
1805 
TransConflictTypeToRegisterFunctionType(int conflictType,RegisterFuncType & type) const1806 int SQLiteSingleVerNaturalStore::TransConflictTypeToRegisterFunctionType(
1807     int conflictType, RegisterFuncType &type) const
1808 {
1809     static constexpr TransPair transMap[] = {
1810         { static_cast<int>(SQLiteGeneralNSConflictType::SQLITE_GENERAL_NS_FOREIGN_KEY_ONLY),
1811             RegisterFuncType::CONFLICT_SINGLE_VERSION_NS_FOREIGN_KEY_ONLY },
1812         { static_cast<int>(SQLiteGeneralNSConflictType::SQLITE_GENERAL_NS_FOREIGN_KEY_ORIG),
1813             RegisterFuncType::CONFLICT_SINGLE_VERSION_NS_FOREIGN_KEY_ORIG },
1814         { static_cast<int>(SQLiteGeneralNSConflictType::SQLITE_GENERAL_NS_NATIVE_ALL),
1815             RegisterFuncType::CONFLICT_SINGLE_VERSION_NS_NATIVE_ALL },
1816     };
1817     auto funcType = GetFuncType(conflictType, transMap, sizeof(transMap) / sizeof(TransPair));
1818     if (funcType == RegisterFuncType::REGISTER_FUNC_TYPE_MAX) {
1819         return -E_NOT_SUPPORT;
1820     }
1821     type = funcType;
1822     return E_OK;
1823 }
1824 
GetSchema(SchemaObject & schema) const1825 int SQLiteSingleVerNaturalStore::GetSchema(SchemaObject &schema) const
1826 {
1827     int errCode = E_OK;
1828     auto handle = GetHandle(true, errCode); // Only open kvdb use, no competition for write handle
1829     if (handle == nullptr) {
1830         return errCode;
1831     }
1832 
1833     Timestamp timestamp;
1834     std::string schemaKey = DBConstant::SCHEMA_KEY;
1835     Key key(schemaKey.begin(), schemaKey.end());
1836     Value value;
1837     errCode = handle->GetKvData(SingleVerDataType::META_TYPE, key, value, timestamp);
1838     if (errCode == E_OK) {
1839         std::string schemaValue(value.begin(), value.end());
1840         errCode = schema.ParseFromSchemaString(schemaValue);
1841     } else {
1842         std::string label = MyProp().GetStringProp(DBProperties::IDENTIFIER_DATA, "");
1843         LOGI("[SqlSinStore] [%.3s] Get schema error:%d.", label.c_str(), errCode);
1844     }
1845     ReleaseHandle(handle);
1846     return errCode;
1847 }
1848 
DecideReadOnlyBaseOnSchema(const KvDBProperties & kvDBProp,bool & isReadOnly,SchemaObject & savedSchemaObj) const1849 int SQLiteSingleVerNaturalStore::DecideReadOnlyBaseOnSchema(const KvDBProperties &kvDBProp, bool &isReadOnly,
1850     SchemaObject &savedSchemaObj) const
1851 {
1852     // Check whether it is a memory db
1853     if (kvDBProp.GetBoolProp(KvDBProperties::MEMORY_MODE, false)) {
1854         isReadOnly = false;
1855         return E_OK;
1856     }
1857     SchemaObject inputSchemaObj = kvDBProp.GetSchema();
1858     if (!inputSchemaObj.IsSchemaValid()) {
1859         int errCode = GetSchema(savedSchemaObj);
1860         if (errCode != E_OK && errCode != -E_NOT_FOUND) {
1861             LOGE("[SqlSinStore][DecideReadOnly] GetSchema fail=%d.", errCode);
1862             return errCode;
1863         }
1864         if (savedSchemaObj.IsSchemaValid()) {
1865             isReadOnly = true;
1866             return E_OK;
1867         }
1868     }
1869     // An valid schema will not lead to readonly
1870     isReadOnly = false;
1871     return E_OK;
1872 }
1873 
InitialLocalDataTimestamp()1874 void SQLiteSingleVerNaturalStore::InitialLocalDataTimestamp()
1875 {
1876     Timestamp timestamp = GetCurrentTimestamp();
1877 
1878     int errCode = E_OK;
1879     auto handle = GetHandle(true, errCode);
1880     if (handle == nullptr) {
1881         return;
1882     }
1883 
1884     errCode = handle->UpdateLocalDataTimestamp(timestamp);
1885     if (errCode != E_OK) {
1886         LOGE("Update the timestamp for local data failed:%d", errCode);
1887     }
1888     ReleaseHandle(handle);
1889 }
1890 
GetDbProperties() const1891 const KvDBProperties &SQLiteSingleVerNaturalStore::GetDbProperties() const
1892 {
1893     return GetMyProperties();
1894 }
1895 
GetKvDBSize(const KvDBProperties & properties,uint64_t & size) const1896 int SQLiteSingleVerNaturalStore::GetKvDBSize(const KvDBProperties &properties, uint64_t &size) const
1897 {
1898     std::string storeOnlyIdentDir;
1899     std::string storeIdentDir;
1900     GenericKvDB::GetStoreDirectory(properties, KvDBProperties::SINGLE_VER_TYPE_SQLITE, storeIdentDir,
1901         storeOnlyIdentDir);
1902     const std::vector<std::pair<const std::string, const std::string>> dbDir {
1903         {DBConstant::MAINDB_DIR, DBConstant::SINGLE_VER_DATA_STORE},
1904         {DBConstant::METADB_DIR, DBConstant::SINGLE_VER_META_STORE},
1905         {DBConstant::CACHEDB_DIR, DBConstant::SINGLE_VER_CACHE_STORE}};
1906     int errCode = -E_NOT_FOUND;
1907     for (const auto &item : dbDir) {
1908         std::string storeDir = storeIdentDir + item.first;
1909         std::string storeOnlyDir = storeOnlyIdentDir + item.first;
1910         int err = KvDBUtils::GetKvDbSize(storeDir, storeOnlyDir, item.second, size);
1911         if (err != -E_NOT_FOUND && err != E_OK) {
1912             return err;
1913         }
1914         if (err == E_OK) {
1915             errCode = E_OK;
1916         }
1917     }
1918     return errCode;
1919 }
1920 
AsyncDataMigration(SQLiteSingleVerStorageEngine * storageEngine) const1921 void SQLiteSingleVerNaturalStore::AsyncDataMigration(SQLiteSingleVerStorageEngine *storageEngine) const
1922 {
1923     // Delay a little time to ensure the completion of the delegate callback
1924     std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_DELEGATE_CALLBACK_TIME));
1925     bool isLocked = RuntimeContext::GetInstance()->IsAccessControlled();
1926     if (!isLocked) {
1927         LOGI("[AsyncDataMigration] Begin");
1928         // we can't use engineMutex_ here, because ExecuteMigration will call GetHandle, it will lead to crash at
1929         // engineMutex_.lock_shared
1930         (void)StorageEngineManager::ExecuteMigration(storageEngine);
1931     }
1932 
1933     RefObject::DecObjRef(storageEngine);
1934     RefObject::DecObjRef(this);
1935 }
1936 
SaveSyncItemsInCacheMode(SQLiteSingleVerStorageExecutor * handle,const QueryObject & query,std::vector<DataItem> & dataItems,const DeviceInfo & deviceInfo,Timestamp & maxTimestamp) const1937 int SQLiteSingleVerNaturalStore::SaveSyncItemsInCacheMode(SQLiteSingleVerStorageExecutor *handle,
1938     const QueryObject &query, std::vector<DataItem> &dataItems, const DeviceInfo &deviceInfo,
1939     Timestamp &maxTimestamp) const
1940 {
1941     int errCode = handle->StartTransaction(TransactType::IMMEDIATE);
1942     if (errCode != E_OK) {
1943         return errCode;
1944     }
1945 
1946     int innerCode;
1947     const uint64_t recordVersion = GetCacheRecordVersion();
1948     errCode = handle->PrepareForSavingCacheData(SingleVerDataType::SYNC_TYPE);
1949     if (errCode != E_OK) {
1950         goto END;
1951     }
1952 
1953     for (auto &item : dataItems) {
1954         errCode = handle->SaveSyncDataItemInCacheMode(item, deviceInfo, maxTimestamp, recordVersion, query);
1955         if (errCode != E_OK && errCode != -E_NOT_FOUND) { // LCOV_EXCL_BR_LINE
1956             break;
1957         }
1958     }
1959 
1960     if (errCode == -E_NOT_FOUND) { // LCOV_EXCL_BR_LINE
1961         errCode = E_OK;
1962     }
1963 
1964     innerCode = handle->ResetForSavingCacheData(SingleVerDataType::SYNC_TYPE);
1965     if (innerCode != E_OK) { // LCOV_EXCL_BR_LINE
1966         errCode = innerCode;
1967     }
1968 END:
1969     if (errCode == E_OK) {
1970         storageEngine_->IncreaseCacheRecordVersion(); // use engine wihtin shard lock by handle
1971         errCode = handle->Commit();
1972     } else {
1973         (void)handle->Rollback(); // Keep the error code of the first scene
1974     }
1975     return errCode;
1976 }
1977 
GetDatabaseCreateTimestamp(Timestamp & outTime) const1978 int SQLiteSingleVerNaturalStore::GetDatabaseCreateTimestamp(Timestamp &outTime) const
1979 {
1980     // Found in memory.
1981     {
1982         std::lock_guard<std::mutex> autoLock(createDBTimeMutex_);
1983         if (createDBTime_ != 0) {
1984             outTime = createDBTime_;
1985             return E_OK;
1986         }
1987     }
1988 
1989     const Key key(CREATE_DB_TIME.begin(), CREATE_DB_TIME.end());
1990     Value value;
1991     int errCode = GetMetaData(key, value);
1992     if (errCode != E_OK) {
1993         LOGD("GetDatabaseCreateTimestamp failed, errCode = %d.", errCode);
1994         return errCode;
1995     }
1996 
1997     Timestamp createDBTime = 0;
1998     Parcel parcel(value.data(), value.size());
1999     (void)parcel.ReadUInt64(createDBTime);
2000     if (parcel.IsError()) {
2001         return -E_INVALID_ARGS;
2002     }
2003     outTime = createDBTime;
2004     std::lock_guard<std::mutex> autoLock(createDBTimeMutex_);
2005     createDBTime_ = createDBTime;
2006     return E_OK;
2007 }
2008 
SaveCreateDBTime()2009 int SQLiteSingleVerNaturalStore::SaveCreateDBTime()
2010 {
2011     Timestamp createDBTime = GetCurrentTimestamp();
2012     const Key key(CREATE_DB_TIME.begin(), CREATE_DB_TIME.end());
2013     Value value(Parcel::GetUInt64Len());
2014     Parcel parcel(value.data(), Parcel::GetUInt64Len());
2015     (void)parcel.WriteUInt64(createDBTime);
2016     if (parcel.IsError()) {
2017         LOGE("SaveCreateDBTime failed, something wrong in parcel.");
2018         return -E_PARSE_FAIL;
2019     }
2020 
2021     int errCode = PutMetaData(key, value, false);
2022     if (errCode != E_OK) {
2023         LOGE("SaveCreateDBTime failed, errCode = %d", errCode);
2024         return errCode;
2025     }
2026 
2027     // save in memory.
2028     std::lock_guard<std::mutex> autoLock(createDBTimeMutex_);
2029     createDBTime_ = createDBTime;
2030     return errCode;
2031 }
2032 
RemoveSubscribe(const std::vector<std::string> & subscribeIds)2033 int SQLiteSingleVerNaturalStore::RemoveSubscribe(const std::vector<std::string> &subscribeIds)
2034 {
2035     int errCode = E_OK;
2036     SQLiteSingleVerStorageExecutor *handle = GetHandle(true, errCode);
2037     if (handle == nullptr) {
2038         return errCode;
2039     }
2040 
2041     errCode = handle->StartTransaction(TransactType::IMMEDIATE);
2042     if (errCode != E_OK) {
2043         ReleaseHandle(handle);
2044         return errCode;
2045     }
2046     errCode = handle->RemoveSubscribeTrigger(subscribeIds);
2047     if (errCode != E_OK) {
2048         LOGE("Remove subscribe trigger failed: %d", errCode);
2049         goto ERR;
2050     }
2051     errCode = handle->RemoveSubscribeTriggerWaterMark(subscribeIds);
2052     if (errCode != E_OK) {
2053         LOGE("Remove subscribe data water mark failed: %d", errCode);
2054     }
2055 ERR:
2056     if (errCode == E_OK) {
2057         errCode = handle->Commit();
2058     } else {
2059         (void)handle->Rollback();
2060     }
2061     ReleaseHandle(handle);
2062     return errCode;
2063 }
2064 
RemoveSubscribe(const std::string & subscribeId)2065 int SQLiteSingleVerNaturalStore::RemoveSubscribe(const std::string &subscribeId)
2066 {
2067     return RemoveSubscribe(std::vector<std::string> {subscribeId});
2068 }
2069 
RemoveAllSubscribe()2070 int SQLiteSingleVerNaturalStore::RemoveAllSubscribe()
2071 {
2072     int errCode = E_OK;
2073     SQLiteSingleVerStorageExecutor *handle = GetHandle(true, errCode);
2074     if (handle == nullptr) {
2075         return errCode;
2076     }
2077     std::vector<std::string> triggers;
2078     errCode = handle->GetTriggers(DBConstant::SUBSCRIBE_QUERY_PREFIX, triggers);
2079     if (errCode != E_OK) {
2080         LOGE("Get all subscribe triggers failed. %d", errCode);
2081         ReleaseHandle(handle);
2082         return errCode;
2083     }
2084 
2085     errCode = handle->StartTransaction(TransactType::IMMEDIATE);
2086     if (errCode != E_OK) {
2087         ReleaseHandle(handle);
2088         return errCode;
2089     }
2090 
2091     Key prefixKey;
2092     errCode = handle->RemoveTrigger(triggers);
2093     if (errCode != E_OK) {
2094         LOGE("remove all subscribe triggers failed. %d", errCode);
2095         goto END;
2096     }
2097 
2098     DBCommon::StringToVector(DBConstant::SUBSCRIBE_QUERY_PREFIX, prefixKey);
2099     errCode = handle->DeleteMetaDataByPrefixKey(prefixKey);
2100     if (errCode != E_OK) {
2101         LOGE("remove all subscribe water mark failed. %d", errCode);
2102     }
2103 END:
2104     if (errCode == E_OK) {
2105         errCode = handle->Commit();
2106     } else {
2107         (void)handle->Rollback();
2108     }
2109     ReleaseHandle(handle);
2110     return errCode;
2111 }
2112 
GetAndResizeLocalIdentity(std::string & outTarget) const2113 void SQLiteSingleVerNaturalStore::GetAndResizeLocalIdentity(std::string &outTarget) const
2114 {
2115     int errCode = GetLocalIdentity(outTarget);
2116     if (errCode == -E_NOT_INIT) {
2117         outTarget.resize(DEVICE_ID_LEN);
2118     } else if (errCode != E_OK) {
2119         LOGE("Get local dev id err:%d", errCode);
2120         outTarget.resize(0);
2121     }
2122 }
2123 
2124 #ifdef USE_DISTRIBUTEDDB_CLOUD
GetICloudSyncInterface() const2125 ICloudSyncStorageInterface *SQLiteSingleVerNaturalStore::GetICloudSyncInterface() const
2126 {
2127     std::lock_guard<std::mutex> autoLock(cloudStoreMutex_);
2128     return sqliteCloudKvStore_;
2129 }
2130 
SetCloudDbSchema(const std::map<std::string,DataBaseSchema> & schema)2131 int SQLiteSingleVerNaturalStore::SetCloudDbSchema(const std::map<std::string, DataBaseSchema> &schema)
2132 {
2133     std::lock_guard<std::mutex> autoLock(cloudStoreMutex_);
2134     return sqliteCloudKvStore_->SetCloudDbSchema(schema);
2135 }
2136 
CheckSchemaSupportForCloudSync() const2137 bool SQLiteSingleVerNaturalStore::CheckSchemaSupportForCloudSync() const
2138 {
2139     auto schemaType = GetSchemaObject().GetSchemaType();
2140     if (schemaType != SchemaType::NONE) {
2141         LOGE("un support schema type %d for cloud sync", static_cast<int>(schemaType));
2142         return false;
2143     }
2144     return true;
2145 }
2146 #endif
2147 
GetDataBaseSchemas()2148 std::map<std::string, DataBaseSchema> SQLiteSingleVerNaturalStore::GetDataBaseSchemas()
2149 {
2150     std::lock_guard<std::mutex> autoLock(cloudStoreMutex_);
2151     return sqliteCloudKvStore_->GetDataBaseSchemas();
2152 }
2153 DEFINE_OBJECT_TAG_FACILITIES(SQLiteSingleVerNaturalStore)
2154 }
2155