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