From 521cc8db95b0d246835f8ee21b7459e095fe4ab9 Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Thu, 4 Sep 2025 09:49:21 +0800 Subject: [PATCH 1/4] fixed the not expected collaboration bugs Signed-off-by: Sven Wang --- .../distributeddataservice/framework/BUILD.gn | 1 - .../framework/cloud/schema_meta.cpp | 29 + .../framework/include/cloud/schema_meta.h | 4 +- .../include/commonevent/data_change_event.h | 9 +- .../commonevent/set_searchable_event.h | 4 +- .../framework/include/store/general_store.h | 3 +- .../service/backup/include/backup_manager.h | 8 +- .../service/data_share/common/common_utils.h | 1 + .../service/rdb/BUILD.gn | 1 + .../service/rdb/rdb_general_store.cpp | 7 +- .../service/rdb/rdb_general_store.h | 1 - .../service/rdb/rdb_query.cpp | 93 +-- .../service/rdb/rdb_query.h | 7 +- .../service/rdb/rdb_service_impl.cpp | 787 +++++++++--------- .../service/rdb/rdb_service_impl.h | 55 +- .../service/rdb/rdb_types_utils.cpp | 48 ++ .../service/rdb/rdb_types_utils.h | 31 + .../service/test/BUILD.gn | 19 +- .../service/test/cloud_data_mock_test.cpp | 24 +- .../service/test/cloud_data_test.cpp | 162 ++-- .../data_share_sys_event_subscriber_test.cpp | 2 +- .../service/test/kvdb_service_impl_test.cpp | 2 +- .../test/kvdb_service_stub_unittest.cpp | 13 +- .../test/mock/device_manager_adapter_mock.h | 6 +- .../service/test/mock/device_matrix_mock.h | 4 +- .../service/test/mock/general_store_mock.cpp | 22 +- .../service/test/mock/general_store_mock.h | 6 +- .../test/mock/general_watcher_mock.cpp | 19 +- .../service/test/mock/general_watcher_mock.h | 2 - .../test/mock/preprocess_utils_mock.cpp | 2 +- .../mock/relational_store_manager_mock.cpp | 1 + .../test/permit_delegate_mock_test.cpp | 4 +- .../service/test/rdb_asset_loader_test.cpp | 83 +- .../service/test/rdb_general_store_test.cpp | 28 +- .../service/test/rdb_query_test.cpp | 38 +- .../service/test/rdb_service_impl_test.cpp | 328 ++++++-- .../test/rdb_service_impl_token_test.cpp | 14 +- .../test/udmf_preprocess_utils_mock_test.cpp | 4 +- .../service/test/udmf_run_time_store_test.cpp | 6 +- .../service/test/udmf_service_impl_test.cpp | 10 +- .../test/udmf_service_stub_mock_test.cpp | 5 +- .../service/test/user_delegate_mock_test.cpp | 1 - .../service/test/value_proxy_test.cpp | 10 +- 43 files changed, 1063 insertions(+), 841 deletions(-) create mode 100644 services/distributeddataservice/service/rdb/rdb_types_utils.cpp create mode 100644 services/distributeddataservice/service/rdb/rdb_types_utils.h diff --git a/services/distributeddataservice/framework/BUILD.gn b/services/distributeddataservice/framework/BUILD.gn index 3f6eea650..ba1649ec6 100644 --- a/services/distributeddataservice/framework/BUILD.gn +++ b/services/distributeddataservice/framework/BUILD.gn @@ -21,7 +21,6 @@ config("module_config") { visibility = [ ":*" ] include_dirs = [ "include", - "include/utils", "${data_service_path}/adapter/include", ] } diff --git a/services/distributeddataservice/framework/cloud/schema_meta.cpp b/services/distributeddataservice/framework/cloud/schema_meta.cpp index 273fc6b48..e8c9bba23 100644 --- a/services/distributeddataservice/framework/cloud/schema_meta.cpp +++ b/services/distributeddataservice/framework/cloud/schema_meta.cpp @@ -53,6 +53,35 @@ std::vector Database::GetTableNames() const return tableNames; } +std::vector Database::GetSyncTables() const +{ + std::vector tableNames; + tableNames.reserve(tables.size()); + for (auto &table : tables) { + if (table.deviceSyncFields.empty()) { + continue; + } + tableNames.push_back(table.name); + } + return tableNames; +} + +std::vector Database::GetCloudTables() const +{ + std::vector tableNames; + tableNames.reserve(tables.size()); + for (auto &table : tables) { + if (table.cloudSyncFields.empty()) { + continue; + } + tableNames.push_back(table.name); + if (!table.sharedTableName.empty()) { + tableNames.push_back(table.sharedTableName); + } + } + return tableNames; +} + std::string Database::GetKey() const { return GetKey({user, "default", bundleName, name}); diff --git a/services/distributeddataservice/framework/include/cloud/schema_meta.h b/services/distributeddataservice/framework/include/cloud/schema_meta.h index 889392199..2ab448ae4 100644 --- a/services/distributeddataservice/framework/include/cloud/schema_meta.h +++ b/services/distributeddataservice/framework/include/cloud/schema_meta.h @@ -42,7 +42,6 @@ struct API_EXPORT Database final : public Serializable { std::string name = ""; std::string alias; std::vector tables; - std::vector GetTableNames() const; uint32_t autoSyncType = 0; std::string user = ""; std::string deviceId = ""; @@ -51,6 +50,9 @@ struct API_EXPORT Database final : public Serializable { API_EXPORT std::string GetKey() const; API_EXPORT static std::string GetKey(const std::initializer_list &fields); API_EXPORT static std::string GetPrefix(const std::initializer_list &fields); + std::vector GetTableNames() const; + std::vector GetSyncTables() const; + std::vector GetCloudTables() const; bool Marshal(json &node) const override; bool Unmarshal(const json &node) override; }; diff --git a/services/distributeddataservice/framework/include/commonevent/data_change_event.h b/services/distributeddataservice/framework/include/commonevent/data_change_event.h index 0c74b688b..7bfd4f84f 100644 --- a/services/distributeddataservice/framework/include/commonevent/data_change_event.h +++ b/services/distributeddataservice/framework/include/commonevent/data_change_event.h @@ -27,8 +27,15 @@ public: }; using TableProperties = std::map; struct EventInfo { + EventInfo() = default; + EventInfo(const std::vector &tables) + { + for (auto &table : tables) { + tableProperties[table].isTrackedDataChange = true; + } + } TableProperties tableProperties; - bool isFull; + bool isFull = false; }; DataChangeEvent(StoreInfo storeInfo, EventInfo evtInfo) diff --git a/services/distributeddataservice/framework/include/commonevent/set_searchable_event.h b/services/distributeddataservice/framework/include/commonevent/set_searchable_event.h index 14e0f0bc0..ac917cd60 100644 --- a/services/distributeddataservice/framework/include/commonevent/set_searchable_event.h +++ b/services/distributeddataservice/framework/include/commonevent/set_searchable_event.h @@ -22,8 +22,8 @@ namespace OHOS::DistributedData { class API_EXPORT SetSearchableEvent : public CloudEvent { public: struct EventInfo { - bool isSearchable; - bool isRebuild; + bool isSearchable = false; + bool isRebuild = false; }; SetSearchableEvent(StoreInfo storeInfo, EventInfo evtInfo, int32_t evtId = SET_SEARCHABLE) diff --git a/services/distributeddataservice/framework/include/store/general_store.h b/services/distributeddataservice/framework/include/store/general_store.h index 0b56018c5..5c08283cb 100644 --- a/services/distributeddataservice/framework/include/store/general_store.h +++ b/services/distributeddataservice/framework/include/store/general_store.h @@ -18,10 +18,10 @@ #include #include #include +#include #include #include "executor_pool.h" -#include "snapshot/snapshot.h" #include "store/cursor.h" #include "store/general_value.h" #include "store/general_watcher.h" @@ -30,6 +30,7 @@ namespace OHOS::DistributedData { class CloudDB; class AssetLoader; struct Database; +class Snapshot; class GeneralStore { public: using Watcher = GeneralWatcher; diff --git a/services/distributeddataservice/service/backup/include/backup_manager.h b/services/distributeddataservice/service/backup/include/backup_manager.h index cdd6f2308..e394d4a80 100644 --- a/services/distributeddataservice/service/backup/include/backup_manager.h +++ b/services/distributeddataservice/service/backup/include/backup_manager.h @@ -16,11 +16,13 @@ #ifndef OHOS_DISTRIBUTED_DATA_SERVICES_BACKUP_BACKUP_MANAGER_H #define OHOS_DISTRIBUTED_DATA_SERVICES_BACKUP_BACKUP_MANAGER_H -#include "executor_pool.h" +#include + #include "metadata/secret_key_meta_data.h" #include "metadata/store_meta_data.h" -#include "types.h" - +namespace OHOS { +class ExecutorPool; +} namespace OHOS::DistributedData { class BackupManager { public: diff --git a/services/distributeddataservice/service/data_share/common/common_utils.h b/services/distributeddataservice/service/data_share/common/common_utils.h index a526fbf62..e4493675c 100644 --- a/services/distributeddataservice/service/data_share/common/common_utils.h +++ b/services/distributeddataservice/service/data_share/common/common_utils.h @@ -15,6 +15,7 @@ #ifndef DATASHARESERVICE_COMMON_UTILS_H #define DATASHARESERVICE_COMMON_UTILS_H +#include #include #include diff --git a/services/distributeddataservice/service/rdb/BUILD.gn b/services/distributeddataservice/service/rdb/BUILD.gn index 4273bba45..69c3a7b4c 100644 --- a/services/distributeddataservice/service/rdb/BUILD.gn +++ b/services/distributeddataservice/service/rdb/BUILD.gn @@ -54,6 +54,7 @@ ohos_source_set("distributeddata_rdb") { "rdb_schema_config.cpp", "rdb_service_impl.cpp", "rdb_service_stub.cpp", + "rdb_types_utils.cpp", "rdb_watcher.cpp", ] diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.cpp b/services/distributeddataservice/service/rdb/rdb_general_store.cpp index 94f13725d..309995d44 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.cpp +++ b/services/distributeddataservice/service/rdb/rdb_general_store.cpp @@ -21,12 +21,8 @@ #include "cache_cursor.h" #include "changeevent/remote_change_event.h" -#include "cloud/asset_loader.h" -#include "cloud/cloud_db.h" #include "cloud/cloud_mark.h" -#include "cloud/cloud_store_types.h" #include "cloud/schema_meta.h" -#include "sync_mgr/sync_mgr.h" #include "cloud_service.h" #include "commonevent/data_sync_event.h" #include "crypto/crypto_manager.h" @@ -36,14 +32,13 @@ #include "eventcenter/event_center.h" #include "log_print.h" #include "metadata/meta_data_manager.h" -#include "metadata/secret_key_meta_data.h" #include "rdb_cursor.h" #include "rdb_query.h" #include "relational_store_manager.h" #include "snapshot/bind_event.h" +#include "sync_mgr/sync_mgr.h" #include "utils/anonymous.h" #include "value_proxy.h" -#include "snapshot/snapshot.h" namespace OHOS::DistributedRdb { using namespace DistributedData; using namespace DistributedDB; diff --git a/services/distributeddataservice/service/rdb/rdb_general_store.h b/services/distributeddataservice/service/rdb/rdb_general_store.h index 64296b5fb..6fcb3da2a 100644 --- a/services/distributeddataservice/service/rdb/rdb_general_store.h +++ b/services/distributeddataservice/service/rdb/rdb_general_store.h @@ -26,7 +26,6 @@ #include "rdb_store.h" #include "relational_store_delegate.h" #include "relational_store_manager.h" -#include "snapshot/snapshot.h" #include "store/general_store.h" #include "store/general_value.h" namespace OHOS::DistributedRdb { diff --git a/services/distributeddataservice/service/rdb/rdb_query.cpp b/services/distributeddataservice/service/rdb/rdb_query.cpp index ec716bbcc..44a245a78 100644 --- a/services/distributeddataservice/service/rdb/rdb_query.cpp +++ b/services/distributeddataservice/service/rdb/rdb_query.cpp @@ -21,81 +21,64 @@ #include "value_proxy.h" namespace OHOS::DistributedRdb { using namespace DistributedData; -bool RdbQuery::IsEqual(uint64_t tid) +RdbQuery::RdbQuery(const PredicatesMemo &predicates, bool isPriority) + : isPriority_(isPriority), devices_(predicates.devices_), tables_(predicates.tables_) { - return tid == TYPE_ID; -} + ZLOGD("table size:%{public}zu, device size:%{public}zu, op size:%{public}zu", predicates.tables_.size(), + predicates.devices_.size(), predicates.operations_.size()); + if (predicates.tables_.size() == 1) { + if (!isPriority) { + query_ = DistributedDB::Query::Select(*predicates.tables_.begin()); + } else { + query_.From(*predicates.tables_.begin()); + } + } -std::vector RdbQuery::GetTables() -{ - return tables_; + if (predicates.tables_.size() > 1) { + query_.FromTable(predicates.tables_); + } + + if (predicates.operations_.empty() || predicates.tables_.empty()) { + return; + } + + predicates_ = std::make_shared(*predicates.tables_.begin()); + for (const auto& operation : predicates.operations_) { + if (operation.operator_ >= 0 && operation.operator_ < OPERATOR_MAX) { + (this->*HANDLES[operation.operator_])(operation); + } + } } -void RdbQuery::MakeRemoteQuery(const std::string &devices, const std::string &sql, Values &&args) +RdbQuery::RdbQuery(const std::vector &tables) + : query_(DistributedDB::Query::Select()) { - isRemote_ = true; - devices_ = { devices }; - sql_ = sql; - args_ = std::move(args); + query_.FromTable(tables); } -DistributedDB::Query RdbQuery::GetQuery() const +RdbQuery::RdbQuery(const std::string &device, const std::string &sql, Values &&args) + : isRemote_(true), sql_(sql), args_(std::move(args)), devices_({device}) { - return query_; } -std::vector RdbQuery::GetDevices() const +bool RdbQuery::IsEqual(uint64_t tid) { - return devices_; + return tid == TYPE_ID; } -void RdbQuery::MakeQuery(const PredicatesMemo &predicates) +std::vector RdbQuery::GetTables() { - ZLOGD("table size:%{public}zu, device size:%{public}zu, op size:%{public}zu", predicates.tables_.size(), - predicates.devices_.size(), predicates.operations_.size()); - query_ = predicates.tables_.size() == 1 ? DistributedDB::Query::Select(*predicates.tables_.begin()) - : DistributedDB::Query::Select(); - if (predicates.tables_.size() > 1) { - query_.FromTable(predicates.tables_); - } - if (!predicates.tables_.empty()) { - predicates_ = std::make_shared(*predicates.tables_.begin()); - } - for (const auto &operation : predicates.operations_) { - if (operation.operator_ >= 0 && operation.operator_ < OPERATOR_MAX) { - (this->*HANDLES[operation.operator_])(operation); - } - } - devices_ = predicates.devices_; - tables_ = predicates.tables_; + return tables_; } -void RdbQuery::MakeDeviceQuery(const std::vector &tables) +DistributedDB::Query RdbQuery::GetQuery() const { - query_ = DistributedDB::Query::Select().FromTable(tables); + return query_; } -void RdbQuery::MakeCloudQuery(const PredicatesMemo& predicates) +std::vector RdbQuery::GetDevices() const { - ZLOGD("table size:%{public}zu, device size:%{public}zu, op size:%{public}zu", predicates.tables_.size(), - predicates.devices_.size(), predicates.operations_.size()); - devices_ = predicates.devices_; - tables_ = predicates.tables_; - if (predicates.operations_.empty() || predicates.tables_.size() != 1) { - query_ = DistributedDB::Query::Select(); - if (!predicates.tables_.empty()) { - query_.FromTable(predicates.tables_); - } - return; - } - predicates_ = std::make_shared(*predicates.tables_.begin()); - query_ = DistributedDB::Query::Select().From(*predicates.tables_.begin()); - isPriority_ = true; - for (const auto& operation : predicates.operations_) { - if (operation.operator_ >= 0 && operation.operator_ < OPERATOR_MAX) { - (this->*HANDLES[operation.operator_])(operation); - } - } + return devices_; } bool RdbQuery::IsRemoteQuery() diff --git a/services/distributeddataservice/service/rdb/rdb_query.h b/services/distributeddataservice/service/rdb/rdb_query.h index cf80b032a..753e94975 100644 --- a/services/distributeddataservice/service/rdb/rdb_query.h +++ b/services/distributeddataservice/service/rdb/rdb_query.h @@ -25,6 +25,9 @@ public: using Predicates = NativeRdb::RdbPredicates; static constexpr uint64_t TYPE_ID = 0x20000001; RdbQuery() = default; + explicit RdbQuery(const PredicatesMemo &predicates, bool isPriority = false); + explicit RdbQuery(const std::vector &tables); + RdbQuery(const std::string &device, const std::string &sql, DistributedData::Values &&args); ~RdbQuery() override = default; bool IsEqual(uint64_t tid) override; std::vector GetTables() override; @@ -40,10 +43,6 @@ public: DistributedDB::RemoteCondition GetRemoteCondition() const; bool IsRemoteQuery(); bool IsPriority(); - void MakeQuery(const PredicatesMemo &predicates); - void MakeDeviceQuery(const std::vector &tables); - void MakeRemoteQuery(const std::string &devices, const std::string &sql, DistributedData::Values &&args); - void MakeCloudQuery(const PredicatesMemo &predicates); private: void EqualTo(const RdbPredicateOperation& operation); diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 62f6aec8a..97c2ea41f 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -49,6 +49,7 @@ #include "rdb_query.h" #include "rdb_result_set_impl.h" #include "rdb_schema_config.h" +#include "rdb_types_utils.h" #include "rdb_watcher.h" #include "store/general_store.h" #include "sync_mgr/sync_mgr.h" @@ -74,7 +75,6 @@ using system_clock = std::chrono::system_clock; constexpr uint32_t ITERATE_TIMES = 10000; constexpr uint32_t ALLOW_ONLINE_AUTO_SYNC = 8; -constexpr uint32_t ALLOW_AUTO_SYNC_DEVICE = 10; constexpr int32_t VALID_PARAM_LENGTH = 2; const size_t KEY_COUNT = 2; namespace OHOS::DistributedRdb { @@ -272,36 +272,27 @@ int32_t RdbServiceImpl::InitNotifier(const RdbSyncerParam ¶m, const sptr RdbServiceImpl::GetStore(const RdbSyncerParam ¶m) +bool RdbServiceImpl::IsCollaboration(const StoreMetaData &metaData) { - StoreMetaData storeMetaData = GetStoreMetaData(param); - MetaDataManager::GetInstance().LoadMeta(storeMetaData.GetKey(), storeMetaData, true); - auto watchers = GetWatchers(storeMetaData.tokenId, storeMetaData.storeId); - auto store = AutoCache::GetInstance().GetStore(storeMetaData, watchers); - if (store == nullptr) { - ZLOGE("store null, storeId:%{public}s", storeMetaData.GetStoreAlias().c_str()); + Database database; + database.bundleName = metaData.bundleName; + database.name = metaData.storeId; + database.user = metaData.user; + if (MetaDataManager::GetInstance().LoadMeta(database.GetKey(), database, true)) { + return true; } - return store; -} -void RdbServiceImpl::UpdateMeta(const StoreMetaData &meta, const StoreMetaData &localMeta, AutoCache::Store store) -{ - StoreMetaData syncMeta; - bool isCreatedSync = MetaDataManager::GetInstance().LoadMeta(meta.GetKeyWithoutPath(), syncMeta); - if (!isCreatedSync || localMeta != syncMeta) { - ZLOGI("save sync meta. bundle:%{public}s store:%{public}s type:%{public}d->%{public}d " - "encrypt:%{public}d->%{public}d , area:%{public}d->%{public}d", - meta.bundleName.c_str(), meta.GetStoreAlias().c_str(), syncMeta.storeType, meta.storeType, - syncMeta.isEncrypt, meta.isEncrypt, syncMeta.area, meta.area); - MetaDataManager::GetInstance().SaveMeta(meta.GetKeyWithoutPath(), localMeta); + auto isAutoSyncApp = SyncManager::GetInstance().IsAutoSyncApp(metaData.bundleName, metaData.appId); + if (!isAutoSyncApp) { + return false; } - bool isAutoSync = SyncManager::GetInstance().IsAutoSyncApp(meta.bundleName, meta.appId); - Database dataBase; - if (isAutoSync && RdbSchemaConfig::GetDistributedSchema(localMeta, dataBase) && !dataBase.name.empty() && - !dataBase.bundleName.empty()) { - MetaDataManager::GetInstance().SaveMeta(dataBase.GetKey(), dataBase, true); - store->SetConfig({ false, GeneralStore::DistributedTableMode::COLLABORATION }); + + auto success = RdbSchemaConfig::GetDistributedSchema(metaData, database); + if (success && !database.name.empty() && !database.bundleName.empty()) { + MetaDataManager::GetInstance().SaveMeta(database.GetKey(), database, true); + return true; } + return false; } int32_t RdbServiceImpl::SetDistributedTables(const RdbSyncerParam ¶m, const std::vector &tables, @@ -312,49 +303,47 @@ int32_t RdbServiceImpl::SetDistributedTables(const RdbSyncerParam ¶m, const Anonymous::Change(param.storeName_).c_str()); return RDB_ERROR; } - if (type == DistributedTableType::DISTRIBUTED_SEARCH) { - DistributedData::SetSearchableEvent::EventInfo eventInfo; - eventInfo.isRebuild = isRebuild; - return PostSearchEvent(CloudEvent::SET_SEARCH_TRIGGER, param, eventInfo); + + auto [exists, metaData] = LoadStoreMetaData(param); + if (!exists || metaData.instanceId != 0) { + ZLOGW("bundleName:%{public}s, storeName:%{public}s instance:%{public}d. No store meta", + metaData.bundleName.c_str(), Anonymous::Change(metaData.storeId).c_str(), metaData.instanceId); } - auto meta = GetStoreMetaData(param); - StoreMetaData localMeta; - bool isCreatedLocal = MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), localMeta, true); - if (!isCreatedLocal) { - ZLOGE("no meta. bundleName:%{public}s, storeName:%{public}s. GetStore failed", param.bundleName_.c_str(), - Anonymous::Change(param.storeName_).c_str()); - return RDB_ERROR; + + if (type == DistributedTableType::DISTRIBUTED_SEARCH) { + DistributedData::SetSearchableEvent::EventInfo eventInfo{ .isRebuild = isRebuild }; + return PostSearchEvent(CloudEvent::SET_SEARCH_TRIGGER, metaData, eventInfo); } - auto store = GetStore(meta); + + auto store = GetStore(metaData); if (store == nullptr) { ZLOGE("bundle:%{public}s, %{public}s.", param.bundleName_.c_str(), Anonymous::Change(param.storeName_).c_str()); return RDB_ERROR; } - StoreMetaMapping metaMapping(localMeta); + + StoreMetaMapping metaMapping(metaData); MetaDataManager::GetInstance().LoadMeta(metaMapping.GetKey(), metaMapping, true); if (type == DistributedTableType::DISTRIBUTED_DEVICE) { - UpdateMeta(meta, localMeta, store); - metaMapping.devicePath = meta.dataDir; + SaveSyncMeta(metaData); + if (IsCollaboration(metaData)) { + store->SetConfig({false, GeneralStore::DistributedTableMode::COLLABORATION}); + } + metaMapping.devicePath = metaData.dataDir; } else if (type == DistributedTableType::DISTRIBUTED_CLOUD) { - if (localMeta.asyncDownloadAsset != param.asyncDownloadAsset_ || localMeta.enableCloud != param.enableCloud_) { + if (metaData.asyncDownloadAsset != param.asyncDownloadAsset_ || metaData.enableCloud != param.enableCloud_) { ZLOGI("update meta, bundleName:%{public}s, storeName:%{public}s, asyncDownloadAsset? [%{public}d -> " - "%{public}d],enableCloud? [%{public}d -> %{public}d]", - param.bundleName_.c_str(), Anonymous::Change(param.storeName_).c_str(), localMeta.asyncDownloadAsset, - param.asyncDownloadAsset_, localMeta.enableCloud, param.enableCloud_); - localMeta.asyncDownloadAsset = param.asyncDownloadAsset_; - localMeta.enableCloud = param.enableCloud_; - MetaDataManager::GetInstance().SaveMeta(localMeta.GetKey(), localMeta, true); + "%{public}d],enableCloud? [%{public}d -> %{public}d]", param.bundleName_.c_str(), + Anonymous::Change(param.storeName_).c_str(), metaData.asyncDownloadAsset, param.asyncDownloadAsset_, + metaData.enableCloud, param.enableCloud_); + metaData.asyncDownloadAsset = param.asyncDownloadAsset_; + metaData.enableCloud = param.enableCloud_; + MetaDataManager::GetInstance().SaveMeta(metaData.GetKey(), metaData, true); } - metaMapping.cloudPath = meta.dataDir; + metaMapping.cloudPath = metaData.dataDir; } - metaMapping = localMeta; + metaMapping = metaData; MetaDataManager::GetInstance().SaveMeta(metaMapping.GetKey(), metaMapping, true); - std::vector relationships; - for (const auto &reference : references) { - DistributedData::Reference relationship = { reference.sourceTable, reference.targetTable, reference.refFields }; - relationships.emplace_back(relationship); - } - return store->SetDistributedTables(tables, type, relationships); + return store->SetDistributedTables(tables, type, RdbTypesUtils::Convert(references)); } void RdbServiceImpl::OnAsyncComplete(uint32_t tokenId, pid_t pid, uint32_t seqNum, Details &&result) @@ -433,7 +422,14 @@ std::pair> RdbServiceImpl::R Anonymous::Change(param.storeName_).c_str()); return { RDB_ERROR, nullptr }; } - StoreMetaData meta = GetStoreMetaData(param); + + auto [exists, meta] = LoadStoreMetaData(param); + if (!exists || meta.instanceId != 0) { + ZLOGE("bundleName:%{public}s, storeName:%{public}s instance:%{public}d. No store meta", + meta.bundleName.c_str(), Anonymous::Change(meta.storeId).c_str(), meta.instanceId); + return { RDB_ERROR, nullptr }; + } + auto store = GetStore(meta); if (store == nullptr) { ZLOGE("bundleName:%{public}s, storeName:%{public}s. GetStore failed", param.bundleName_.c_str(), @@ -445,8 +441,7 @@ std::pair> RdbServiceImpl::R ZLOGW("bundleName:%{public}s, storeName:%{public}s. meta sync failed", param.bundleName_.c_str(), Anonymous::Change(param.storeName_).c_str()); } - RdbQuery rdbQuery; - rdbQuery.MakeRemoteQuery(DmAdapter::GetInstance().ToUUID(device), sql, ValueProxy::Convert(selectionArgs)); + RdbQuery rdbQuery(DmAdapter::GetInstance().ToUUID(device), sql, ValueProxy::Convert(selectionArgs)); auto [errCode, cursor] = store->Query("", rdbQuery); if (errCode != GeneralError::E_OK) { return { RDB_ERROR, nullptr }; @@ -462,88 +457,63 @@ int32_t RdbServiceImpl::Sync(const RdbSyncerParam ¶m, const Option &option, Anonymous::Change(param.storeName_).c_str()); return RDB_ERROR; } + + auto [exists, meta] = LoadStoreMetaData(param); + if (meta.instanceId != 0) { // the exists flag should + ZLOGW("bundleName:%{public}s, storeName:%{public}s instance:%{public}d. No store meta", + meta.bundleName.c_str(), Anonymous::Change(meta.storeId).c_str(), meta.instanceId); + return RDB_ERROR; + } + if (option.mode < DistributedData::GeneralStore::CLOUD_END && option.mode >= DistributedData::GeneralStore::CLOUD_BEGIN) { - DoCloudSync(param, option, predicates, async); + DoCloudSync(meta, option, predicates, async); return RDB_OK; } - return DoSync(param, option, predicates, async); -} -void RdbServiceImpl::SaveAutoSyncDeviceId(const StoreMetaData &meta, const std::vector &devices) -{ - DistributedData::SpecialChannelData specialDevices; - if (devices.empty()) { - ZLOGE("There is no deviceId in predicates"); - return; + StoreMetaData syncMeta; + exists = MetaDataManager::GetInstance().LoadMeta(meta.GetKeyWithoutPath(), syncMeta); + if (!exists || syncMeta.dataDir != meta.dataDir) { + ZLOGW("bundleName:%{public}s, storeName:%{public}s No sync meta(%{public}d) or dataDir invalid", + meta.bundleName.c_str(), Anonymous::Change(meta.storeId).c_str(), exists); + return RDB_ERROR; } - MetaDataManager::GetInstance().LoadMeta(specialDevices.GetKey(), specialDevices, true); - auto &specialUUIDs = specialDevices.devices; - for (auto &device : devices) { - auto sha256UUID = Crypto::Sha256(device); - auto iter = std::find(specialUUIDs.begin(), specialUUIDs.end(), sha256UUID); - if (iter != specialUUIDs.end() && specialUUIDs.size() == 1) { - continue; - } - if (iter != specialUUIDs.end()) { - std::swap(*iter, specialUUIDs.back()); - } else { - specialUUIDs.push_back(sha256UUID); - } - } - if (specialUUIDs.size() > ALLOW_AUTO_SYNC_DEVICE) { - auto index = specialUUIDs.size() - ALLOW_AUTO_SYNC_DEVICE; - specialUUIDs.erase(specialUUIDs.begin(), specialUUIDs.begin() + index - 1); - } - MetaDataManager::GetInstance().SaveMeta(specialDevices.GetKey(), specialDevices, true); + return DoSync(syncMeta, option, predicates, async); } -int RdbServiceImpl::DoSync(const RdbSyncerParam ¶m, const RdbService::Option &option, +int RdbServiceImpl::DoSync(const StoreMetaData &meta, const RdbService::Option &option, const PredicatesMemo &predicates, const AsyncDetail &async) { - StoreMetaData meta = GetStoreMetaData(param); - if (meta.instanceId != 0) { + auto store = GetStore(meta); + if (store == nullptr) { return RDB_ERROR; } - RdbQuery rdbQuery; - rdbQuery.MakeQuery(predicates); + RdbQuery rdbQuery(predicates); auto devices = rdbQuery.GetDevices().empty() ? DmAdapter::ToUUID(DmAdapter::GetInstance().GetRemoteDevices()) : DmAdapter::ToUUID(rdbQuery.GetDevices()); - bool isAutoSync = SyncManager::GetInstance().IsAutoSyncApp(meta.bundleName, meta.appId); - if (isAutoSync && !rdbQuery.GetDevices().empty()) { - SaveAutoSyncDeviceId(meta, devices); - } - auto store = GetStore(meta); - if (store == nullptr) { - return RDB_ERROR; + if (!rdbQuery.GetDevices().empty() && !devices.empty()) { + SaveAutoSyncInfo(meta, devices); } auto pid = IPCSkeleton::GetCallingPid(); SyncParam syncParam = { option.mode, 0, option.isCompensation }; - auto tokenId = IPCSkeleton::GetCallingTokenID(); + auto tokenId = meta.tokenId; ZLOGD("seqNum=%{public}u", option.seqNum); - auto complete = [this, rdbQuery, store, pid, syncParam, tokenId, seq = option.seqNum]( - const auto &results) mutable { + auto notify = [this, tokenId, seqNum = option.seqNum, pid](const GenDetails &result) mutable { + OnAsyncComplete(tokenId, pid, seqNum, HandleGenDetails(result)); + }; + auto complete = [rdbQuery, store, syncParam, notify](const auto &results) mutable { auto ret = ProcessResult(results); - store->Sync( - ret.first, rdbQuery, - [this, tokenId, seq, pid](const GenDetails &result) mutable { - OnAsyncComplete(tokenId, pid, seq, HandleGenDetails(result)); - }, - syncParam); + store->Sync(ret.first, rdbQuery, notify, syncParam); }; if (IsNeedMetaSync(meta, devices)) { auto result = MetaDataManager::GetInstance().Sync(devices, complete); return result ? GeneralError::E_OK : GeneralError::E_ERROR; } - return store->Sync( - devices, rdbQuery, - [this, tokenId, pid, seqNum = option.seqNum](const GenDetails &result) mutable { - OnAsyncComplete(tokenId, pid, seqNum, HandleGenDetails(result)); - }, - syncParam).first; + auto [ret, _] = store->Sync(devices, rdbQuery, notify, syncParam); + return ret; } bool RdbServiceImpl::IsNeedMetaSync(const StoreMetaData &meta, const std::vector &uuids) @@ -604,8 +574,7 @@ void RdbServiceImpl::DoCompensateSync(const BindEvent &event) auto memo = predicates.GetDistributedPredicates(); std::shared_ptr query = nullptr; if (!memo.tables_.empty()) { - query = std::make_shared(); - query->MakeCloudQuery(memo); + query = std::make_shared(memo, true); } auto mixMode = event.GetEventId() == BindEvent::COMPENSATE_SYNC ? GeneralStore::MixMode(TIME_FIRST, GeneralStore::AUTO_SYNC_MODE) @@ -615,27 +584,23 @@ void RdbServiceImpl::DoCompensateSync(const BindEvent &event) EventCenter::GetInstance().PostEvent(std::move(evt)); } -void RdbServiceImpl::DoCloudSync(const RdbSyncerParam ¶m, const RdbService::Option &option, +void RdbServiceImpl::DoCloudSync(const StoreMetaData &metaData, const RdbService::Option &option, const PredicatesMemo &predicates, const AsyncDetail &async) { - StoreInfo storeInfo; - storeInfo.bundleName = param.bundleName_; - storeInfo.tokenId = IPCSkeleton::GetCallingTokenID(); - storeInfo.user = AccountDelegate::GetInstance()->GetUserByToken(storeInfo.tokenId); - storeInfo.storeName = RemoveSuffix(param.storeName_); + StoreInfo storeInfo = GetStoreInfoEx(metaData); std::shared_ptr query = nullptr; if (!predicates.tables_.empty()) { - query = std::make_shared(); - query->MakeCloudQuery(predicates); + query = std::make_shared(predicates, true); } auto pid = IPCSkeleton::GetCallingPid(); GenAsync asyncCallback = [this, tokenId = storeInfo.tokenId, seqNum = option.seqNum, pid]( const GenDetails &result) mutable { OnAsyncComplete(tokenId, pid, seqNum, HandleGenDetails(result)); }; - GenAsync syncCallback = [async, ¶m](const GenDetails &details) { - ZLOGD("Cloud Sync complete, bundleName:%{public}s, storeName:%{public}s", param.bundleName_.c_str(), - Anonymous::Change(param.storeName_).c_str()); + GenAsync syncCallback = [async, bundleName = storeInfo.bundleName, storeName = storeInfo.storeName]( + const GenDetails &details) { + ZLOGD("Cloud Sync complete, bundleName:%{public}s, storeName:%{public}s", bundleName.c_str(), + Anonymous::Change(storeName).c_str()); if (async != nullptr) { async(HandleGenDetails(details)); } @@ -645,7 +610,7 @@ void RdbServiceImpl::DoCloudSync(const RdbSyncerParam ¶m, const RdbService:: : (option.isAutoSync ? GeneralStore::AUTO_SYNC_MODE : GeneralStore::MANUAL_SYNC_MODE); auto mixMode = static_cast(GeneralStore::MixMode(option.mode, highMode)); SyncParam syncParam = { mixMode, (option.isAsync ? 0 : static_cast(WAIT_TIME)), option.isCompensation }; - syncParam.asyncDownloadAsset = param.asyncDownloadAsset_; + syncParam.asyncDownloadAsset = metaData.asyncDownloadAsset; auto info = ChangeEvent::EventInfo(syncParam, option.isAutoSync, query, option.isAutoSync ? nullptr : option.isAsync ? asyncCallback @@ -677,8 +642,8 @@ int32_t RdbServiceImpl::Subscribe(const RdbSyncerParam ¶m, const SubscribeOp return true; }); if (isCreate) { - AutoCache::GetInstance().SetObserver(tokenId, GetWatchers(tokenId, param.storeName_), GetPath(param), - RemoveSuffix(param.storeName_)); + AutoCache::GetInstance().SetObserver(tokenId, GetWatchers(tokenId, param.storeName_), + GetStoreMetaData(param).dataDir, RemoveSuffix(param.storeName_)); } return RDB_OK; } @@ -706,8 +671,8 @@ int32_t RdbServiceImpl::UnSubscribe(const RdbSyncerParam ¶m, const Subscribe return true; }); if (destroyed) { - AutoCache::GetInstance().SetObserver(tokenId, GetWatchers(tokenId, param.storeName_), GetPath(param), - RemoveSuffix(param.storeName_)); + AutoCache::GetInstance().SetObserver(tokenId, GetWatchers(tokenId, param.storeName_), + GetStoreMetaData(param).dataDir, RemoveSuffix(param.storeName_)); } return RDB_OK; } @@ -815,14 +780,17 @@ std::pair> RdbServiceImpl::Query Anonymous::Change(param.storeName_).c_str()); return { RDB_ERROR, {} }; } - auto rdbQuery = std::make_shared(); - rdbQuery->MakeQuery(predicates); + + auto [exists, meta] = LoadStoreMetaData(param); + if (!exists || meta.instanceId != 0) { + ZLOGW("bundleName:%{public}s, storeName:%{public}s instance:%{public}d. No store meta", + meta.bundleName.c_str(), Anonymous::Change(meta.storeId).c_str(), meta.instanceId); + return { RDB_ERROR, {} }; + } + + auto rdbQuery = std::make_shared(predicates); rdbQuery->SetColumns(columns); - StoreInfo storeInfo; - storeInfo.bundleName = param.bundleName_; - storeInfo.tokenId = IPCSkeleton::GetCallingTokenID(); - storeInfo.user = AccountDelegate::GetInstance()->GetUserByToken(storeInfo.tokenId); - storeInfo.storeName = RemoveSuffix(param.storeName_); + StoreInfo storeInfo = GetStoreInfoEx(meta); auto [status, cursor] = AllocResource(storeInfo, rdbQuery); if (cursor == nullptr) { ZLOGE("cursor is null, bundleName:%{public}s, storeName:%{public}s", param.bundleName_.c_str(), @@ -914,8 +882,8 @@ int32_t RdbServiceImpl::BeforeOpen(RdbSyncerParam ¶m) } auto [exist, meta] = LoadStoreMetaData(param); if (!exist) { - ZLOGW("bundleName:%{public}s, storeName:%{public}s. no meta", param.bundleName_.c_str(), - Anonymous::Change(param.storeName_).c_str()); + ZLOGW("bundleName:%{public}s, storeName:%{public}s instance:%{public}d. No store meta", + meta.bundleName.c_str(), Anonymous::Change(meta.storeId).c_str(), meta.instanceId); return RDB_NO_META; } SetReturnParam(meta, param); @@ -1010,11 +978,11 @@ int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) auto isCreated = MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), old, true); meta.enableCloud = isCreated ? old.enableCloud : meta.enableCloud; if (!isCreated || meta != old) { - Upgrade(param, old); + Upgrade(meta, old); ZLOGI("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " "area:%{public}d->%{public}d", meta.bundleName.c_str(), meta.GetStoreAlias().c_str(), old.storeType, meta.storeType, old.isEncrypt, meta.isEncrypt, old.area, meta.area); - meta.isNeedUpdateDeviceId = isCreated && !TryUpdateDeviceId(param, old, meta); + meta.isNeedUpdateDeviceId = isCreated && !TryUpdateDeviceId(old, meta); MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true); AutoLaunchMetaData launchData; if (!MetaDataManager::GetInstance().LoadMeta(meta.GetAutoLaunchKey(), launchData, true)) { @@ -1041,7 +1009,7 @@ int32_t RdbServiceImpl::AfterOpen(const RdbSyncerParam ¶m) if (param.isEncrypt_ && !param.password_.empty()) { SaveSecretKeyMeta(meta, param.password_); } - GetSchema(param); + GetCloudSchema(meta); return RDB_OK; } @@ -1063,7 +1031,61 @@ bool RdbServiceImpl::SaveAppIDMeta(const StoreMetaData &meta, const StoreMetaDat return true; } -int32_t RdbServiceImpl::ReportStatistic(const RdbSyncerParam ¶m, const RdbStatEvent &statEvent) +void RdbServiceImpl::SaveAutoSyncInfo(const StoreMetaData &metaData, const std::vector &devices) +{ + if (!SyncManager::GetInstance().IsAutoSyncApp(metaData.bundleName, metaData.appId)) { + return; + } + + bool changed = false; + bool immediately = false; + for (auto &device : devices) { + auto sha256UUID = Crypto::Sha256(device); + auto [exists, notHeader] = specialChannels_.Contains(sha256UUID); + if (!exists) { + immediately = true; + specialChannels_.Set(sha256UUID, {}); + } + changed = changed || notHeader; + } + if (!changed && !immediately) { + return; + } + + DoChannelsMemento(immediately); +} + +void RdbServiceImpl::DoChannelsMemento(bool immediately) +{ + SpecialChannelData specialChannels; + auto [memento, values] = specialChannels_.DumpMemento(); + specialChannels.devices = memento; + if (executors_ == nullptr || immediately) { + MetaDataManager::GetInstance().SaveMeta(SpecialChannelData::GetKey(), specialChannels, true); + return; + } + + if (saveChannelsTask_ != ExecutorPool::INVALID_TASK_ID) { + executors_->Remove(saveChannelsTask_); + saveChannelsTask_ = ExecutorPool::INVALID_TASK_ID; + } + + saveChannelsTask_ = executors_->Schedule(std::chrono::minutes(SAVE_CHANNEL_INTERVAL), [specialChannels] { + MetaDataManager::GetInstance().SaveMeta(SpecialChannelData::GetKey(), specialChannels, true); + }); +} + +bool RdbServiceImpl::IsSpecialChannel(const std::string &device) +{ + auto sha256UUID = Crypto::Sha256(device); + auto [exists, changed] = specialChannels_.Contains(sha256UUID); + if (changed) { + DoChannelsMemento(); + } + return exists; +} + +int32_t RdbServiceImpl::ReportStatistic(const RdbSyncerParam& param, const RdbStatEvent &statEvent) { if (!IsValidAccess(param.bundleName_, param.storeName_)) { ZLOGE("bundleName:%{public}s, storeName:%{public}s. Permission error", param.bundleName_.c_str(), @@ -1074,52 +1096,16 @@ int32_t RdbServiceImpl::ReportStatistic(const RdbSyncerParam ¶m, const RdbSt return RDB_OK; } -void RdbServiceImpl::GetSchema(const RdbSyncerParam ¶m) -{ - if (executors_ != nullptr) { - StoreInfo storeInfo; - storeInfo.tokenId = IPCSkeleton::GetCallingTokenID(); - storeInfo.bundleName = param.bundleName_; - storeInfo.storeName = RemoveSuffix(param.storeName_); - auto [instanceId, user] = GetInstIndexAndUser(storeInfo.tokenId, param.bundleName_); - storeInfo.instanceId = instanceId; - storeInfo.user = user; - storeInfo.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; - auto meta = GetStoreMetaData(param); - storeInfo.path = meta.dataDir; - executors_->Execute([storeInfo]() { - auto event = std::make_unique(CloudEvent::GET_SCHEMA, std::move(storeInfo)); - EventCenter::GetInstance().PostEvent(move(event)); - return; - }); - } -} - -std::pair RdbServiceImpl::LoadStoreMetaData(const RdbSyncerParam ¶m) +void RdbServiceImpl::GetCloudSchema(const StoreMetaData &metaData) { - StoreMetaData metaData; - metaData.uid = IPCSkeleton::GetCallingUid(); - metaData.tokenId = IPCSkeleton::GetCallingTokenID(); - auto [instanceId, user] = GetInstIndexAndUser(metaData.tokenId, param.bundleName_); - metaData.instanceId = instanceId; - metaData.bundleName = param.bundleName_; - metaData.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; - metaData.storeId = RemoveSuffix(param.storeName_); - if (AccessTokenKit::GetTokenTypeFlag(metaData.tokenId) != TOKEN_HAP && param.subUser_ != 0) { - metaData.user = std::to_string(param.subUser_); - } else { - metaData.user = std::to_string(user); + if (executors_ == nullptr) { + return; } - metaData.storeType = param.type_; - metaData.securityLevel = param.level_; - metaData.area = param.area_; - metaData.appId = CheckerManager::GetInstance().GetAppId(Converter::ConvertToStoreInfo(metaData)); - metaData.appType = "harmony"; - metaData.hapName = param.hapName_; - metaData.customDir = param.customDir_; - metaData.dataDir = DirectoryManager::GetInstance().GetStorePath(metaData) + "/" + param.storeName_; - auto exist = MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData, true); - return { exist, metaData }; + StoreInfo storeInfo = GetStoreInfoEx(metaData); + executors_->Execute([storeInfo]() { + auto event = std::make_unique(CloudEvent::GET_SCHEMA, std::move(storeInfo)); + EventCenter::GetInstance().PostEvent(move(event)); + }); } StoreMetaData RdbServiceImpl::GetStoreMetaData(const RdbSyncerParam ¶m) @@ -1154,13 +1140,46 @@ StoreMetaData RdbServiceImpl::GetStoreMetaData(const RdbSyncerParam ¶m) return metaData; } -int32_t RdbServiceImpl::Upgrade(const RdbSyncerParam ¶m, const StoreMetaData &old) +std::pair RdbServiceImpl::LoadStoreMetaData(const RdbSyncerParam ¶m) +{ + StoreMetaData metaData = GetStoreMetaData(param); + auto exist = MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData, true); + return {exist, metaData}; +} + +void RdbServiceImpl::SaveSyncMeta(const StoreMetaData &metaData) +{ + StoreMetaData syncMeta; + bool isCreated = MetaDataManager::GetInstance().LoadMeta(metaData.GetKeyWithoutPath(), syncMeta); + if (!isCreated || metaData != syncMeta) { + ZLOGI("save sync meta. bundle:%{public}s store:%{public}s type:%{public}d->%{public}d " + "encrypt:%{public}d->%{public}d , area:%{public}d->%{public}d", + metaData.bundleName.c_str(), metaData.GetStoreAlias().c_str(), syncMeta.storeType, metaData.storeType, + syncMeta.isEncrypt, metaData.isEncrypt, syncMeta.area, metaData.area); + MetaDataManager::GetInstance().SaveMeta(metaData.GetKeyWithoutPath(), metaData); + } +} + +std::pair RdbServiceImpl::LoadSyncMeta(const Database &database) +{ + std::pair result; + auto &[isCreated, metaData] = result; + metaData.storeId = database.name; + metaData.bundleName = database.bundleName; + metaData.user = database.user; + metaData.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + metaData.instanceId = 0; + isCreated = MetaDataManager::GetInstance().LoadMeta(metaData.GetKeyWithoutPath(), metaData); + return result; +} + +int32_t RdbServiceImpl::Upgrade(const StoreMetaData &metaData, const StoreMetaData &old) { if (old.storeType == RDB_DEVICE_COLLABORATION && old.version < StoreMetaData::UUID_CHANGED_TAG) { - auto store = GetStore(param); + auto store = GetStore(metaData); if (store == nullptr) { - ZLOGE("store is null, bundleName:%{public}s storeName:%{public}s", param.bundleName_.c_str(), - Anonymous::Change(param.storeName_).c_str()); + ZLOGE("store is null, bundleName:%{public}s storeName:%{public}s", metaData.bundleName.c_str(), + Anonymous::Change(metaData.storeId).c_str()); return RDB_ERROR; } return store->Clean({}, GeneralStore::CleanMode::NEARBY_DATA, "") == GeneralError::E_OK ? RDB_OK : RDB_ERROR; @@ -1217,25 +1236,6 @@ int32_t RdbServiceImpl::OnBind(const BindInfo &bindInfo) return 0; } -StoreMetaData RdbServiceImpl::GetStoreMetaData(const Database &dataBase) -{ - StoreMetaMapping storeMetaMapping; - storeMetaMapping.storeId = dataBase.name; - storeMetaMapping.bundleName = dataBase.bundleName; - storeMetaMapping.user = dataBase.user; - storeMetaMapping.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; - auto tokenId = IPCSkeleton::GetCallingTokenID(); - storeMetaMapping.tokenId = tokenId; - auto [instanceId, user] = GetInstIndexAndUser(storeMetaMapping.tokenId, storeMetaMapping.bundleName); - storeMetaMapping.instanceId = instanceId; - MetaDataManager::GetInstance().LoadMeta(storeMetaMapping.GetKey(), storeMetaMapping, true); - StoreMetaData storeMetaData = storeMetaMapping; - if (storeMetaMapping.dataDir != storeMetaMapping.devicePath) { - MetaDataManager::GetInstance().LoadMeta(storeMetaMapping.GetDeviceStoreMetaKey(), storeMetaData, true); - } - return storeMetaData; -} - std::shared_ptr RdbServiceImpl::GetStore(const StoreMetaData &storeMetaData) { auto watchers = GetWatchers(storeMetaData.tokenId, storeMetaData.storeId); @@ -1259,90 +1259,75 @@ std::vector RdbServiceImpl::GetReuseDevice(const std::vector &devices, const StoreMetaData &storeMetaData, +int RdbServiceImpl::DoAutoSync(const std::vector &devices, const StoreMetaData &metaData, const std::vector &tables) { - if (storeMetaData.instanceId != 0) { - return RDB_ERROR; - } - DistributedData::SpecialChannelData specialDevices; - if (!MetaDataManager::GetInstance().LoadMeta(specialDevices.GetKey(), specialDevices, true) || - specialDevices.devices.empty()) { - ZLOGE("There is no auto sync devices, store:%{public}s.", Anonymous::Change(storeMetaData.storeId).c_str()); - return RDB_ERROR; - } - auto &specialUUIDs = specialDevices.devices; - std::vector syncDevices; - for (auto &device : devices) { - auto sha256UUID = Crypto::Sha256(device); - if (std::find(specialUUIDs.begin(), specialUUIDs.end(), sha256UUID) != specialUUIDs.end()) { - syncDevices.push_back(device); - } - } - auto store = GetStore(storeMetaData); - if (syncDevices.empty() || executors_ == nullptr || store == nullptr) { - ZLOGE("Designated sync device not in cache storeId:%{public}s", storeMetaData.GetStoreAlias().c_str()); + if (executors_ == nullptr || tables.empty()) { + ZLOGE("executors_ null or no tables, storeId:%{public}s", metaData.GetStoreAlias().c_str()); return RDB_ERROR; } - SyncParam syncParam = { 0, 0 }; - DetailAsync async; - executors_->Execute([this, tables, store, syncParam, async, syncDevices, storeMetaData]() { - RdbQuery rdbQuery; - rdbQuery.MakeDeviceQuery(tables); - std::vector onDevices = GetReuseDevice(syncDevices, storeMetaData); + executors_->Execute([this, tables, devices, metaData]() { + RdbQuery rdbQuery(tables); + std::vector onDevices = GetReuseDevice(devices, metaData); if (onDevices.empty()) { - ZLOGE("autosync device null, storeId:%{public}s", storeMetaData.GetStoreAlias().c_str()); + ZLOGE("autosync ondevices null, storeId:%{public}s", metaData.GetStoreAlias().c_str()); + return; + } + auto store = GetStore(metaData); + if (store == nullptr) { + ZLOGE("autosync store null, storeId:%{public}s", metaData.GetStoreAlias().c_str()); return; } - auto complete = [rdbQuery, store, syncParam, async](const auto &results) mutable { + auto complete = [rdbQuery, store](const auto &results) mutable { auto ret = ProcessResult(results); - store->Sync(ret.first, rdbQuery, async, syncParam); + store->Sync(ret.first, rdbQuery, DetailAsync(), { 0, 0 }); }; - if (IsNeedMetaSync(storeMetaData, onDevices)) { + if (IsNeedMetaSync(metaData, onDevices)) { MetaDataManager::GetInstance().Sync(onDevices, complete); return; } - (void)store->Sync(onDevices, rdbQuery, async, syncParam).first; - return; + store->Sync(onDevices, rdbQuery, DetailAsync(), { 0, 0 }); }); return RDB_OK; } -int RdbServiceImpl::DoOnlineSync(const std::string &device, const Database &dataBase) -{ - std::vector tableNames; - for (auto &table : dataBase.tables) { - if (!table.deviceSyncFields.empty()) { - tableNames.push_back(table.name); - } - } - StoreMetaData storeMetaData = GetStoreMetaData(dataBase); - return DoAutoSync({ device }, storeMetaData, tableNames); -} - int32_t RdbServiceImpl::OnReady(const std::string &device) { if (device.empty()) { return 0; } int index = ALLOW_ONLINE_AUTO_SYNC; - Database dataBase; - std::string prefix = dataBase.GetPrefix({}); - std::vector dataBases; - if (!MetaDataManager::GetInstance().LoadMeta(prefix, dataBases, true)) { - return 0; - } - for (auto &dataBase : dataBases) { - if ((dataBase.autoSyncType == AutoSyncType::SYNC_ON_READY || - dataBase.autoSyncType == AutoSyncType::SYNC_ON_CHANGE_READY) && - index > 0) { - if (DoOnlineSync(device, dataBase) != RDB_OK) { - ZLOGE("store online sync fail, storeId:%{public}s", Anonymous::Change(dataBase.name).c_str()); - } - index--; + std::string prefix = Database::GetPrefix({}); + std::vector databases; + if (!MetaDataManager::GetInstance().LoadMeta(prefix, databases, true)) { + return -E_OK; + } + int32_t synced = 0; + auto isSpecialDevice = IsSpecialChannel(device); + for (auto &database : databases) { + if (database.autoSyncType != AutoSyncType::SYNC_ON_READY && + database.autoSyncType != AutoSyncType::SYNC_ON_CHANGE_READY) { + continue; + } + + if (index <= 0) { + return -E_OVER_MAX_LIMITS; + } + index--; + + auto [isCreated, metaData] = LoadSyncMeta(database); + if (!isCreated || metaData.instanceId != 0) { + continue; + } + + if (SyncManager::GetInstance().IsAutoSyncApp(metaData.bundleName, metaData.appId) && !isSpecialDevice) { + continue; } + + synced++; + DoAutoSync({ device }, metaData, database.GetSyncTables()); } - return 0; + return synced; } void RdbServiceImpl::SyncAgent::SetNotifier(sptr notifier) @@ -1467,6 +1452,9 @@ void RdbServiceImpl::DumpRdbServiceInfo(int fd, std::map{} }); RegisterRdbServiceInfo(); RegisterHandler(); return RDB_OK; @@ -1477,28 +1465,53 @@ RdbServiceImpl::~RdbServiceImpl() DumpManager::GetInstance().RemoveHandler("FEATURE_INFO", uintptr_t(this)); } -int RdbServiceImpl::DoDataChangeSync(const StoreInfo &storeInfo, const RdbChangedData &rdbChangedData) +void RdbServiceImpl::OnCollaborationChange(const StoreMetaData &metaData, const RdbChangedData &changedData) { - std::vector tableNames; - Database dataBase; - dataBase.bundleName = storeInfo.bundleName; - dataBase.name = storeInfo.storeName; - dataBase.user = std::to_string(storeInfo.user); - dataBase.deviceId = storeInfo.deviceId; - for (const auto &[key, value] : rdbChangedData.tableData) { - if (value.isP2pSyncDataChange) { - tableNames.push_back(key); - } + Database database; + database.bundleName = metaData.bundleName; + database.name = metaData.storeId; + database.user = metaData.user; + database.deviceId = metaData.deviceId; + if (!MetaDataManager::GetInstance().LoadMeta(database.GetKey(), database, true)) { + return; } - if (!MetaDataManager::GetInstance().LoadMeta(dataBase.GetKey(), dataBase, true)) { - return RDB_OK; + + if (database.autoSyncType != AutoSyncType::SYNC_ON_CHANGE && + database.autoSyncType != AutoSyncType::SYNC_ON_CHANGE_READY) { + return; + } + + auto devices = DmAdapter::ToUUID(DmAdapter::GetInstance().GetRemoteDevices()); + if (SyncManager::GetInstance().IsAutoSyncApp(metaData.bundleName, metaData.appId)) { + auto begin = std::remove_if(devices.begin(), devices.end(), [this](const std::string &device) { + return !IsSpecialChannel(device); + }); + devices.erase(begin, devices.end()); } - StoreMetaData storeMetaData = GetStoreMetaData(dataBase); - if ((dataBase.autoSyncType == AutoSyncType::SYNC_ON_CHANGE || - dataBase.autoSyncType == AutoSyncType::SYNC_ON_CHANGE_READY)) { - return DoAutoSync(DmAdapter::ToUUID(DmAdapter::GetInstance().GetRemoteDevices()), storeMetaData, tableNames); + + if (devices.empty()) { + return; } - return RDB_OK; + + auto tables = RdbTypesUtils::GetP2PTables(changedData); + DoAutoSync(devices, metaData, tables); +} + +void RdbServiceImpl::OnSearchableChange(const StoreMetaData &metaData, const RdbNotifyConfig &config, + const RdbChangedData &changedData) +{ + auto changedTables = RdbTypesUtils::GetSearchableTables(changedData); + DataChangeEvent::EventInfo eventInfo(changedTables); + eventInfo.isFull = config.isFull_; + StoreInfo storeInfo = GetStoreInfoEx(metaData); + auto pid = IPCSkeleton::GetCallingPid(); + if (executors_ == nullptr || config.delay_ == 0) { + RemoveHeartbeatTask(pid, storeInfo.path); + auto evt = std::make_unique(std::move(storeInfo), std::move(eventInfo)); + EventCenter::GetInstance().PostEvent(std::move(evt)); + return; + } + PostHeartbeatTask(pid, config.delay_, storeInfo, eventInfo); } int32_t RdbServiceImpl::NotifyDataChange(const RdbSyncerParam ¶m, const RdbChangedData &rdbChangedData, @@ -1510,68 +1523,68 @@ int32_t RdbServiceImpl::NotifyDataChange(const RdbSyncerParam ¶m, const RdbC Anonymous::Change(param.storeName_).c_str()); return RDB_ERROR; } - StoreInfo storeInfo; - storeInfo.tokenId = IPCSkeleton::GetCallingTokenID(); - storeInfo.bundleName = param.bundleName_; - storeInfo.storeName = RemoveSuffix(param.storeName_); - storeInfo.path = GetPath(param); - auto [instanceId, user] = GetInstIndexAndUser(storeInfo.tokenId, param.bundleName_); - storeInfo.instanceId = instanceId; - storeInfo.user = user; - storeInfo.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; - DataChangeEvent::EventInfo eventInfo; - eventInfo.isFull = rdbNotifyConfig.isFull_; - if (DoDataChangeSync(storeInfo, rdbChangedData) != RDB_OK) { - ZLOGE("store datachange sync fail, storeId:%{public}s", Anonymous::Change(storeInfo.storeName).c_str()); - } - for (const auto &[key, value] : rdbChangedData.tableData) { - if (value.isTrackedDataChange) { - DataChangeEvent::TableChangeProperties tableChangeProperties = { value.isTrackedDataChange }; - eventInfo.tableProperties.insert_or_assign(key, std::move(tableChangeProperties)); - } - } - if (IsPostImmediately(IPCSkeleton::GetCallingPid(), rdbNotifyConfig, storeInfo, eventInfo, storeInfo.path)) { - auto evt = std::make_unique(std::move(storeInfo), std::move(eventInfo)); - EventCenter::GetInstance().PostEvent(std::move(evt)); + + auto [exists, meta] = LoadStoreMetaData(param); + if (!exists || meta.instanceId != 0) { + ZLOGW("bundleName:%{public}s, storeName:%{public}s instance:%{public}d. No store meta", + meta.bundleName.c_str(), Anonymous::Change(meta.storeId).c_str(), meta.instanceId); + return RDB_ERROR; } + + OnCollaborationChange(meta, rdbChangedData); + + OnSearchableChange(meta, rdbNotifyConfig, rdbChangedData); return RDB_OK; } -bool RdbServiceImpl::IsPostImmediately(const int32_t callingPid, const RdbNotifyConfig &rdbNotifyConfig, - StoreInfo &storeInfo, DataChangeEvent::EventInfo &eventInfo, const std::string &path) +void RdbServiceImpl::PostHeartbeatTask(int32_t pid, uint32_t delay, StoreInfo &storeInfo, + DataChangeEvent::EventInfo &eventInfo) { - bool postImmediately = false; - heartbeatTaskIds_.Compute(callingPid, [this, &postImmediately, &rdbNotifyConfig, &storeInfo, &eventInfo, - &path](const int32_t &key, std::map &tasks) { - auto iter = tasks.find(path); + heartbeatTaskIds_.Compute(pid, [this, delay, &storeInfo, &eventInfo] + (const int32_t &key, std::map &tasks) { + auto iter = tasks.find(storeInfo.path); ExecutorPool::TaskId taskId = ExecutorPool::INVALID_TASK_ID; if (iter != tasks.end()) { taskId = iter->second; } - if (rdbNotifyConfig.delay_ == 0) { - if (taskId != ExecutorPool::INVALID_TASK_ID && executors_ != nullptr) { + if (delay == 0) { + if (taskId != ExecutorPool::INVALID_TASK_ID) { executors_->Remove(taskId); } - postImmediately = true; - tasks.erase(path); + tasks.erase(storeInfo.path); return !tasks.empty(); } - if (executors_ != nullptr) { - auto task = [storeInfoInner = storeInfo, eventInfoInner = eventInfo]() { - auto evt = std::make_unique(std::move(storeInfoInner), std::move(eventInfoInner)); + if (taskId == ExecutorPool::INVALID_TASK_ID) { + auto task = [storeInfo, eventInfo]() mutable { + auto evt = std::make_unique(storeInfo, eventInfo); EventCenter::GetInstance().PostEvent(std::move(evt)); }; - if (taskId == ExecutorPool::INVALID_TASK_ID) { - taskId = executors_->Schedule(std::chrono::milliseconds(rdbNotifyConfig.delay_), task); - } else { - taskId = executors_->Reset(taskId, std::chrono::milliseconds(rdbNotifyConfig.delay_)); - } + taskId = executors_->Schedule(std::chrono::milliseconds(delay), task); + } else { + taskId = executors_->Reset(taskId, std::chrono::milliseconds(delay)); } - tasks.insert_or_assign(path, taskId); + tasks.insert_or_assign(storeInfo.path, taskId); return true; }); - return postImmediately; +} + +void RdbServiceImpl::RemoveHeartbeatTask(int32_t pid, const std::string &path) +{ + heartbeatTaskIds_.Compute(pid, + [this, &path](const int32_t &key, std::map &tasks) { + auto iter = tasks.find(path); + if (iter == tasks.end()) { + return !tasks.empty(); + } + + if (iter->second != ExecutorPool::INVALID_TASK_ID && executors_ != nullptr) { + executors_->Remove(iter->second); + } + + tasks.erase(path); + return !tasks.empty(); + }); } int32_t RdbServiceImpl::SetSearchable(const RdbSyncerParam ¶m, bool isSearchable) @@ -1582,24 +1595,22 @@ int32_t RdbServiceImpl::SetSearchable(const RdbSyncerParam ¶m, bool isSearch Anonymous::Change(param.storeName_).c_str()); return RDB_ERROR; } - SetSearchableEvent::EventInfo eventInfo; + auto [exists, meta] = LoadStoreMetaData(param); + if (!exists) { + ZLOGW("bundleName:%{public}s, storeName:%{public}s. no meta", param.bundleName_.c_str(), + Anonymous::Change(param.storeName_).c_str()); + return RDB_NO_META; + } + + SetSearchableEvent::EventInfo eventInfo {}; eventInfo.isSearchable = isSearchable; - return PostSearchEvent(CloudEvent::SET_SEARCHABLE, param, eventInfo); + return PostSearchEvent(CloudEvent::SET_SEARCHABLE, meta, eventInfo); } -int32_t RdbServiceImpl::PostSearchEvent(int32_t evtId, const RdbSyncerParam& param, +int32_t RdbServiceImpl::PostSearchEvent(int32_t evtId, const StoreMetaData &meta, SetSearchableEvent::EventInfo &eventInfo) { - StoreInfo storeInfo; - storeInfo.tokenId = IPCSkeleton::GetCallingTokenID(); - storeInfo.bundleName = param.bundleName_; - storeInfo.storeName = RemoveSuffix(param.storeName_); - auto [instanceId, user]= GetInstIndexAndUser(storeInfo.tokenId, param.bundleName_); - storeInfo.instanceId = instanceId; - storeInfo.user = user; - storeInfo.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; - storeInfo.path = GetPath(param); - + StoreInfo storeInfo = GetStoreInfoEx(meta); auto evt = std::make_unique(std::move(storeInfo), std::move(eventInfo), evtId); EventCenter::GetInstance().PostEvent(std::move(evt)); return RDB_OK; @@ -1609,7 +1620,7 @@ int32_t RdbServiceImpl::Disable(const RdbSyncerParam ¶m) { auto tokenId = IPCSkeleton::GetCallingTokenID(); auto storeId = RemoveSuffix(param.storeName_); - AutoCache::GetInstance().Disable(tokenId, GetPath(param), storeId); + AutoCache::GetInstance().Disable(tokenId, GetStoreMetaData(param).dataDir, storeId); return RDB_OK; } @@ -1617,7 +1628,7 @@ int32_t RdbServiceImpl::Enable(const RdbSyncerParam ¶m) { auto tokenId = IPCSkeleton::GetCallingTokenID(); auto storeId = RemoveSuffix(param.storeName_); - AutoCache::GetInstance().Enable(tokenId, GetPath(param), storeId); + AutoCache::GetInstance().Enable(tokenId, GetStoreMetaData(param).dataDir, storeId); return RDB_OK; } @@ -1665,15 +1676,16 @@ int32_t RdbServiceImpl::GetPassword(const RdbSyncerParam ¶m, std::vector 0 ? RDB_OK : RDB_ERROR; } -StoreInfo RdbServiceImpl::GetStoreInfo(const RdbSyncerParam ¶m) +StoreInfo RdbServiceImpl::GetStoreInfoEx(const StoreMetaData &metaData) { StoreInfo storeInfo; - storeInfo.bundleName = param.bundleName_; - storeInfo.tokenId = IPCSkeleton::GetCallingTokenID(); - storeInfo.user = AccountDelegate::GetInstance()->GetUserByToken(storeInfo.tokenId); - storeInfo.storeName = RemoveSuffix(param.storeName_); - auto meta = GetStoreMetaData(param); - storeInfo.path = meta.dataDir; + storeInfo.tokenId = metaData.tokenId; + storeInfo.bundleName = metaData.bundleName; + storeInfo.storeName = metaData.storeId; + storeInfo.instanceId = metaData.instanceId; + storeInfo.user = atoi(metaData.user.c_str()); + storeInfo.deviceId = metaData.deviceId; + storeInfo.path = metaData.dataDir; return storeInfo; } @@ -1688,7 +1700,7 @@ std::pair RdbServiceImpl::LockCloudContainer(const RdbSyncerP ZLOGI("start to lock cloud db: bundleName:%{public}s, storeName:%{public}s", param.bundleName_.c_str(), Anonymous::Change(param.storeName_).c_str()); - auto storeInfo = GetStoreInfo(param); + auto storeInfo = GetStoreInfoEx(GetStoreMetaData(param)); CloudLockEvent::Callback callback = [&result](int32_t status, uint32_t expiredTime) { result.first = status; @@ -1710,7 +1722,7 @@ int32_t RdbServiceImpl::UnlockCloudContainer(const RdbSyncerParam ¶m) ZLOGI("start to unlock cloud db: bundleName:%{public}s, storeName:%{public}s", param.bundleName_.c_str(), Anonymous::Change(param.storeName_).c_str()); - auto storeInfo = GetStoreInfo(param); + auto storeInfo = GetStoreInfoEx(GetStoreMetaData(param)); CloudLockEvent::Callback callback = [&result](int32_t status, uint32_t expiredTime) { (void)expiredTime; @@ -1728,16 +1740,15 @@ int32_t RdbServiceImpl::GetDebugInfo(const RdbSyncerParam ¶m, std::map= StoreMetaData::StoreType::STORE_RELATIONAL_BEGIN && oldMeta.storeType <= StoreMetaData::StoreType::STORE_RELATIONAL_END && MetaDataManager::GetInstance().LoadMeta(meta.GetKeyWithoutPath(), syncMeta)) { - auto store = GetStore(param); + auto store = GetStore(meta); if (store == nullptr) { - ZLOGE("store is null, bundleName:%{public}s storeName:%{public}s", param.bundleName_.c_str(), - Anonymous::Change(param.storeName_).c_str()); + ZLOGE("store is null, bundleName:%{public}s storeName:%{public}s", meta.bundleName.c_str(), + Anonymous::Change(meta.storeId).c_str()); return false; } auto errCode = store->UpdateDBStatus(); @@ -1947,8 +1957,7 @@ void RdbServiceImpl::RegisterEvent() return; } auto predicate = evt.GetPredicates(); - auto rdbQuery = std::make_shared(); - rdbQuery->MakeQuery(*predicate); + auto rdbQuery = std::make_shared(*predicate); rdbQuery->SetColumns(evt.GetColumns()); callback(rdbQuery); }); @@ -1959,28 +1968,4 @@ void RdbServiceImpl::RegisterEvent() EventCenter::GetInstance().Subscribe(BindEvent::COMPENSATE_SYNC, compensateSyncProcess); EventCenter::GetInstance().Subscribe(BindEvent::RECOVER_SYNC, compensateSyncProcess); } - -std::string RdbServiceImpl::GetPath(const RdbSyncerParam ¶m) -{ - StoreMetaData metaData; - metaData.uid = IPCSkeleton::GetCallingUid(); - metaData.tokenId = IPCSkeleton::GetCallingTokenID(); - auto [instanceId, user] = GetInstIndexAndUser(metaData.tokenId, param.bundleName_); - metaData.instanceId = instanceId; - metaData.bundleName = param.bundleName_; - metaData.storeId = RemoveSuffix(param.storeName_); - if (AccessTokenKit::GetTokenTypeFlag(metaData.tokenId) != TOKEN_HAP && param.subUser_ != 0) { - metaData.user = std::to_string(param.subUser_); - } else { - metaData.user = std::to_string(user); - } - metaData.storeType = param.type_; - metaData.securityLevel = param.level_; - metaData.area = param.area_; - metaData.appType = "harmony"; - metaData.hapName = param.hapName_; - metaData.customDir = param.customDir_; - return DirectoryManager::GetInstance().GetStorePath(metaData) + "/" + param.storeName_; -} - } // namespace OHOS::DistributedRdb \ No newline at end of file diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.h b/services/distributeddataservice/service/rdb/rdb_service_impl.h index ea3b9aa74..bfb2ffbb2 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.h +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.h @@ -27,6 +27,7 @@ #include "concurrent_map.h" #include "crypto/crypto_manager.h" #include "feature/static_acts.h" +#include "lru_bucket.h" #include "metadata/secret_key_meta_data.h" #include "metadata/store_meta_data.h" #include "process_communicator_impl.h" @@ -168,6 +169,7 @@ private: static constexpr inline uint32_t WAIT_TIME = 30 * 1000; static constexpr inline uint32_t SHARE_WAIT_TIME = 60; // seconds + static constexpr inline uint32_t SAVE_CHANNEL_INTERVAL = 5; // minutes void RegisterRdbServiceInfo(); @@ -177,45 +179,51 @@ private: void DumpRdbServiceInfo(int fd, std::map> ¶ms); - void DoCloudSync(const RdbSyncerParam ¶m, const Option &option, const PredicatesMemo &predicates, + void DoCloudSync(const StoreMetaData &metaData, const Option &option, const PredicatesMemo &predicates, const AsyncDetail &async); void DoCompensateSync(const DistributedData::BindEvent& event); - - void SaveAutoSyncDeviceId(const StoreMetaData &meta, const std::vector &devices); - int DoSync(const RdbSyncerParam ¶m, const Option &option, const PredicatesMemo &predicates, + int DoSync(const StoreMetaData &meta, const Option &option, const PredicatesMemo &predicates, const AsyncDetail &async); - int DoAutoSync(const std::vector &devices, const StoreMetaData &storeMetaData, + int DoAutoSync(const std::vector &devices, const StoreMetaData &metaData, const std::vector &tables); std::vector GetReuseDevice(const std::vector &devices, const StoreMetaData &metaData); - int DoOnlineSync(const std::string &device, const Database &dataBase); - int DoDataChangeSync(const StoreInfo &storeInfo, const RdbChangedData &rdbChangedData); + void OnCollaborationChange(const StoreMetaData &metaData, const RdbChangedData &changedData); + + void OnSearchableChange(const StoreMetaData &metaData, const RdbNotifyConfig &config, + const RdbChangedData &changedData); Watchers GetWatchers(uint32_t tokenId, const std::string &storeName); DetailAsync GetCallbacks(uint32_t tokenId, const std::string &storeName); - std::shared_ptr GetStore(const RdbSyncerParam& param); - std::shared_ptr GetStore(const StoreMetaData &storeMetaData); void OnAsyncComplete(uint32_t tokenId, pid_t pid, uint32_t seqNum, Details &&result); - int32_t Upgrade(const RdbSyncerParam ¶m, const StoreMetaData &old); + int32_t Upgrade(const StoreMetaData &metaData, const StoreMetaData &old); + + void GetCloudSchema(const StoreMetaData &metaData); - void GetSchema(const RdbSyncerParam ¶m); + void PostHeartbeatTask(int32_t pid, uint32_t delay, StoreInfo &storeInfo, + DistributedData::DataChangeEvent::EventInfo &eventInfo); - bool IsPostImmediately(const int32_t callingPid, const RdbNotifyConfig &rdbNotifyConfig, StoreInfo &storeInfo, - DistributedData::DataChangeEvent::EventInfo &eventInfo, const std::string &storeName); + void RemoveHeartbeatTask(int32_t pid, const std::string &path); - bool TryUpdateDeviceId(const RdbSyncerParam ¶m, const StoreMetaData &oldMeta, StoreMetaData &meta); + bool TryUpdateDeviceId(const StoreMetaData &oldMeta, StoreMetaData &meta); void SaveLaunchInfo(StoreMetaData &meta); + void SaveAutoSyncInfo(const StoreMetaData &meta, const std::vector &devices); + + void DoChannelsMemento(bool immediately = false); + + bool IsSpecialChannel(const std::string &device); + static bool IsValidAccess(const std::string& bundleName, const std::string& storeName); static bool IsValidPath(const std::string& param); @@ -228,9 +236,9 @@ private: static std::pair LoadStoreMetaData(const RdbSyncerParam ¶m); - static std::string GetPath(const RdbSyncerParam ¶m); + static void SaveSyncMeta(const StoreMetaData &meta); - static StoreMetaData GetStoreMetaData(const Database &dataBase); + static std::pair LoadSyncMeta(const Database &database); static std::pair> AllocResource( StoreInfo& storeInfo, std::shared_ptr rdbQuery); @@ -243,9 +251,7 @@ private: static std::pair GetInstIndexAndUser(uint32_t tokenId, const std::string &bundleName); - static std::string GetSubUser(const int32_t subUser); - - static bool SaveAppIDMeta(const StoreMetaData &meta, const StoreMetaData &old); + static std::string GetSubUser(int32_t subUser); static void SetReturnParam(const StoreMetaData &metadata, RdbSyncerParam ¶m); @@ -253,7 +259,7 @@ private: static SyncResult ProcessResult(const std::map &results); - static StoreInfo GetStoreInfo(const RdbSyncerParam ¶m); + static StoreInfo GetStoreInfoEx(const StoreMetaData &metaData); static int32_t SaveDebugInfo(const StoreMetaData &metaData, const RdbSyncerParam ¶m); @@ -261,10 +267,12 @@ private: static int32_t SavePromiseInfo(const StoreMetaData &metaData, const RdbSyncerParam ¶m); - static int32_t PostSearchEvent(int32_t evtId, const RdbSyncerParam& param, + static bool SaveAppIDMeta(const StoreMetaData &meta, const StoreMetaData &old); + + static int32_t PostSearchEvent(int32_t evtId, const StoreMetaData ¶m, DistributedData::SetSearchableEvent::EventInfo &eventInfo); - static void UpdateMeta(const StoreMetaData &meta, const StoreMetaData &localMeta, AutoCache::Store store); + static bool IsCollaboration(const StoreMetaData &metaData); std::vector LoadSecretKey(const StoreMetaData &metaData, CryptoManager::SecretKeyType secretKeyType); @@ -274,6 +282,9 @@ private: ConcurrentMap syncAgents_; std::shared_ptr executors_; ConcurrentMap> heartbeatTaskIds_; + + LRUBucket specialChannels_ { 10 }; + ExecutorPool::TaskId saveChannelsTask_ = ExecutorPool::INVALID_TASK_ID; }; } // namespace OHOS::DistributedRdb #endif \ No newline at end of file diff --git a/services/distributeddataservice/service/rdb/rdb_types_utils.cpp b/services/distributeddataservice/service/rdb/rdb_types_utils.cpp new file mode 100644 index 000000000..b81475f7f --- /dev/null +++ b/services/distributeddataservice/service/rdb/rdb_types_utils.cpp @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "rdb_types_utils.h" +namespace OHOS::DistributedRdb { +std::vector RdbTypesUtils::GetSearchableTables(const RdbChangedData &changedData) +{ + std::vector tables; + for (auto &[key, value] : changedData.tableData) { + if (value.isTrackedDataChange) { + tables.push_back(key); + } + } + return tables; +} + +std::vector RdbTypesUtils::GetP2PTables(const RdbChangedData &changedData) +{ + std::vector tables; + for (auto &[key, value] : changedData.tableData) { + if (value.isP2pSyncDataChange) { + tables.push_back(key); + } + } + return tables; +} +std::vector RdbTypesUtils::Convert(const std::vector &references) +{ + std::vector relationships; + for (const auto &reference : references) { + DistributedData::Reference relationship = { reference.sourceTable, reference.targetTable, reference.refFields }; + relationships.emplace_back(relationship); + } + return relationships; +} +} // namespace OHOS::DistributedRdb \ No newline at end of file diff --git a/services/distributeddataservice/service/rdb/rdb_types_utils.h b/services/distributeddataservice/service/rdb/rdb_types_utils.h new file mode 100644 index 000000000..95b3e8de6 --- /dev/null +++ b/services/distributeddataservice/service/rdb/rdb_types_utils.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DISTRIBUTED_DATA_DATAMGR_SERVICE_RDB_RDB_TYPE_UTILS_H +#define OHOS_DISTRIBUTED_DATA_DATAMGR_SERVICE_RDB_RDB_TYPE_UTILS_H +#include +#include + +#include "rdb_types.h" +#include "store/general_value.h" +namespace OHOS::DistributedRdb { +class RdbTypesUtils final { +public: + static std::vector GetSearchableTables(const RdbChangedData &changedData); + static std::vector GetP2PTables(const RdbChangedData &changedData); + static std::vector Convert(const std::vector &references); +}; +} // namespace OHOS::DistributedRdb +#endif // OHOS_DISTRIBUTED_DATA_DATAMGR_SERVICE_RDB_RDB_TYPE_UTILS_H diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 810c25bb8..38066f799 100644 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -29,8 +29,6 @@ config("module_private_config") { "${data_service_path}/service/cloud/", "${data_service_path}/service/config/include/", "${data_service_path}/service/common/", - "${data_service_path}/service/crypto/include", - "${data_service_path}/service/directory/include/", "${data_service_path}/service/data_share/common", "${data_service_path}/service/data_share/data", "${data_service_path}/service/data_share/dfx", @@ -473,8 +471,6 @@ ohos_unittest("KVDBGeneralStoreAbnormalTest") { "${data_service_path}/service/backup/include/", "${data_service_path}/service/cloud/", "${data_service_path}/service/config/include/", - "${data_service_path}/service/crypto/include", - "${data_service_path}/service/directory/include/", "${data_service_path}/service/data_share/common", "${data_service_path}/service/data_share/data", "${data_service_path}/service/data_share/strategies", @@ -662,7 +658,7 @@ ohos_unittest("RdbServiceImplTest") { include_dirs = [ "${data_service_path}/adapter/include/communicator", - "${data_service_path}/framework/include/eventcenter", + "${data_service_path}/framework/include", "${data_service_path}/service/test/mock", ] @@ -732,7 +728,6 @@ ohos_unittest("RdbServiceImplTokenTest") { include_dirs = [ "${data_service_path}/adapter/include/communicator", - "${data_service_path}/framework/include/eventcenter", "${data_service_path}/service/test/mock", ] @@ -1127,7 +1122,7 @@ ohos_unittest("UdmfRunTimeStoreTest") { "${data_service_path}/service/udmf", "${data_service_path}/service/udmf/store", "${data_service_path}/service/udmf/preprocess", - "${data_service_path}/framework/include/directory", + "${data_service_path}/framework/include", ] configs = [ ":module_private_config" ] @@ -1187,7 +1182,6 @@ ohos_unittest("DataShareServiceImplTest") { include_dirs = [ "${data_service_path}/service/config/include", - "${data_service_path}/framework/include/metadata", "${data_service_path}/service/data_share/common", ] @@ -1464,8 +1458,6 @@ ohos_unittest("KvdbServicePasswordTest") { "${data_service_path}/service/kvdb", "${data_service_path}/adapter/include/account", "${data_service_path}/framework/include", - "${data_service_path}/framework/include/cloud", - "${data_service_path}/framework/include/eventcenter", "${data_service_path}/service/test/mock", "${data_service_path}/adapter/include/communicator", ] @@ -1531,8 +1523,6 @@ ohos_unittest("KvdbServiceImplTest") { "${data_service_path}/service/kvdb", "${data_service_path}/adapter/include/account", "${data_service_path}/framework/include", - "${data_service_path}/framework/include/cloud", - "${data_service_path}/framework/include/eventcenter", "${data_service_path}/service/test/mock", "${data_service_path}/adapter/include/communicator", ] @@ -1625,7 +1615,6 @@ ohos_unittest("UdmfServiceImplTest") { "${data_service_path}/adapter/include/account", "${data_service_path}/adapter/include/communicator", "${data_service_path}/app/src", - "${data_service_path}/framework/include/account", "${data_service_path}/service/kvdb", "${data_service_path}/service/matrix/include", "${data_service_path}/service/udmf", @@ -1822,10 +1811,8 @@ ohos_unittest("UdmfServiceStubMockTest") { "${data_service_path}/framework/include", "${data_service_path}/service/test/mock", "${data_service_path}/service/udmf/permission", - "${data_service_path}/framework/include/dfx", "${data_service_path}/service/udmf/preprocess", "${data_service_path}/adapter/include/communicator", - "${data_service_path}/framework/include/account", "${data_service_path}/service/udmf/store", ] @@ -1914,7 +1901,7 @@ ohos_unittest("UdmfPreProcessUtilsMockTest") { "${data_service_path}/service/udmf/preprocess", "${data_service_path}/service/test/mock", "${data_service_path}/service/udmf/store", - "${data_service_path}/framework/include/account", + "${data_service_path}/framework/include", "${data_service_path}/adapter/include/communicator", ] diff --git a/services/distributeddataservice/service/test/cloud_data_mock_test.cpp b/services/distributeddataservice/service/test/cloud_data_mock_test.cpp index 5f7e68b9d..b9796b470 100644 --- a/services/distributeddataservice/service/test/cloud_data_mock_test.cpp +++ b/services/distributeddataservice/service/test/cloud_data_mock_test.cpp @@ -60,6 +60,16 @@ public: static std::shared_ptr cloudServiceImpl_; protected: + class CloudServerMock : public CloudServer { + public: + std::pair GetServerInfo(int32_t userId, bool needSpaceInfo) override; + std::pair GetAppSchema(int32_t userId, const std::string &bundleName) override; + virtual ~CloudServerMock() = default; + static constexpr uint64_t REMAINSPACE = 1000; + static constexpr uint64_t TATALSPACE = 2000; + static constexpr int32_t INVALID_USER_ID = -1; + }; + static void InitMetaData(); static void InitSchemaMeta(); static void InitCloudInfo(); @@ -70,17 +80,8 @@ protected: static inline AccountDelegateMock *accountDelegateMock = nullptr; }; -class CloudServerMock : public CloudServer { -public: - std::pair GetServerInfo(int32_t userId, bool needSpaceInfo) override; - std::pair GetAppSchema(int32_t userId, const std::string &bundleName) override; - virtual ~CloudServerMock() = default; - static constexpr uint64_t REMAINSPACE = 1000; - static constexpr uint64_t TATALSPACE = 2000; - static constexpr int32_t INVALID_USER_ID = -1; -}; -std::pair CloudServerMock::GetServerInfo(int32_t userId, bool needSpaceInfo) +std::pair CloudDataMockTest::CloudServerMock::GetServerInfo(int32_t userId, bool needSpaceInfo) { CloudInfo cloudInfo; cloudInfo.user = userId; @@ -99,7 +100,8 @@ std::pair CloudServerMock::GetServerInfo(int32_t userId, boo return { E_OK, cloudInfo }; } -std::pair CloudServerMock::GetAppSchema(int32_t userId, const std::string &bundleName) +std::pair CloudDataMockTest::CloudServerMock::GetAppSchema(int32_t userId, + const std::string &bundleName) { if (userId == INVALID_USER_ID) { return { E_ERROR, CloudDataMockTest::schemaMeta_ }; diff --git a/services/distributeddataservice/service/test/cloud_data_test.cpp b/services/distributeddataservice/service/test/cloud_data_test.cpp index 7e2995508..2f277052e 100644 --- a/services/distributeddataservice/service/test/cloud_data_test.cpp +++ b/services/distributeddataservice/service/test/cloud_data_test.cpp @@ -20,15 +20,13 @@ #include "account/account_delegate.h" #include "bootstrap.h" #include "checker_mock.h" -#include "cloud/cloud_mark.h" #include "cloud/change_event.h" -#include "cloud/cloud_event.h" #include "cloud/cloud_last_sync_info.h" +#include "cloud/cloud_mark.h" #include "cloud/cloud_report.h" #include "cloud/cloud_server.h" #include "cloud/cloud_share_event.h" #include "cloud/make_query_event.h" -#include "cloud/schema_meta.h" #include "cloud_data_translate.h" #include "cloud_service_impl.h" #include "cloud_types.h" @@ -37,23 +35,18 @@ #include "communicator/device_manager_adapter.h" #include "device_matrix.h" #include "eventcenter/event_center.h" -#include "feature/feature_system.h" #include "ipc_skeleton.h" #include "log_print.h" #include "metadata/meta_data_manager.h" -#include "metadata/store_meta_data.h" -#include "metadata/store_meta_data_local.h" #include "mock/db_store_mock.h" #include "mock/general_store_mock.h" #include "network/network_delegate.h" #include "network_delegate_mock.h" +#include "rdb_general_store.h" #include "rdb_query.h" #include "rdb_service.h" #include "rdb_service_impl.h" #include "rdb_types.h" -#include "store/auto_cache.h" -#include "store/general_value.h" -#include "store/store_info.h" #include "sync_manager.h" #include "token_setproc.h" @@ -62,7 +55,6 @@ using namespace OHOS::DistributedData; using namespace OHOS::Security::AccessToken; using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; using Querykey = OHOS::CloudData::QueryKey; -using QueryLastResults = OHOS::CloudData::QueryLastResults; using CloudSyncInfo = OHOS::CloudData::CloudSyncInfo; using SharingCfm = OHOS::CloudData::SharingUtil::SharingCfm; using Confirmation = OHOS::CloudData::Confirmation; @@ -70,6 +62,7 @@ using CenterCode = OHOS::DistributedData::SharingCenter::SharingCode; using Status = OHOS::CloudData::CloudService::Status; using CloudSyncScene = OHOS::CloudData::CloudServiceImpl::CloudSyncScene; using GenErr = OHOS::DistributedData::GeneralError; +using RdbGeneralStore = OHOS::DistributedRdb::RdbGeneralStore; uint64_t g_selfTokenID = 0; void AllocHapToken(const HapPolicyParams &policy) @@ -140,6 +133,16 @@ public: static std::shared_ptr cloudServiceImpl_; protected: + class CloudServerMock : public CloudServer { + public: + std::pair GetServerInfo(int32_t userId, bool needSpaceInfo) override; + std::pair GetAppSchema(int32_t userId, const std::string &bundle) override; + virtual ~CloudServerMock() = default; + static constexpr uint64_t REMAINSPACE = 1000; + static constexpr uint64_t TATALSPACE = 2000; + static constexpr int32_t INVALID_USER_ID = -1; + }; + static void InitMetaData(); static void InitSchemaMeta(); static void InitCloudInfo(); @@ -148,19 +151,10 @@ protected: static CloudInfo cloudInfo_; static DistributedData::CheckerMock checker_; static NetworkDelegateMock delegate_; + static int32_t dbStatus_; }; -class CloudServerMock : public CloudServer { -public: - std::pair GetServerInfo(int32_t userId, bool needSpaceInfo) override; - std::pair GetAppSchema(int32_t userId, const std::string &bundleName) override; - virtual ~CloudServerMock() = default; - static constexpr uint64_t REMAINSPACE = 1000; - static constexpr uint64_t TATALSPACE = 2000; - static constexpr int32_t INVALID_USER_ID = -1; -}; - -std::pair CloudServerMock::GetServerInfo(int32_t userId, bool needSpaceInfo) +std::pair CloudDataTest::CloudServerMock::GetServerInfo(int32_t userId, bool needSpaceInfo) { CloudInfo cloudInfo; cloudInfo.user = userId; @@ -179,13 +173,13 @@ std::pair CloudServerMock::GetServerInfo(int32_t userId, boo return { E_OK, cloudInfo }; } -std::pair CloudServerMock::GetAppSchema(int32_t userId, const std::string &bundleName) +std::pair CloudDataTest::CloudServerMock::GetAppSchema(int32_t userId, const std::string &bundle) { if (userId == INVALID_USER_ID) { return { E_ERROR, CloudDataTest::schemaMeta_ }; } - if (bundleName.empty()) { + if (bundle.empty()) { SchemaMeta schemaMeta; return { E_OK, schemaMeta }; } @@ -200,7 +194,7 @@ std::shared_ptr CloudDataTest::cloudServiceImpl_ = std::make_shared(); DistributedData::CheckerMock CloudDataTest::checker_; NetworkDelegateMock CloudDataTest::delegate_; - +int32_t CloudDataTest::dbStatus_ = E_OK; void CloudDataTest::InitMetaData() { metaData_.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; @@ -296,11 +290,32 @@ void CloudDataTest::SetUpTestCase(void) InitCloudInfo(); InitMetaData(); InitSchemaMeta(); + // Construct the statisticInfo data + AutoCache::GetInstance().RegCreator(DistributedRdb::RDB_DEVICE_COLLABORATION, + [](const StoreMetaData &metaData) -> GeneralStore* { + auto store = new (std::nothrow) GeneralStoreMock(); + if (store != nullptr) { + std::map entry = { { "inserted", 1 }, { "updated", 2 }, { "normal", 3 } }; + store->SetMockCursor(entry); + store->SetEqualIdentifier("", ""); + store->SetMockDBStatus(dbStatus_); + } + return store; + }); } void CloudDataTest::TearDownTestCase() { SetSelfTokenID(g_selfTokenID); + AutoCache::GetInstance().RegCreator(DistributedRdb::RDB_DEVICE_COLLABORATION, + [](const StoreMetaData &metaData) -> GeneralStore* { + auto store = new (std::nothrow) RdbGeneralStore(metaData); + if (store != nullptr && !store->IsValid()) { + delete store; + store = nullptr; + } + return store; + }); } void CloudDataTest::SetUp() @@ -394,18 +409,6 @@ HWTEST_F(CloudDataTest, QueryStatistics002, TestSize.Level0) */ HWTEST_F(CloudDataTest, QueryStatistics003, TestSize.Level1) { - // Construct the statisticInfo data - auto creator = [](const StoreMetaData &metaData) -> GeneralStore* { - auto store = new (std::nothrow) GeneralStoreMock(); - if (store != nullptr) { - std::map entry = { { "inserted", 1 }, { "updated", 2 }, { "normal", 3 } }; - store->MakeCursor(entry); - store->SetEqualIdentifier("", ""); - } - return store; - }; - AutoCache::GetInstance().RegCreator(DistributedRdb::RDB_DEVICE_COLLABORATION, creator); - auto [status, result] = cloudServiceImpl_->QueryStatistics(TEST_CLOUD_ID, TEST_CLOUD_BUNDLE, TEST_CLOUD_DATABASE_ALIAS_1); ASSERT_EQ(status, CloudData::CloudService::SUCCESS); @@ -430,17 +433,6 @@ HWTEST_F(CloudDataTest, QueryStatistics003, TestSize.Level1) */ HWTEST_F(CloudDataTest, QueryStatistics004, TestSize.Level1) { - // Construct the statisticInfo data - auto creator = [](const StoreMetaData &metaData) -> GeneralStore* { - auto store = new (std::nothrow) GeneralStoreMock(); - if (store != nullptr) { - std::map entry = { { "inserted", 1 }, { "updated", 2 }, { "normal", 3 } }; - store->MakeCursor(entry); - } - return store; - }; - AutoCache::GetInstance().RegCreator(DistributedRdb::RDB_DEVICE_COLLABORATION, creator); - auto [status, result] = cloudServiceImpl_->QueryStatistics(TEST_CLOUD_ID, TEST_CLOUD_BUNDLE, ""); ASSERT_EQ(status, CloudData::CloudService::SUCCESS); ASSERT_EQ(result.size(), 2); @@ -1012,8 +1004,7 @@ HWTEST_F(CloudDataTest, AllocResourceAndShare001, TestSize.Level0) return; } auto predicate = evt.GetPredicates(); - auto rdbQuery = std::make_shared(); - rdbQuery->MakeQuery(*predicate); + auto rdbQuery = std::make_shared(*predicate); rdbQuery->SetColumns(evt.GetColumns()); callback(rdbQuery); }); @@ -2335,13 +2326,13 @@ HWTEST_F(CloudDataTest, QueryTableStatistic, TestSize.Level0) auto store = std::make_shared(); if (store != nullptr) { std::map entry = { { "inserted", "TEST" }, { "updated", "TEST" }, { "normal", "TEST" } }; - store->MakeCursor(entry); + store->SetMockCursor(entry); } auto [ret, result] = cloudServiceImpl_->QueryTableStatistic("test", store); EXPECT_TRUE(ret); if (store != nullptr) { std::map entry = { { "Test", 1 } }; - store->MakeCursor(entry); + store->SetMockCursor(entry); } std::tie(ret, result) = cloudServiceImpl_->QueryTableStatistic("test", store); EXPECT_TRUE(ret); @@ -2679,7 +2670,8 @@ HWTEST_F(CloudDataTest, GetPriorityLevel001, TestSize.Level1) DistributedRdb::RdbService::Option option{ .mode = GeneralStore::SyncMode::CLOUD_CLOUD_FIRST, .isAsync = true }; DistributedRdb::PredicatesMemo memo; memo.tables_ = { TEST_CLOUD_TABLE }; - rdbServiceImpl.DoCloudSync(param, option, memo, nullptr); + auto metaData = DistributedRdb::RdbServiceImpl::GetStoreMetaData(param); + rdbServiceImpl.DoCloudSync(metaData, option, memo, nullptr); } /** @@ -2701,7 +2693,8 @@ HWTEST_F(CloudDataTest, GetPriorityLevel002, TestSize.Level1) DistributedRdb::RdbService::Option option{ .mode = GeneralStore::SyncMode::CLOUD_TIME_FIRST, .isAsync = true }; DistributedRdb::PredicatesMemo memo; memo.tables_ = { TEST_CLOUD_TABLE }; - rdbServiceImpl.DoCloudSync(param, option, memo, nullptr); + auto metaData = DistributedRdb::RdbServiceImpl::GetStoreMetaData(param); + rdbServiceImpl.DoCloudSync(metaData, option, memo, nullptr); } /** @@ -2722,7 +2715,8 @@ HWTEST_F(CloudDataTest, GetPriorityLevel003, TestSize.Level1) DistributedRdb::RdbSyncerParam param{ .bundleName_ = TEST_CLOUD_BUNDLE, .storeName_ = TEST_CLOUD_STORE }; DistributedRdb::RdbService::Option option{ .mode = GeneralStore::SyncMode::CLOUD_CLOUD_FIRST, .isAsync = true }; DistributedRdb::PredicatesMemo memo; - rdbServiceImpl.DoCloudSync(param, option, memo, nullptr); + auto metaData = DistributedRdb::RdbServiceImpl::GetStoreMetaData(param); + rdbServiceImpl.DoCloudSync(metaData, option, memo, nullptr); } /** @@ -2746,7 +2740,8 @@ HWTEST_F(CloudDataTest, GetPriorityLevel004, TestSize.Level1) .isAsync = true, .isAutoSync = true }; DistributedRdb::PredicatesMemo memo; - rdbServiceImpl.DoCloudSync(param, option, memo, nullptr); + auto metaData = DistributedRdb::RdbServiceImpl::GetStoreMetaData(param); + rdbServiceImpl.DoCloudSync(metaData, option, memo, nullptr); } /** @@ -2758,7 +2753,7 @@ HWTEST_F(CloudDataTest, GetPriorityLevel004, TestSize.Level1) HWTEST_F(CloudDataTest, UpdateSchemaFromHap001, TestSize.Level1) { ASSERT_NE(cloudServiceImpl_, nullptr); - CloudData::CloudServiceImpl::HapInfo info = { .instIndex = 0, .bundleName = TEST_CLOUD_BUNDLE, .user = -1 }; + CloudData::CloudServiceImpl::HapInfo info = { .user = -1, .instIndex = 0, .bundleName = TEST_CLOUD_BUNDLE }; auto ret = cloudServiceImpl_->UpdateSchemaFromHap(info); EXPECT_EQ(ret, Status::ERROR); } @@ -2772,7 +2767,7 @@ HWTEST_F(CloudDataTest, UpdateSchemaFromHap001, TestSize.Level1) HWTEST_F(CloudDataTest, UpdateSchemaFromHap002, TestSize.Level1) { ASSERT_NE(cloudServiceImpl_, nullptr); - CloudData::CloudServiceImpl::HapInfo info = { .instIndex = 0, .bundleName = "", .user = cloudInfo_.user }; + CloudData::CloudServiceImpl::HapInfo info = { .user = cloudInfo_.user, .instIndex = 0, .bundleName = "" }; auto ret = cloudServiceImpl_->UpdateSchemaFromHap(info); EXPECT_EQ(ret, Status::ERROR); } @@ -2787,7 +2782,7 @@ HWTEST_F(CloudDataTest, UpdateSchemaFromHap003, TestSize.Level1) { ASSERT_NE(cloudServiceImpl_, nullptr); CloudData::CloudServiceImpl::HapInfo info = { - .instIndex = 0, .bundleName = TEST_CLOUD_BUNDLE, .user = cloudInfo_.user + .user = cloudInfo_.user, .instIndex = 0, .bundleName = TEST_CLOUD_BUNDLE }; auto ret = cloudServiceImpl_->UpdateSchemaFromHap(info); EXPECT_EQ(ret, Status::SUCCESS); @@ -2817,7 +2812,7 @@ HWTEST_F(CloudDataTest, UpdateSchemaFromHap004, TestSize.Level1) cloudInfo.apps[COM_EXAMPLE_TEST_CLOUD] = std::move(exampleAppInfo); MetaDataManager::GetInstance().SaveMeta(cloudInfo_.GetKey(), cloudInfo, true); CloudData::CloudServiceImpl::HapInfo info = { - .instIndex = 0, .bundleName = COM_EXAMPLE_TEST_CLOUD, .user = cloudInfo_.user + .user = cloudInfo_.user, .instIndex = 0, .bundleName = COM_EXAMPLE_TEST_CLOUD }; auto ret = cloudServiceImpl_->UpdateSchemaFromHap(info); EXPECT_EQ(ret, Status::SUCCESS); @@ -2837,7 +2832,7 @@ HWTEST_F(CloudDataTest, UpdateClearWaterMark001, TestSize.Level0) { ASSERT_NE(cloudServiceImpl_, nullptr); CloudData::CloudServiceImpl::HapInfo hapInfo = { - .instIndex = 0, .bundleName = TEST_CLOUD_BUNDLE, .user = cloudInfo_.user + .user = cloudInfo_.user, .instIndex = 0, .bundleName = TEST_CLOUD_BUNDLE }; SchemaMeta::Database database; database.name = TEST_CLOUD_STORE; @@ -2873,7 +2868,7 @@ HWTEST_F(CloudDataTest, UpdateClearWaterMark002, TestSize.Level0) { ASSERT_NE(cloudServiceImpl_, nullptr); CloudData::CloudServiceImpl::HapInfo hapInfo = { - .instIndex = 0, .bundleName = TEST_CLOUD_BUNDLE, .user = cloudInfo_.user + .user = cloudInfo_.user, .instIndex = 0, .bundleName = TEST_CLOUD_BUNDLE }; SchemaMeta::Database database; database.name = TEST_CLOUD_STORE; @@ -2909,7 +2904,7 @@ HWTEST_F(CloudDataTest, UpdateClearWaterMark003, TestSize.Level0) { ASSERT_NE(cloudServiceImpl_, nullptr); CloudData::CloudServiceImpl::HapInfo hapInfo = { - .instIndex = 0, .bundleName = TEST_CLOUD_BUNDLE, .user = cloudInfo_.user + .user = cloudInfo_.user, .instIndex = 0, .bundleName = TEST_CLOUD_BUNDLE }; SchemaMeta::Database database; database.name = TEST_CLOUD_STORE; @@ -2966,7 +2961,6 @@ HWTEST_F(CloudDataTest, GetPrepareTraceId, TestSize.Level0) HWTEST_F(CloudDataTest, TryUpdateDeviceId001, TestSize.Level1) { DistributedRdb::RdbServiceImpl rdbServiceImpl; - DistributedRdb::RdbSyncerParam param{ .bundleName_ = TEST_CLOUD_BUNDLE, .storeName_ = TEST_CLOUD_STORE }; StoreMetaData oldMeta; oldMeta.deviceId = "oldUuidtest"; oldMeta.user = "100"; @@ -2977,7 +2971,7 @@ HWTEST_F(CloudDataTest, TryUpdateDeviceId001, TestSize.Level1) bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKeyWithoutPath(), oldMeta); EXPECT_EQ(isSuccess, true); StoreMetaData meta1 = oldMeta; - auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); + auto ret = rdbServiceImpl.TryUpdateDeviceId(oldMeta, meta1); EXPECT_EQ(ret, true); MetaDataManager::GetInstance().DelMeta(oldMeta.GetKeyWithoutPath()); } @@ -2992,7 +2986,6 @@ HWTEST_F(CloudDataTest, TryUpdateDeviceId001, TestSize.Level1) HWTEST_F(CloudDataTest, TryUpdateDeviceId002, TestSize.Level1) { DistributedRdb::RdbServiceImpl rdbServiceImpl; - DistributedRdb::RdbSyncerParam param{ .bundleName_ = TEST_CLOUD_BUNDLE, .storeName_ = TEST_CLOUD_STORE }; StoreMetaData oldMeta; oldMeta.deviceId = "oldUuidtest"; oldMeta.user = "100"; @@ -3003,7 +2996,7 @@ HWTEST_F(CloudDataTest, TryUpdateDeviceId002, TestSize.Level1) bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKeyWithoutPath(), oldMeta); EXPECT_EQ(isSuccess, true); StoreMetaData meta1 = oldMeta; - auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); + auto ret = rdbServiceImpl.TryUpdateDeviceId(oldMeta, meta1); EXPECT_EQ(ret, true); MetaDataManager::GetInstance().DelMeta(oldMeta.GetKeyWithoutPath()); } @@ -3018,45 +3011,20 @@ HWTEST_F(CloudDataTest, TryUpdateDeviceId002, TestSize.Level1) HWTEST_F(CloudDataTest, TryUpdateDeviceId003, TestSize.Level1) { DistributedRdb::RdbServiceImpl rdbServiceImpl; - DistributedRdb::RdbSyncerParam param{ .bundleName_ = TEST_CLOUD_BUNDLE, .storeName_ = TEST_CLOUD_STORE }; StoreMetaData oldMeta; oldMeta.deviceId = "oldUuidtest"; oldMeta.user = "100"; oldMeta.bundleName = "test_appid_001"; - oldMeta.storeId = "test_storeid_001"; + oldMeta.storeId = "test_storeid_002"; oldMeta.isNeedUpdateDeviceId = true; - oldMeta.storeType = StoreMetaData::StoreType::STORE_RELATIONAL_END; - bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKeyWithoutPath(), oldMeta); - EXPECT_EQ(isSuccess, true); - StoreMetaData meta1 = oldMeta; - auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); - EXPECT_EQ(ret, true); - MetaDataManager::GetInstance().DelMeta(oldMeta.GetKeyWithoutPath()); -} - -/** -* @tc.name: TryUpdateDeviceId004 -* @tc.desc: TryUpdateDeviceId test -* @tc.type: FUNC -* @tc.require: -* @tc.author: -*/ -HWTEST_F(CloudDataTest, TryUpdateDeviceId004, TestSize.Level1) -{ - DistributedRdb::RdbServiceImpl rdbServiceImpl; - DistributedRdb::RdbSyncerParam param{ .bundleName_ = TEST_CLOUD_BUNDLE, .storeName_ = TEST_CLOUD_STORE }; - StoreMetaData oldMeta; - oldMeta.deviceId = "oldUuidtest"; - oldMeta.user = "100"; - oldMeta.bundleName = "test_appid_001"; - oldMeta.storeId = "test_storeid_001"; - oldMeta.isNeedUpdateDeviceId = false; - oldMeta.storeType = StoreMetaData::StoreType::STORE_RELATIONAL_END; + oldMeta.storeType = StoreMetaData::StoreType::STORE_RELATIONAL_BEGIN; bool isSuccess = MetaDataManager::GetInstance().SaveMeta(oldMeta.GetKeyWithoutPath(), oldMeta); EXPECT_EQ(isSuccess, true); StoreMetaData meta1 = oldMeta; - auto ret = rdbServiceImpl.TryUpdateDeviceId(param, oldMeta, meta1); - EXPECT_EQ(ret, true); + dbStatus_ = E_ERROR; + auto ret = rdbServiceImpl.TryUpdateDeviceId(oldMeta, meta1); + dbStatus_ = E_OK; + EXPECT_EQ(ret, false); MetaDataManager::GetInstance().DelMeta(oldMeta.GetKeyWithoutPath()); } diff --git a/services/distributeddataservice/service/test/data_share_sys_event_subscriber_test.cpp b/services/distributeddataservice/service/test/data_share_sys_event_subscriber_test.cpp index cfea876c2..7e24fcf16 100644 --- a/services/distributeddataservice/service/test/data_share_sys_event_subscriber_test.cpp +++ b/services/distributeddataservice/service/test/data_share_sys_event_subscriber_test.cpp @@ -53,7 +53,7 @@ HWTEST_F(DataShareSysEventSubscriberTest, OnBMSReady001, TestSize.Level1) // executors not null auto executors = std::make_shared(1, 0); // make sysEventSubscriber not null - auto sysEventSubscriber = std::make_shared(subscribeInfo, executors);\ + auto sysEventSubscriber = std::make_shared(subscribeInfo, executors); ASSERT_NE(sysEventSubscriber, nullptr); sysEventSubscriber->OnBMSReady(); ASSERT_NE(sysEventSubscriber->executors_, nullptr); diff --git a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp index 1d0d7d625..dcc328e6d 100644 --- a/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/kvdb_service_impl_test.cpp @@ -25,7 +25,7 @@ #include "cloud/cloud_server.h" #include "device_manager_adapter.h" #include "distributed_kv_data_manager.h" -#include "event_center.h" +#include "eventcenter/event_center.h" #include "ipc_skeleton.h" #include "kvdb_query.h" #include "kvdb_service_impl.h" diff --git a/services/distributeddataservice/service/test/kvdb_service_stub_unittest.cpp b/services/distributeddataservice/service/test/kvdb_service_stub_unittest.cpp index 59a0a826e..89d31df2c 100644 --- a/services/distributeddataservice/service/test/kvdb_service_stub_unittest.cpp +++ b/services/distributeddataservice/service/test/kvdb_service_stub_unittest.cpp @@ -14,16 +14,17 @@ */ #define LOG_TAG "KVDBServiceStubTest " -#include "kvdb_service_stub.h" -#include "kvdb_service_impl.h" -#include "gtest/gtest.h" +#include + +#include "bootstrap.h" +#include "device_matrix.h" #include "ipc_skeleton.h" +#include "itypes_util.h" #include "kv_types_util.h" +#include "kvdb_service_impl.h" +#include "kvdb_service_stub.h" #include "log_print.h" #include "types.h" -#include "device_matrix.h" -#include "bootstrap.h" -#include "itypes_util.h" using namespace OHOS; using namespace testing; diff --git a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h index 126862436..d03ed0592 100644 --- a/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h +++ b/services/distributeddataservice/service/test/mock/device_manager_adapter_mock.h @@ -37,9 +37,9 @@ public: virtual Status StopWatchDeviceChange(const AppDeviceChangeListener *, const PipeInfo &) = 0; virtual bool IsSameAccount(const AccessCaller &, const AccessCallee &) = 0; virtual bool IsSameAccount(const std::string &) = 0; - virtual std::string GetUuidByNetworkId(const std::string &); - virtual DeviceInfo GetDeviceInfo(const std::string &); - virtual std::string ToNetworkID(const std::string &); + virtual std::string GetUuidByNetworkId(const std::string &) = 0; + virtual DeviceInfo GetDeviceInfo(const std::string &) = 0; + virtual std::string ToNetworkID(const std::string &) = 0; virtual bool CheckAccessControl(const AccessCaller &, const AccessCallee &) = 0; virtual DeviceInfo GetLocalDevice() = 0; virtual std::string CalcClientUuid(const std::string &appId, const std::string &uuid) = 0; diff --git a/services/distributeddataservice/service/test/mock/device_matrix_mock.h b/services/distributeddataservice/service/test/mock/device_matrix_mock.h index f67eb94ca..055304c0c 100644 --- a/services/distributeddataservice/service/test/mock/device_matrix_mock.h +++ b/services/distributeddataservice/service/test/mock/device_matrix_mock.h @@ -22,8 +22,8 @@ namespace OHOS::DistributedData { class BDeviceMatrix { public: - virtual std::pair GetMask(const std::string &, DeviceMatrix::LevelType); - virtual std::pair GetRemoteMask(const std::string &, DeviceMatrix::LevelType); + virtual std::pair GetMask(const std::string &, DeviceMatrix::LevelType) = 0; + virtual std::pair GetRemoteMask(const std::string &, DeviceMatrix::LevelType) = 0; BDeviceMatrix() = default; virtual ~BDeviceMatrix() = default; static inline std::shared_ptr deviceMatrix = nullptr; diff --git a/services/distributeddataservice/service/test/mock/general_store_mock.cpp b/services/distributeddataservice/service/test/mock/general_store_mock.cpp index e984f665a..7fc984a89 100644 --- a/services/distributeddataservice/service/test/mock/general_store_mock.cpp +++ b/services/distributeddataservice/service/test/mock/general_store_mock.cpp @@ -141,11 +141,7 @@ std::pair> GeneralStoreMock::Query(const std::s return {GeneralError::E_OK, cursor_}; } -void GeneralStoreMock::MakeCursor(const std::map &entry) -{ - auto resultSet = std::make_shared(1, entry); - cursor_ = std::make_shared(resultSet); -} +void GeneralStoreMock::SetExecutor(std::shared_ptr executor) {} std::pair GeneralStoreMock::LockCloudDB() { @@ -157,6 +153,20 @@ int32_t GeneralStoreMock::UnLockCloudDB() return E_OK; } -void GeneralStoreMock::SetExecutor(std::shared_ptr executor) {} +int32_t GeneralStoreMock::UpdateDBStatus() +{ + return dbStatus_; +} + +void GeneralStoreMock::SetMockCursor(const std::map &entry) +{ + auto resultSet = std::make_shared(1, entry); + cursor_ = std::make_shared(resultSet); +} + +void GeneralStoreMock::SetMockDBStatus(int32_t dbStatus) +{ + dbStatus_ = dbStatus; +} } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/services/distributeddataservice/service/test/mock/general_store_mock.h b/services/distributeddataservice/service/test/mock/general_store_mock.h index 03fcb2eee..5d471f221 100644 --- a/services/distributeddataservice/service/test/mock/general_store_mock.h +++ b/services/distributeddataservice/service/test/mock/general_store_mock.h @@ -52,12 +52,16 @@ public: int32_t MergeMigratedData(const std::string &tableName, VBuckets &&values) override; int32_t CleanTrackerData(const std::string &tableName, int64_t cursor) override; void SetExecutor(std::shared_ptr executor) override; - void MakeCursor(const std::map &entry); std::pair LockCloudDB() override; int32_t UnLockCloudDB() override; + int32_t UpdateDBStatus() override; + + void SetMockCursor(const std::map &entry); + void SetMockDBStatus(int32_t dbStatus); private: std::shared_ptr cursor_ = nullptr; + int32_t dbStatus_ = 0; }; } // namespace DistributedData } // namespace OHOS diff --git a/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp b/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp index e5d20802c..13f2b736d 100644 --- a/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp +++ b/services/distributeddataservice/service/test/mock/general_watcher_mock.cpp @@ -25,28 +25,11 @@ std::vector MockQuery::GetTables() return tables_; } -const std::string GetStatement() +const std::string MockQuery::GetStatement() { return "AS distributed_log"; } -void MockQuery::MakeRemoteQuery(const std::string &devices, const std::string &sql, Values &&args) -{ - isRemote_ = true; - devices_ = { devices }; - sql_ = sql; - args_ = std::move(args); -} - -void MockQuery::MakeQuery(const DistributedRdb::PredicatesMemo &predicates) -{ - if (!predicates.tables_.empty()) { - predicates_ = std::make_shared(*predicates.tables_.begin()); - predicates_->SetWhereClause("id = 1"); - } - devices_ = predicates.devices_; - tables_ = predicates.tables_; -} int32_t MockGeneralWatcher::OnChange(const Origin &origin, const PRIFields &primaryFields, ChangeInfo &&values) { origin_ = origin; diff --git a/services/distributeddataservice/service/test/mock/general_watcher_mock.h b/services/distributeddataservice/service/test/mock/general_watcher_mock.h index f82741779..96d22d8e1 100644 --- a/services/distributeddataservice/service/test/mock/general_watcher_mock.h +++ b/services/distributeddataservice/service/test/mock/general_watcher_mock.h @@ -28,8 +28,6 @@ public: std::vector GetTables() override; const std::string GetStatement(); - void MakeRemoteQuery(const std::string &devices, const std::string &sql, DistributedData::Values &&args); - void MakeQuery(const DistributedRdb::PredicatesMemo &predicates); }; class MockGeneralWatcher : public DistributedData::GeneralWatcher { diff --git a/services/distributeddataservice/service/test/mock/preprocess_utils_mock.cpp b/services/distributeddataservice/service/test/mock/preprocess_utils_mock.cpp index 37238e41c..a042cf98c 100644 --- a/services/distributeddataservice/service/test/mock/preprocess_utils_mock.cpp +++ b/services/distributeddataservice/service/test/mock/preprocess_utils_mock.cpp @@ -30,7 +30,7 @@ #include "utils/crypto.h" #include "uri_permission_manager_client.h" #include "ipc_skeleton.h" -#include "bundle_mgr_interface.h" +#include "bundlemgr/bundle_mgr_interface.h" namespace OHOS { namespace UDMF { using namespace OHOS::DistributedDataDfx; diff --git a/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp b/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp index fa61b0cc4..ee3e111bc 100644 --- a/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp +++ b/services/distributeddataservice/service/test/mock/relational_store_manager_mock.cpp @@ -18,6 +18,7 @@ #include "relational_store_delegate_mock.h" #include "relational_store_manager.h" namespace DistributedDB { +bool MockRelationalStoreDelegate::gTestResult = false; DBStatus RelationalStoreManager::OpenStore(const std::string &path, const std::string &storeId, const RelationalStoreDelegate::Option &option, RelationalStoreDelegate *&delegate) { diff --git a/services/distributeddataservice/service/test/permit_delegate_mock_test.cpp b/services/distributeddataservice/service/test/permit_delegate_mock_test.cpp index 791708732..92b06a02b 100644 --- a/services/distributeddataservice/service/test/permit_delegate_mock_test.cpp +++ b/services/distributeddataservice/service/test/permit_delegate_mock_test.cpp @@ -166,8 +166,8 @@ HWTEST_F(PermitDelegateMockTest, VerifyPermission001, testing::ext::TestSize.Lev AppIDMetaData appMeta("permitdelegatemocktestId", "com.permitdelegatetest.app"); EXPECT_CALL(*metaDataMgrMock, LoadMeta(_, _, _)).WillOnce(DoAll(SetArgReferee<1>(appMeta), Return(true))); CheckParam checkParam = { - .appId = "permitdelegatemocktestId", .userId = "userid", + .appId = "permitdelegatemocktestId", .storeId = "storeid", .deviceId = "deviceid", .instanceId = 1 @@ -193,8 +193,8 @@ HWTEST_F(PermitDelegateMockTest, VerifyPermission002, testing::ext::TestSize.Lev auto ret = PermitDelegate::GetInstance().appId2BundleNameMap_.Find(key); ASSERT_TRUE(ret.second == value); CheckParam checkParam = { - .appId = "permitdelegatemocktestId2", .userId = "userid2", + .appId = "permitdelegatemocktestId2", .storeId = "storeid2", .deviceId = "deviceid2", .instanceId = 0 diff --git a/services/distributeddataservice/service/test/rdb_asset_loader_test.cpp b/services/distributeddataservice/service/test/rdb_asset_loader_test.cpp index a24357120..398337f8b 100644 --- a/services/distributeddataservice/service/test/rdb_asset_loader_test.cpp +++ b/services/distributeddataservice/service/test/rdb_asset_loader_test.cpp @@ -237,16 +237,17 @@ HWTEST_F(RdbAssetLoaderTest, PostEvent001, TestSize.Level0) HWTEST_F(RdbAssetLoaderTest, PostEvent002, TestSize.Level0) { DistributedData::Asset asset = { - .name = "", + .status = DistributedData::Asset::STATUS_DELETE, .id = "", - .path = "", + .name = "", .uri = "", - .modifyTime = "", .createTime = "", + .modifyTime = "", .size = "", .hash = "", - .status = DistributedData::Asset::STATUS_DELETE, + .path = "", }; + DistributedData::Assets assets; assets.push_back(asset); BindAssets bindAssets = nullptr; @@ -267,15 +268,15 @@ HWTEST_F(RdbAssetLoaderTest, PostEvent002, TestSize.Level0) */ HWTEST_F(RdbAssetLoaderTest, PostEvent003, TestSize.Level0) { DistributedData::Asset asset = { - .name = "", - .id = "", - .path = "", - .uri = "", - .modifyTime = "", - .createTime = "", - .size = "", - .hash = "", - .status = DistributedData::Asset::STATUS_NORMAL, + .status = DistributedData::Asset::STATUS_NORMAL, + .id = "", + .name = "", + .uri = "", + .createTime = "", + .modifyTime = "", + .size = "", + .hash = "", + .path = "", }; DistributedData::Assets assets; assets.push_back(asset); @@ -298,15 +299,15 @@ HWTEST_F(RdbAssetLoaderTest, PostEvent003, TestSize.Level0) { */ HWTEST_F(RdbAssetLoaderTest, PostEvent004, TestSize.Level0) { DistributedData::Asset asset = { - .name = "", + .status = DistributedData::Asset::STATUS_NORMAL, .id = "", - .path = "", + .name = "", .uri = "PostEvent004", - .modifyTime = "", .createTime = "", + .modifyTime = "", .size = "", .hash = "", - .status = DistributedData::Asset::STATUS_NORMAL, + .path = "", }; DistributedData::Assets assets; assets.push_back(asset); @@ -338,15 +339,15 @@ HWTEST_F(RdbAssetLoaderTest, PostEvent005, TestSize.Level0) { bool hasDownload = false; }; DistributedData::Asset asset = { - .name = "", + .status = DistributedData::Asset::STATUS_NORMAL, .id = "", - .path = "", + .name = "", .uri = "PostEvent005", - .modifyTime = "", .createTime = "", + .modifyTime = "", .size = "", .hash = "", - .status = DistributedData::Asset::STATUS_NORMAL, + .path = "", }; DistributedData::Assets assets; assets.push_back(asset); @@ -371,15 +372,15 @@ HWTEST_F(RdbAssetLoaderTest, PostEvent005, TestSize.Level0) { */ HWTEST_F(RdbAssetLoaderTest, PostEvent006, TestSize.Level0) { DistributedData::Asset asset = { - .name = "", + .status = DistributedData::Asset::STATUS_NORMAL, .id = "", - .path = "", + .name = "", .uri = "", - .modifyTime = "", .createTime = "", + .modifyTime = "", .size = "", .hash = "", - .status = DistributedData::Asset::STATUS_NORMAL, + .path = "", }; DistributedData::Assets assets; assets.push_back(asset); @@ -411,15 +412,15 @@ HWTEST_F(RdbAssetLoaderTest, PostEvent007, TestSize.Level0) { bool hasDownloaded = false; }; DistributedData::Asset asset = { - .name = "", + .status = DistributedData::Asset::STATUS_NORMAL, .id = "", - .path = "", + .name = "", .uri = "PostEvent007", - .modifyTime = "", .createTime = "", + .modifyTime = "", .size = "", .hash = "", - .status = DistributedData::Asset::STATUS_NORMAL, + .path = "", }; DistributedData::Assets assets; assets.push_back(asset); @@ -453,15 +454,15 @@ HWTEST_F(RdbAssetLoaderTest, PostEvent008, TestSize.Level0) { bool hasDownloaded = false; }; DistributedData::Asset asset = { - .name = "", + .status = DistributedData::Asset::STATUS_NORMAL, .id = "", - .path = "", + .name = "", .uri = "PostEvent008", - .modifyTime = "", .createTime = "", + .modifyTime = "", .size = "", .hash = "", - .status = DistributedData::Asset::STATUS_NORMAL, + .path = "", }; DistributedData::Assets assets; assets.push_back(asset); @@ -493,15 +494,15 @@ HWTEST_F(RdbAssetLoaderTest, PostEvent009, TestSize.Level0) { bool hasDownloaded = false; }; DistributedData::Asset asset = { - .name = "", + .status = DistributedData::Asset::STATUS_NORMAL, .id = "", - .path = "", + .name = "", .uri = "PostEvent009", - .modifyTime = "", .createTime = "", + .modifyTime = "", .size = "", .hash = "", - .status = DistributedData::Asset::STATUS_NORMAL, + .path = "", }; DistributedData::Assets assets; assets.push_back(asset); @@ -534,15 +535,15 @@ HWTEST_F(RdbAssetLoaderTest, PostEvent0010, TestSize.Level0) { bool hasDownloaded = false; }; DistributedData::Asset asset = { - .name = "", + .status = DistributedData::Asset::STATUS_NORMAL, .id = "", - .path = "", + .name = "", .uri = "PostEvent0010", - .modifyTime = "", .createTime = "", + .modifyTime = "", .size = "", .hash = "", - .status = DistributedData::Asset::STATUS_NORMAL, + .path = "", }; DistributedData::Assets assets; assets.push_back(asset); diff --git a/services/distributeddataservice/service/test/rdb_general_store_test.cpp b/services/distributeddataservice/service/test/rdb_general_store_test.cpp index 6a2dbf2a1..935b613de 100644 --- a/services/distributeddataservice/service/test/rdb_general_store_test.cpp +++ b/services/distributeddataservice/service/test/rdb_general_store_test.cpp @@ -48,7 +48,6 @@ RdbGeneralStore::Values g_RdbValues = { { "0000000" }, { true }, { int64_t(100) { Bytes({ 1, 2, 3, 4 }) } }; RdbGeneralStore::VBucket g_RdbVBucket = { { "#gid", { "0000000" } }, { "#flag", { true } }, { "#value", { int64_t(100) } }, { "#float", { double(100) } } }; -bool MockRelationalStoreDelegate::gTestResult = false; namespace OHOS::Test { namespace DistributedRDBTest { using StoreMetaData = OHOS::DistributedData::StoreMetaData; @@ -58,7 +57,10 @@ static constexpr const char *BUNDLE_NAME = "test_rdb_general_store"; static constexpr const char *STORE_NAME = "test_service_rdb"; class RdbGeneralStoreTest : public testing::Test { public: - static void SetUpTestCase(void){}; + static void SetUpTestCase(void) + { + MockRelationalStoreDelegate::gTestResult = false; + }; static void TearDownTestCase(void){}; void SetUp() { @@ -571,11 +573,7 @@ HWTEST_F(RdbGeneralStoreTest, Query003, TestSize.Level1) store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); - MockQuery query; - const std::string devices = "device1"; - const std::string sql; - Values args; - query.lastResult = true; + RdbQuery query; std::string table = "test_table"; auto [err, cursor] = store->Query(table, query); EXPECT_EQ(err, GeneralError::E_ERROR); @@ -588,13 +586,10 @@ HWTEST_F(RdbGeneralStoreTest, Query003, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, Query004, TestSize.Level1) { - MockQuery query; const std::string devices = "device1"; const std::string sql; Values args; - query.MakeRemoteQuery(devices, sql, std::move(args)); - query.lastResult = true; - + RdbQuery query(devices, sql, std::move(args)); metaData_.storeId = "mock"; store = std::make_shared(metaData_); @@ -721,12 +716,11 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing001, TestSize.Level1) */ HWTEST_F(RdbGeneralStoreTest, PreSharing002, TestSize.Level1) { - MockQuery query; DistributedRdb::PredicatesMemo predicates; predicates.devices_ = { "device1" }; predicates.tables_ = { "tables1" }; - query.lastResult = true; - query.MakeQuery(predicates); + predicates.AddOperation(EQUAL_TO, "id", "1"); + RdbQuery query(predicates); auto [errCode, result] = store->PreSharing(query); EXPECT_EQ(errCode, GeneralError::E_ALREADY_CLOSED); EXPECT_EQ(result, nullptr); @@ -742,12 +736,12 @@ HWTEST_F(RdbGeneralStoreTest, PreSharing003, TestSize.Level1) metaData_.storeId = "mock"; store = std::make_shared(metaData_); ASSERT_NE(store, nullptr); - MockQuery query; + DistributedRdb::PredicatesMemo predicates; predicates.devices_ = { "device1" }; predicates.tables_ = { "tables1" }; - query.lastResult = true; - query.MakeQuery(predicates); + predicates.AddOperation(EQUAL_TO, "id", "1"); + RdbQuery query(predicates); auto [errCode, result] = store->PreSharing(query); EXPECT_EQ(errCode, GeneralError::E_CLOUD_DISABLED); ASSERT_EQ(result, nullptr); diff --git a/services/distributeddataservice/service/test/rdb_query_test.cpp b/services/distributeddataservice/service/test/rdb_query_test.cpp index 3405f4f0f..1dbc82672 100644 --- a/services/distributeddataservice/service/test/rdb_query_test.cpp +++ b/services/distributeddataservice/service/test/rdb_query_test.cpp @@ -54,13 +54,13 @@ HWTEST_F(RdbQueryTest, RdbQueryTest001, TestSize.Level1) std::string devices = "devices1"; std::string sql = "SELECT * FROM table"; Values args; - rdbQuery.MakeRemoteQuery(devices, sql, std::move(args)); - EXPECT_TRUE(rdbQuery.IsRemoteQuery()); - EXPECT_EQ(rdbQuery.GetDevices().size(), 1); - EXPECT_EQ(rdbQuery.GetDevices()[0], devices); + RdbQuery remoteQuery(devices, sql, std::move(args)); + EXPECT_TRUE(remoteQuery.IsRemoteQuery()); + EXPECT_EQ(remoteQuery.GetDevices().size(), 1); + EXPECT_EQ(remoteQuery.GetDevices()[0], devices); DistributedRdb::PredicatesMemo predicates; - rdbQuery.MakeQuery(predicates); - rdbQuery.MakeCloudQuery(predicates); + RdbQuery normalQuery(predicates); + RdbQuery cloudQuery(predicates, true); EXPECT_EQ(predicates.tables_.size(), 0); EXPECT_TRUE(predicates.tables_.empty()); EXPECT_EQ(predicates.operations_.size(), 0); @@ -75,11 +75,10 @@ HWTEST_F(RdbQueryTest, RdbQueryTest001, TestSize.Level1) */ HWTEST_F(RdbQueryTest, RdbQueryTest002, TestSize.Level1) { - RdbQuery rdbQuery; std::string devices = "devices1"; std::string sql = "SELECT * FROM table"; Values args; - rdbQuery.MakeRemoteQuery(devices, sql, std::move(args)); + RdbQuery remoteQuery(devices, sql, std::move(args)); DistributedRdb::PredicatesMemo predicates; predicates.tables_.push_back("table1"); predicates.tables_.push_back("table2"); @@ -87,8 +86,8 @@ HWTEST_F(RdbQueryTest, RdbQueryTest002, TestSize.Level1) predicates.AddOperation(DistributedRdb::RdbPredicateOperator::EQUAL_TO, "name", "John Doe"); predicates.AddOperation(DistributedRdb::RdbPredicateOperator::GREATER_THAN, "age", "30"); predicates.AddOperation(DistributedRdb::RdbPredicateOperator::OPERATOR_MAX, "too", "99"); - rdbQuery.MakeQuery(predicates); - rdbQuery.MakeCloudQuery(predicates); + RdbQuery rdbQuery(predicates); + RdbQuery cloudQuery(predicates, true); EXPECT_EQ(predicates.tables_.size(), 2); EXPECT_TRUE(!predicates.tables_.empty()); EXPECT_EQ(predicates.operations_.size(), 3); @@ -103,11 +102,10 @@ HWTEST_F(RdbQueryTest, RdbQueryTest002, TestSize.Level1) */ HWTEST_F(RdbQueryTest, RdbQueryTest003, TestSize.Level1) { - RdbQuery rdbQuery; std::string devices = "devices1"; std::string sql = "SELECT * FROM table"; Values args; - rdbQuery.MakeRemoteQuery(devices, sql, std::move(args)); + RdbQuery remoteQuery(devices, sql, std::move(args)); DistributedRdb::PredicatesMemo predicates; predicates.tables_.push_back("table1"); predicates.tables_.push_back("table2"); @@ -127,7 +125,7 @@ HWTEST_F(RdbQueryTest, RdbQueryTest003, TestSize.Level1) predicates.AddOperation(DistributedRdb::RdbPredicateOperator::GREATER_THAN_OR_EQUAL, "test", values); predicates.AddOperation(DistributedRdb::RdbPredicateOperator::LESS_THAN, "test", values); predicates.AddOperation(DistributedRdb::RdbPredicateOperator::LESS_THAN_OR_EQUAL, "test", values); - rdbQuery.MakeQuery(predicates); + RdbQuery rdbQuery(predicates); EXPECT_TRUE(values.empty()); EXPECT_TRUE(values.size() != 2); } @@ -141,11 +139,10 @@ HWTEST_F(RdbQueryTest, RdbQueryTest003, TestSize.Level1) */ HWTEST_F(RdbQueryTest, RdbQueryTest004, TestSize.Level1) { - RdbQuery rdbQuery; std::string devices = "devices1"; std::string sql = "SELECT * FROM table"; Values args; - rdbQuery.MakeRemoteQuery(devices, sql, std::move(args)); + RdbQuery remoteQuery(devices, sql, std::move(args)); DistributedRdb::PredicatesMemo predicates; predicates.tables_.push_back("table1"); predicates.tables_.push_back("table2"); @@ -176,7 +173,7 @@ HWTEST_F(RdbQueryTest, RdbQueryTest004, TestSize.Level1) predicates.AddOperation(DistributedRdb::RdbPredicateOperator::LESS_THAN_OR_EQUAL, "test", values); predicates.AddOperation(DistributedRdb::RdbPredicateOperator::DISTINCT, "test", values); predicates.AddOperation(DistributedRdb::RdbPredicateOperator::INDEXED_BY, "test", values); - rdbQuery.MakeQuery(predicates); + RdbQuery rdbQuery(predicates); EXPECT_TRUE(!values.empty()); EXPECT_FALSE(values.size() != 2); } @@ -190,7 +187,6 @@ HWTEST_F(RdbQueryTest, RdbQueryTest004, TestSize.Level1) */ HWTEST_F(RdbQueryTest, RdbQueryTest005, TestSize.Level1) { - RdbQuery rdbQuery; DistributedRdb::PredicatesMemo predicates; predicates.tables_.push_back("table"); std::vector assets; @@ -198,7 +194,7 @@ HWTEST_F(RdbQueryTest, RdbQueryTest005, TestSize.Level1) assets.push_back(asset); NativeRdb::ValueObject object(assets); predicates.AddOperation(DistributedRdb::RdbPredicateOperator::EQUAL_TO, "test", object); - rdbQuery.MakeCloudQuery(predicates); + RdbQuery rdbQuery(predicates); EXPECT_EQ(predicates.operations_.size(), 1); } @@ -211,14 +207,13 @@ HWTEST_F(RdbQueryTest, RdbQueryTest005, TestSize.Level1) */ HWTEST_F(RdbQueryTest, RdbQueryTest006, TestSize.Level1) { - RdbQuery rdbQuery; DistributedRdb::PredicatesMemo predicates; predicates.tables_.push_back("table"); std::vector assets; NativeRdb::AssetValue asset{ .name = "name1" }; NativeRdb::ValueObject object(asset); predicates.AddOperation(DistributedRdb::RdbPredicateOperator::EQUAL_TO, "test", object); - rdbQuery.MakeCloudQuery(predicates); + RdbQuery rdbQuery(predicates); EXPECT_EQ(predicates.operations_.size(), 1); } @@ -231,7 +226,6 @@ HWTEST_F(RdbQueryTest, RdbQueryTest006, TestSize.Level1) */ HWTEST_F(RdbQueryTest, RdbQueryTest007, TestSize.Level1) { - RdbQuery rdbQuery; DistributedRdb::PredicatesMemo predicates; predicates.tables_.push_back("table"); std::vector assets; @@ -239,7 +233,7 @@ HWTEST_F(RdbQueryTest, RdbQueryTest007, TestSize.Level1) assets.push_back(asset); NativeRdb::ValueObject object(assets); predicates.AddOperation(DistributedRdb::RdbPredicateOperator::IN, "test", object); - rdbQuery.MakeCloudQuery(predicates); + RdbQuery rdbQuery(predicates); EXPECT_EQ(predicates.operations_.size(), 1); } } // namespace DistributedRDBTest diff --git a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp index fe4501ad8..95e9a4ba7 100644 --- a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp @@ -13,6 +13,9 @@ * limitations under the License. */ +#include "rdb_service_impl.h" + +#include #include #include "account/account_delegate.h" @@ -20,26 +23,24 @@ #include "checker_mock.h" #include "cloud/change_event.h" #include "cloud/schema_meta.h" -#include "crypto/crypto_manager.h" #include "device_manager_adapter.h" #include "device_matrix.h" -#include "event_center.h" +#include "directory/directory_manager.h" +#include "eventcenter/event_center.h" #include "ipc_skeleton.h" #include "metadata/appid_meta_data.h" #include "metadata/capability_meta_data.h" #include "metadata/meta_data_manager.h" -#include "metadata/store_meta_data.h" -#include "metadata/store_meta_data_local.h" +#include "metadata/special_channel_data.h" #include "metadata/store_debug_info.h" -#include "mock/device_manager_adapter_mock.h" +#include "metadata/store_meta_data_local.h" #include "mock/db_store_mock.h" +#include "mock/device_manager_adapter_mock.h" #include "mock/general_store_mock.h" -#include "store/general_value.h" -#include "rdb_service_impl.h" +#include "rdb_general_store.h" #include "rdb_types.h" #include "relational_store_manager.h" -#include "gtest/gtest.h" -#include "directory/directory_manager.h" +#include "sync_mgr/sync_mgr.h" using namespace OHOS::DistributedRdb; using namespace OHOS::DistributedData; @@ -48,6 +49,7 @@ using namespace testing::ext; using namespace testing; using namespace std; using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; +using RdbGeneralStore = OHOS::DistributedRdb::RdbGeneralStore; namespace OHOS::Test { namespace DistributedRDBTest { @@ -55,6 +57,8 @@ namespace DistributedRDBTest { static constexpr const char *TEST_BUNDLE = "test_rdb_service_impl_bundleName"; static constexpr const char *TEST_APPID = "test_rdb_service_impl_appid"; static constexpr const char *TEST_STORE = "test_rdb_service_impl_store"; +static constexpr const char *TEST_SYNC_DEVICE = "test_sync_device1"; +static constexpr const char *TEST_INVALID_DEVICE = "test_invalid_device1"; static constexpr int32_t KEY_LENGTH = 32; static constexpr uint32_t DELY_TIME = 10000; @@ -63,21 +67,22 @@ public: static void SetUpTestCase(void); static void TearDownTestCase(void); static void InitMetaData(); - static void InitMapping(StoreMetaMapping &meta); + static void InitMapping(StoreMetaData &meta); void SetUp(); void TearDown(); static std::vector Random(int32_t len); protected: + static void InitMetaDataManager(); + static StoreMetaData GetDBMetaData(const Database &database); static std::shared_ptr dbStoreMock_; static StoreMetaData metaData_; - static CheckerMock checkerMock_; + static CheckerMock systemChecker_; static inline std::shared_ptr deviceManagerAdapterMock = nullptr; - static void InitMetaDataManager(); }; std::shared_ptr RdbServiceImplTest::dbStoreMock_ = std::make_shared(); StoreMetaData RdbServiceImplTest::metaData_; -CheckerMock RdbServiceImplTest::checkerMock_; +CheckerMock RdbServiceImplTest::systemChecker_; void RdbServiceImplTest::InitMetaData() { @@ -94,7 +99,7 @@ void RdbServiceImplTest::InitMetaData() metaData_.dataDir = DirectoryManager::GetInstance().GetStorePath(metaData_) + "/" + TEST_STORE; } -void RdbServiceImplTest::InitMapping(StoreMetaMapping &metaMapping) +void RdbServiceImplTest::InitMapping(StoreMetaData &metaMapping) { metaMapping.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; metaMapping.user = "100"; @@ -110,6 +115,16 @@ void RdbServiceImplTest::InitMetaDataManager() }); } +StoreMetaData RdbServiceImplTest::GetDBMetaData(const Database &database) +{ + StoreMetaData metaData = metaData_; + RdbSyncerParam param; + metaData.bundleName = database.bundleName; + metaData.user = database.user; + metaData.storeId = RdbServiceImpl::RemoveSuffix(database.name); + return metaData; +} + void RdbServiceImplTest::SetUpTestCase() { deviceManagerAdapterMock = std::make_shared(); @@ -125,16 +140,34 @@ void RdbServiceImplTest::SetUpTestCase() Bootstrap::GetInstance().LoadCheckers(); CryptoManager::GetInstance().GenerateRootKey(); MetaDataManager::GetInstance().Initialize(dbStoreMock_, nullptr, ""); + + auto creator = [](const StoreMetaData &metaData) -> GeneralStore* { + return new (std::nothrow) GeneralStoreMock(); + }; + AutoCache::GetInstance().RegCreator(DistributedRdb::RDB_DEVICE_COLLABORATION, creator); + SyncManager::AutoSyncInfo syncInfo = { 3, TEST_APPID, TEST_BUNDLE }; + SyncManager::GetInstance().Initialize({ syncInfo }); } void RdbServiceImplTest::TearDownTestCase() { deviceManagerAdapterMock = nullptr; BDeviceManagerAdapter::deviceManagerAdapter = nullptr; + AutoCache::GetInstance().RegCreator(DistributedRdb::RDB_DEVICE_COLLABORATION, + [](const StoreMetaData &metaData) -> GeneralStore* { + auto store = new (std::nothrow) RdbGeneralStore(metaData); + if (store != nullptr && !store->IsValid()) { + delete store; + store = nullptr; + } + return store; + }); } void RdbServiceImplTest::SetUp() { + RdbServiceImpl service; + service.SaveAutoSyncInfo(metaData_, { TEST_SYNC_DEVICE }); } void RdbServiceImplTest::TearDown() @@ -268,13 +301,13 @@ HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch005, TestSize.Level0) } /** -* @tc.name: ResolveAutoLaunch006 +* @tc.name: ObtainDistributedTableName001 * @tc.desc: test ObtainDistributedTableName, uuid exist. * @tc.type: FUNC * @tc.require: * @tc.author: zhaojh */ -HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch006, TestSize.Level0) +HWTEST_F(RdbServiceImplTest, ObtainDistributedTableName001, TestSize.Level0) { EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKeyWithoutPath(), metaData_, false), true); RdbServiceImpl service; @@ -286,13 +319,13 @@ HWTEST_F(RdbServiceImplTest, ResolveAutoLaunch006, TestSize.Level0) } /** -* @tc.name: ObtainDistributedTableName001 +* @tc.name: ObtainDistributedTableName002 * @tc.desc: test ObtainDistributedTableName, uuid invalid. * @tc.type: FUNC * @tc.require: * @tc.author: zhaojh */ -HWTEST_F(RdbServiceImplTest, ObtainDistributedTableName001, TestSize.Level0) +HWTEST_F(RdbServiceImplTest, ObtainDistributedTableName002, TestSize.Level0) { EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKeyWithoutPath(), metaData_, false), true); RdbServiceImpl service; @@ -401,12 +434,12 @@ HWTEST_F(RdbServiceImplTest, GetCallbacks001, TestSize.Level0) HWTEST_F(RdbServiceImplTest, DoSync001, TestSize.Level0) { RdbServiceImpl service; - RdbSyncerParam param; + StoreMetaData metaData; RdbService::Option option; PredicatesMemo predicates; AsyncDetail async; - auto result = service.DoSync(param, option, predicates, async); + auto result = service.DoSync(metaData, option, predicates, async); EXPECT_EQ(result, RDB_ERROR); } @@ -422,18 +455,6 @@ HWTEST_F(RdbServiceImplTest, DoSync002, TestSize.Level0) EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKeyWithoutPath(), metaData_, false), true); RdbServiceImpl service; - RdbSyncerParam param; - param.bundleName_ = metaData_.bundleName; - param.type_ = metaData_.storeType; - param.level_ = metaData_.securityLevel; - param.area_ = metaData_.area; - param.hapName_ = metaData_.bundleName; - param.storeName_ = metaData_.storeId; - param.isEncrypt_ = metaData_.isEncrypt; - param.isSearchable_ = metaData_.isSearchable; - param.haMode_ = metaData_.haMode; - param.asyncDownloadAsset_ = metaData_.asyncDownloadAsset; - RdbService::Option option; option.mode = DistributedData::GeneralStore::AUTO_SYNC_MODE; option.seqNum = 1; @@ -441,8 +462,8 @@ HWTEST_F(RdbServiceImplTest, DoSync002, TestSize.Level0) PredicatesMemo predicates; AsyncDetail async; - auto result = service.DoSync(param, option, predicates, async); - EXPECT_EQ(result, RDB_ERROR); + auto result = service.DoSync(metaData_, option, predicates, async); + EXPECT_EQ(result, RDB_OK); EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKeyWithoutPath(), false), true); } @@ -640,10 +661,10 @@ HWTEST_F(RdbServiceImplTest, DoAutoSync001, TestSize.Level0) { RdbServiceImpl service; std::vector devices = {"device1"}; - StoreMetaData meta; + StoreMetaData metaData; std::vector tables = {"table1"}; - auto result = service.DoAutoSync(devices, meta, tables); + auto result = service.DoAutoSync(devices, metaData, tables); EXPECT_EQ(result, RDB_ERROR); } @@ -656,35 +677,40 @@ HWTEST_F(RdbServiceImplTest, DoAutoSync001, TestSize.Level0) */ HWTEST_F(RdbServiceImplTest, DoAutoSync002, TestSize.Level0) { - StoreMetaMapping metaMapping; - InitMapping(metaMapping); - metaMapping.dataDir = "path"; + StoreMetaData syncMeta; + InitMapping(syncMeta); + syncMeta.dataDir = "path"; + RdbServiceImpl::SaveSyncMeta(syncMeta); + StoreMetaMapping metaMapping(syncMeta); metaMapping.devicePath = "path1"; EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaMapping.GetKey(), metaMapping, true), true); + RdbServiceImpl service; - StoreMetaData meta; std::vector devices = {"device1"}; - DistributedData::Database dataBase; + DistributedData::Database database; std::vector tables = {"table1"}; - meta.bundleName = "bundleName"; - meta.storeId= "storeName"; - meta.user = "100"; - auto result = service.DoAutoSync(devices, meta, tables); + database.bundleName = "bundleName"; + database.name = "storeName"; + database.user = "100"; + auto [exists, metaData] = RdbServiceImpl::LoadSyncMeta(database); + EXPECT_EQ(exists, true); + auto result = service.DoAutoSync(devices, metaData, tables); EXPECT_EQ(result, RDB_ERROR); } /** - * @tc.name: DoOnlineSync001 - * @tc.desc: Test DoOnlineSync when all tables have deviceSyncFields. + * @tc.name: OnReady_DoAutoSync001 + * @tc.desc: Test OnReady_DoAutoSync001 when all tables have deviceSyncFields. * @tc.type: FUNC * @tc.require: * @tc.author: zhaojh */ -HWTEST_F(RdbServiceImplTest, DoOnlineSync001, TestSize.Level0) +HWTEST_F(RdbServiceImplTest, OnReady_DoAutoSync001, TestSize.Level0) { RdbServiceImpl service; - DistributedData::Database dataBase; - dataBase.name = TEST_STORE; + std::vector devices = {"device1"}; + DistributedData::Database database; + database.name = TEST_STORE; DistributedData::Table table1; table1.name = "table1"; @@ -693,9 +719,10 @@ HWTEST_F(RdbServiceImplTest, DoOnlineSync001, TestSize.Level0) table2.name = "table2"; table2.deviceSyncFields = {}; - dataBase.tables = {table1, table2}; - - auto result = service.DoOnlineSync("device1", dataBase); + database.tables = {table1, table2}; + auto [exists, metaData] = RdbServiceImpl::LoadSyncMeta(database); + EXPECT_EQ(exists, false); + auto result = service.DoAutoSync(devices, metaData, database.GetSyncTables()); EXPECT_EQ(result, RDB_ERROR); } @@ -712,7 +739,7 @@ HWTEST_F(RdbServiceImplTest, OnReady001, TestSize.Level0) std::string device = "test_device"; int32_t result = service.OnReady(device); - EXPECT_EQ(result, 0); + EXPECT_EQ(result, -E_OK); } /** @@ -725,10 +752,9 @@ HWTEST_F(RdbServiceImplTest, OnReady001, TestSize.Level0) HWTEST_F(RdbServiceImplTest, OnReady002, TestSize.Level0) { RdbServiceImpl service; - std::string device = metaData_.deviceId; - + service.OnInitialize(); DistributedData::Database dataBase1; - dataBase1.name = "test_rdb_service_impl_sync_store2"; + dataBase1.name = "test_rdb_service_impl_sync_store1"; dataBase1.bundleName = TEST_BUNDLE; dataBase1.user = std::to_string(AccountDelegate::GetInstance()->GetUserByToken(metaData_.tokenId)); dataBase1.autoSyncType = AutoSyncType::SYNC_ON_READY; @@ -738,14 +764,178 @@ HWTEST_F(RdbServiceImplTest, OnReady002, TestSize.Level0) dataBase2.bundleName = TEST_BUNDLE; dataBase2.user = std::to_string(AccountDelegate::GetInstance()->GetUserByToken(metaData_.tokenId)); dataBase2.autoSyncType = AutoSyncType::SYNC_ON_CHANGE_READY; + auto metaData1 = GetDBMetaData(dataBase1); + RdbServiceImpl::SaveSyncMeta(metaData1); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(dataBase1.GetKey(), dataBase1, true), true); + auto metaData2 = GetDBMetaData(dataBase2); + RdbServiceImpl::SaveSyncMeta(metaData2); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(dataBase2.GetKey(), dataBase2, true), true); + int32_t result = service.OnReady(TEST_SYNC_DEVICE); + EXPECT_EQ(result, 2); + result = service.OnReady(TEST_INVALID_DEVICE); + EXPECT_EQ(result, 0); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(dataBase1.GetKey(), true), true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData1.GetKey(), true), true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(dataBase2.GetKey(), true), true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData2.GetKey(), true), true); +} - EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(dataBase1.GetKey(), metaData_, true), true); - EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(dataBase2.GetKey(), metaData_, true), true); - int32_t result = service.OnReady(device); +/** + * @tc.name: OnReady002 + * @tc.desc: Test OnReady when no databases have autoSyncType SYNC_ON_READY or SYNC_ON_CHANGE_READY. + * @tc.type: FUNC + * @tc.require: + * @tc.author: Sven Wang + */ +HWTEST_F(RdbServiceImplTest, OnReady003, TestSize.Level0) +{ + RdbServiceImpl service; + service.OnInitialize(); + DistributedData::Database database; + database.bundleName = TEST_BUNDLE; + database.user = std::to_string(AccountDelegate::GetInstance()->GetUserByToken(metaData_.tokenId)); + database.autoSyncType = AutoSyncType::SYNC_ON_READY; + for (int i = 0; i < 10; ++i) { + database.name = "test_rdb_service_impl_sync_store" + std::to_string(i); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(database.GetKey(), database, true), true); + RdbServiceImpl::SaveSyncMeta(GetDBMetaData(database)); + } + int32_t result = service.OnReady(TEST_SYNC_DEVICE); + EXPECT_EQ(result, -E_OVER_MAX_LIMITS); + + for (int i = 0; i < 10; ++i) { + database.name = "test_rdb_service_impl_sync_store" + std::to_string(i); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(database.GetKey(), true), true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(GetDBMetaData(database).GetKeyWithoutPath()), true); + } +} + +/** + * @tc.name: OnReady004 + * @tc.desc: Test OnReady when no databases have autoSyncType SYNC_ON_READY or SYNC_ON_CHANGE_READY. + * @tc.type: FUNC + * @tc.require: + * @tc.author: Sven Wang + */ +HWTEST_F(RdbServiceImplTest, OnReady004, TestSize.Level0) +{ + RdbServiceImpl service; + service.OnInitialize(); + DistributedData::Database database; + database.bundleName = TEST_BUNDLE; + database.user = std::to_string(AccountDelegate::GetInstance()->GetUserByToken(metaData_.tokenId)); + database.autoSyncType = AutoSyncType::SYNC_ON_READY; + for (int i = 0; i < 3; ++i) { + database.name = "test_rdb_service_impl_sync_store" + std::to_string(i); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(database.GetKey(), database, true), true); + RdbServiceImpl::SaveSyncMeta(GetDBMetaData(database)); + } + + int32_t result = service.OnReady("test_sync_device2"); EXPECT_EQ(result, 0); - EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(dataBase1.GetKey(), metaData_, true), true); - EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(dataBase2.GetKey(), metaData_, true), true); + service.SaveAutoSyncInfo(metaData_, { "test_sync_device2" }); + result = service.OnReady("test_sync_device2"); + EXPECT_EQ(result, 3); + for (int i = 0; i < 3; ++i) { + database.name = "test_rdb_service_impl_sync_store" + std::to_string(i); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(database.GetKey(), true), true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(GetDBMetaData(database).GetKeyWithoutPath()), true); + } +} + +/** + * @tc.name: SpecialChannel001 + * @tc.desc: Test OnReady when no databases have autoSyncType SYNC_ON_READY or SYNC_ON_CHANGE_READY. + * @tc.type: FUNC + * @tc.require: + * @tc.author: Sven Wang + */ +HWTEST_F(RdbServiceImplTest, SpecialChannel001, TestSize.Level0) +{ + RdbServiceImpl service; + service.OnInitialize(); + auto result = service.IsSpecialChannel(TEST_SYNC_DEVICE); + EXPECT_EQ(result, true); + result = service.IsSpecialChannel("test_sync_device2"); + EXPECT_EQ(result, false); + service.SaveAutoSyncInfo(metaData_, { "test_sync_device2" }); + result = service.IsSpecialChannel("test_sync_device2"); + EXPECT_EQ(result, true); +} + +/** + * @tc.name: SpecialChannel002 + * @tc.desc: Test OnReady when no databases have autoSyncType SYNC_ON_READY or SYNC_ON_CHANGE_READY. + * @tc.type: FUNC + * @tc.require: + * @tc.author: Sven Wang + */ +HWTEST_F(RdbServiceImplTest, SpecialChannel002, TestSize.Level0) +{ + { + RdbServiceImpl service; + service.OnInitialize(); + service.SaveAutoSyncInfo(metaData_, { "test_sync_device2" }); + } + RdbServiceImpl service; + service.OnInitialize(); + auto result = service.IsSpecialChannel("test_sync_device2"); + EXPECT_EQ(result, true); +} + +/** + * @tc.name: SpecialChannel003 + * @tc.desc: Test OnReady when no databases have autoSyncType SYNC_ON_READY or SYNC_ON_CHANGE_READY. + * @tc.type: FUNC + * @tc.require: + * @tc.author: Sven Wang + */ +HWTEST_F(RdbServiceImplTest, SpecialChannel003, TestSize.Level0) +{ + { + RdbServiceImpl service; + service.OnInitialize(); + service.SaveAutoSyncInfo(metaData_, { "test_sync_device2" }); + } + auto executors = std::make_shared(1, 0); + EXPECT_NE(executors, nullptr); + RdbServiceImpl service; + service.OnInitialize(); + service.OnBind({.executors = executors}); + auto result = service.IsSpecialChannel(TEST_SYNC_DEVICE); + EXPECT_EQ(result, true); + executors->Remove(service.saveChannelsTask_); + service.OnBind({.executors = nullptr}); + executors = nullptr; +} + +/** + * @tc.name: SpecialChannel004 + * @tc.desc: Test OnReady when no databases have autoSyncType SYNC_ON_READY or SYNC_ON_CHANGE_READY. + * @tc.type: FUNC + * @tc.require: + * @tc.author: Sven Wang + */ +HWTEST_F(RdbServiceImplTest, SpecialChannel004, TestSize.Level0) +{ + { + RdbServiceImpl service; + service.OnInitialize(); + service.SaveAutoSyncInfo(metaData_, { "test_sync_device2" }); + } + RdbServiceImpl service; + service.OnInitialize(); + std::vector devices = { TEST_SYNC_DEVICE, "test_sync_device2", "test_sync_device3", + "test_sync_device4" }; + if (SyncManager::GetInstance().IsAutoSyncApp(metaData_.bundleName, metaData_.appId)) { + auto begin = std::remove_if(devices.begin(), devices.end(), [&service](const std::string &device) { + return !service.IsSpecialChannel(device); + }); + devices.erase(begin, devices.end()); + } + std::vector devTag = { TEST_SYNC_DEVICE, "test_sync_device2" }; + EXPECT_EQ(devices, devTag); } /** @@ -898,12 +1088,15 @@ HWTEST_F(RdbServiceImplTest, NotifyDataChange003, TestSize.Level0) param.customDir_ = "dir1/dir2"; RdbChangedData rdbChangedData; RdbNotifyConfig rdbNotifyConfig; + auto metaData = service.GetStoreMetaData(param); + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData.GetKey(), metaData, true), true); rdbNotifyConfig.delay_ = 0; int32_t result = service.NotifyDataChange(param, rdbChangedData, rdbNotifyConfig); EXPECT_EQ(result, RDB_OK); rdbNotifyConfig.delay_ = DELY_TIME; result = service.NotifyDataChange(param, rdbChangedData, rdbNotifyConfig); EXPECT_EQ(result, RDB_OK); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData.GetKey(), true), true); } /** @@ -1219,12 +1412,6 @@ HWTEST_F(RdbServiceImplTest, SetDistributedTables004, TestSize.Level0) auto meta = service.GetStoreMetaData(param); ASSERT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true), true); - auto creator = [](const StoreMetaData &metaData) -> GeneralStore* { - auto store = new (std::nothrow) GeneralStoreMock(); - return store; - }; - AutoCache::GetInstance().RegCreator(DistributedRdb::RDB_DEVICE_COLLABORATION, creator); - int32_t result = service.SetDistributedTables(param, tables, references, false, DistributedTableType::DISTRIBUTED_DEVICE); @@ -1286,9 +1473,12 @@ HWTEST_F(RdbServiceImplTest, Sync003, TestSize.Level0) param.storeName_ = "Sync003"; RdbService::Option option { DistributedData::GeneralStore::NEARBY_BEGIN }; PredicatesMemo predicates; - + auto [exists, meta] = RdbServiceImpl::LoadStoreMetaData(param); + (void)exists; + RdbServiceImpl::SaveSyncMeta(meta); int32_t result = service.Sync(param, option, predicates, nullptr); EXPECT_EQ(result, RDB_OK); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(meta.GetKeyWithoutPath()), true); } /** diff --git a/services/distributeddataservice/service/test/rdb_service_impl_token_test.cpp b/services/distributeddataservice/service/test/rdb_service_impl_token_test.cpp index 4a49356a4..c8bca0a33 100644 --- a/services/distributeddataservice/service/test/rdb_service_impl_token_test.cpp +++ b/services/distributeddataservice/service/test/rdb_service_impl_token_test.cpp @@ -12,24 +12,24 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include +#include + #include "account/account_delegate.h" -#include "rdb_service_impl.h" -#include "ipc_skeleton.h" -#include "gmock/gmock.h" -#include "mock/access_token_mock.h" #include "bootstrap.h" #include "checker_mock.h" #include "crypto/crypto_manager.h" #include "device_manager_adapter.h" #include "device_matrix.h" +#include "directory/directory_manager.h" +#include "ipc_skeleton.h" #include "metadata/meta_data_manager.h" -#include "metadata/store_meta_data.h" #include "metadata/store_meta_data_local.h" +#include "mock/access_token_mock.h" #include "mock/db_store_mock.h" +#include "rdb_service_impl.h" #include "rdb_types.h" #include "relational_store_manager.h" -#include "gtest/gtest.h" -#include "directory/directory_manager.h" using namespace OHOS::DistributedRdb; using namespace OHOS::DistributedData; using namespace DistributedDB; diff --git a/services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp b/services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp index 0ca8e3b2d..156e2d973 100644 --- a/services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp +++ b/services/distributeddataservice/service/test/udmf_preprocess_utils_mock_test.cpp @@ -12,11 +12,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include -#include "preprocess_utils.h" -#include "gtest/gtest.h" #include "access_token_mock.h" #include "ipc_skeleton.h" +#include "preprocess_utils.h" namespace OHOS::UDMF { using namespace testing; diff --git a/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp b/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp index e188e2284..bceccdb3b 100644 --- a/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp +++ b/services/distributeddataservice/service/test/udmf_run_time_store_test.cpp @@ -14,22 +14,20 @@ */ #define LOG_TAG "UdmfRunTimeStoreTest" +#include #include #include "accesstoken_kit.h" #include "bootstrap.h" #include "device_manager_adapter.h" +#include "directory/directory_manager.h" #include "executor_pool.h" -#include "gtest/gtest.h" -#include "ipc_skeleton.h" #include "kvstore_meta_manager.h" -#include "metadata/meta_data_manager.h" #include "nativetoken_kit.h" #include "preprocess_utils.h" #include "runtime_store.h" #include "text.h" #include "token_setproc.h" -#include "directory_manager.h" using namespace testing::ext; using namespace OHOS::DistributedData; diff --git a/services/distributeddataservice/service/test/udmf_service_impl_test.cpp b/services/distributeddataservice/service/test/udmf_service_impl_test.cpp index 541089c74..de5614d92 100644 --- a/services/distributeddataservice/service/test/udmf_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/udmf_service_impl_test.cpp @@ -12,23 +12,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #define LOG_TAG "UdmfServiceImplTest" #include "udmf_service_impl.h" + +#include + #include "accesstoken_kit.h" -#include "account_delegate.h" +#include "account/account_delegate.h" #include "bootstrap.h" #include "device_manager_adapter.h" #include "executor_pool.h" -#include "gtest/gtest.h" #include "ipc_skeleton.h" #include "kvstore_meta_manager.h" -#include "metadata/meta_data_manager.h" #include "nativetoken_kit.h" #include "preprocess_utils.h" #include "runtime_store.h" -#include "text.h" -#include "plain_text.h" #include "token_setproc.h" using namespace testing::ext; diff --git a/services/distributeddataservice/service/test/udmf_service_stub_mock_test.cpp b/services/distributeddataservice/service/test/udmf_service_stub_mock_test.cpp index e9935eab9..be3444bc5 100644 --- a/services/distributeddataservice/service/test/udmf_service_stub_mock_test.cpp +++ b/services/distributeddataservice/service/test/udmf_service_stub_mock_test.cpp @@ -14,10 +14,11 @@ */ #define LOG_TAG "UdmfServiceStubMockTest" -#include "udmf_service_stub.h" +#include + #include "udmf_service_impl.h" +#include "udmf_service_stub.h" #include "udmf_types_util.h" -#include "gtest/gtest.h" using namespace OHOS::DistributedData; namespace OHOS::UDMF { diff --git a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp index 5a40b23ab..c75c65a54 100644 --- a/services/distributeddataservice/service/test/user_delegate_mock_test.cpp +++ b/services/distributeddataservice/service/test/user_delegate_mock_test.cpp @@ -21,7 +21,6 @@ #include "metadata/meta_data_manager.h" #include "user_delegate.h" - using namespace OHOS::DistributedData; using namespace testing::ext; using namespace testing; diff --git a/services/distributeddataservice/service/test/value_proxy_test.cpp b/services/distributeddataservice/service/test/value_proxy_test.cpp index 469d2230d..5226dca30 100644 --- a/services/distributeddataservice/service/test/value_proxy_test.cpp +++ b/services/distributeddataservice/service/test/value_proxy_test.cpp @@ -375,27 +375,27 @@ HWTEST_F(ValueProxyServiceTest, AssetsOperator001, TestSize.Level0) ValueProxy::Assets proxy3; proxy1.assets_.push_back(ValueProxy::Asset(DistributedDB::Asset { .version = 1, - .status = DistributedData::Asset::Status::STATUS_INSERT, .name = "Asset1", .uri = "uri1", .size = "1", .hash = "hash1", + .status = DistributedData::Asset::Status::STATUS_INSERT, })); proxy2.assets_.push_back(ValueProxy::Asset(DistributedDB::Asset { .version = 2, - .status = DistributedData::Asset::Status::STATUS_NORMAL, .name = "Asset2", .uri = "uri2", .size = "2", .hash = "hash2", + .status = DistributedData::Asset::Status::STATUS_NORMAL, })); proxy2.assets_.push_back(ValueProxy::Asset(DistributedDB::Asset { .version = 3, - .status = DistributedData::Asset::Status::STATUS_NORMAL, .name = "Asset3", .uri = "uri3", .size = "3", .hash = "hash3", + .status = DistributedData::Asset::Status::STATUS_NORMAL, })); // operator "=" same asset case proxy3 = proxy1; @@ -427,19 +427,19 @@ HWTEST_F(ValueProxyServiceTest, AssetOperator001, TestSize.Level0) { ValueProxy::Asset asset1 = DistributedDB::Asset { .version = 1, - .status = DistributedData::Asset::Status::STATUS_INSERT, .name = "Asset1", .uri = "uri1", .size = "1", .hash = "hash1", + .status = DistributedData::Asset::Status::STATUS_INSERT, }; ValueProxy::Asset asset2 = DistributedDB::Asset { .version = 2, - .status = DistributedData::Asset::Status::STATUS_NORMAL, .name = "Asset2", .uri = "uri2", .size = "2", .hash = "hash2", + .status = DistributedData::Asset::Status::STATUS_NORMAL, }; ValueProxy::Asset asset3 = asset1; DistributedData::Asset asset = asset3; -- Gitee From 58bc03b04fb37fbf11434b176682857769506015 Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Fri, 5 Sep 2025 11:47:56 +0800 Subject: [PATCH 2/4] fixed ut coverage Signed-off-by: Sven Wang --- .../framework/test/cloud_test.cpp | 132 ++++++++++++++++ .../service/test/BUILD.gn | 1 + .../service/test/rdb_service_impl_test.cpp | 145 +++++++++++------- .../service/test/rdb_types_utils_test.cpp | 102 ++++++++++++ 4 files changed, 322 insertions(+), 58 deletions(-) create mode 100644 services/distributeddataservice/service/test/rdb_types_utils_test.cpp diff --git a/services/distributeddataservice/framework/test/cloud_test.cpp b/services/distributeddataservice/framework/test/cloud_test.cpp index 57e4ab7ec..a9cd111e9 100644 --- a/services/distributeddataservice/framework/test/cloud_test.cpp +++ b/services/distributeddataservice/framework/test/cloud_test.cpp @@ -546,4 +546,136 @@ HWTEST_F(CloudEventTest, GetEventId, TestSize.Level0) auto ret = event.GetEventId(); EXPECT_EQ(ret, evtId); } + +/** +* @tc.name: GetTableNames_001 +* @tc.desc: get table names no shared tables +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudEventTest, GetTableNames_001, TestSize.Level0) +{ + Database database; + for (int i = 0; i < 5; ++i) { + Table table; + table.name = "table" + std::to_string(i); + database.tables.push_back(std::move(table)); + } + auto tables = database.GetTableNames(); + std::vector tagTable = { "table0", "table1", "table2", "table3", "table4" }; + EXPECT_EQ(tables, tagTable); +} + +/** +* @tc.name: GetTableNames_002 +* @tc.desc: get table names with shared tables +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudEventTest, GetTableNames_002, TestSize.Level0) +{ + Database database; + for (int i = 0; i < 5; ++i) { + Table table; + table.name = "table" + std::to_string(i); + table.sharedTableName = "shared" + std::to_string(i); + database.tables.push_back(std::move(table)); + } + auto tables = database.GetTableNames(); + std::vector tagTable = { "table0", "shared0", "table1", "shared1", "table2", "shared2", "table3", + "shared3", "table4", "shared4" }; + EXPECT_EQ(tables, tagTable); +} + +/** +* @tc.name: GetSyncTables_001 +* @tc.desc: get p2p sync table names +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudEventTest, GetSyncTables_001, TestSize.Level0) +{ + Database database; + for (int i = 0; i < 5; ++i) { + Table table; + table.name = "table" + std::to_string(i); + table.sharedTableName = "shared" + std::to_string(i); + auto &fields = (i % 2 == 0) ? table.deviceSyncFields : table.cloudSyncFields; + fields.push_back("field" + std::to_string(i)); + database.tables.push_back(std::move(table)); + } + auto tables = database.GetSyncTables(); + std::vector tagTable = { "table0", "table2", "table4" }; + EXPECT_EQ(tables, tagTable); +} + +/** +* @tc.name: GetSyncTables_002 +* @tc.desc: get p2p sync table names w +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudEventTest, GetSyncTables_002, TestSize.Level0) +{ + Database database; + auto tables = database.GetSyncTables(); + std::vector tagTable; + EXPECT_EQ(tables, tagTable); + for (int i = 0; i < 5; ++i) { + Table table; + table.name = "table" + std::to_string(i); + table.sharedTableName = "shared" + std::to_string(i); + database.tables.push_back(std::move(table)); + } + tables = database.GetSyncTables(); + EXPECT_EQ(tables, tagTable); +} + +/** +* @tc.name: GetSyncTables_001 +* @tc.desc: get p2p sync table names w +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudEventTest, GetCloudTables_001, TestSize.Level0) +{ + Database database; + for (int i = 0; i < 5; ++i) { + Table table; + table.name = "table" + std::to_string(i); + table.sharedTableName = "shared" + std::to_string(i); + auto &fields = (i % 2 == 0) ? table.deviceSyncFields : table.cloudSyncFields; + fields.push_back("field" + std::to_string(i)); + database.tables.push_back(std::move(table)); + } + auto tables = database.GetCloudTables(); + std::vector tagTable = { "table1", "shared1", "table3", "shared3" }; + EXPECT_EQ(tables, tagTable); +} + +/** +* @tc.name: GetSyncTables_002 +* @tc.desc: get p2p sync table names w +* @tc.type: FUNC +* @tc.require: +* @tc.author: +*/ +HWTEST_F(CloudEventTest, GetCloudTables_002, TestSize.Level0) +{ + Database database; + for (int i = 0; i < 5; ++i) { + Table table; + table.name = "table" + std::to_string(i); + table.sharedTableName = "shared" + std::to_string(i); + database.tables.push_back(std::move(table)); + } + auto tables = database.GetCloudTables(); + std::vector tagTable; + EXPECT_EQ(tables, tagTable); +} } // namespace OHOS::Test diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 38066f799..1d5003ccd 100644 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -654,6 +654,7 @@ ohos_unittest("RdbServiceImplTest") { "mock/db_change_data_mock.cpp", "mock/db_store_mock.cpp", "rdb_service_impl_test.cpp", + "rdb_types_utils_test.cpp", ] include_dirs = [ diff --git a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp index 95e9a4ba7..51b81568d 100644 --- a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp @@ -478,7 +478,7 @@ HWTEST_F(RdbServiceImplTest, DoSync002, TestSize.Level0) HWTEST_F(RdbServiceImplTest, IsNeedMetaSync001, TestSize.Level0) { EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKeyWithoutPath(), metaData_, false), true); - std::vector devices = {DmAdapter::GetInstance().ToUUID(metaData_.deviceId)}; + std::vector devices = { DmAdapter::GetInstance().ToUUID(metaData_.deviceId) }; RdbServiceImpl service; bool result = service.IsNeedMetaSync(metaData_, devices); @@ -500,7 +500,7 @@ HWTEST_F(RdbServiceImplTest, IsNeedMetaSync002, TestSize.Level0) EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(std::string(capKey.begin(), capKey.end()), capMetaData), true); EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKeyWithoutPath(), metaData_, false), true); - std::vector devices = {DmAdapter::GetInstance().ToUUID(metaData_.deviceId)}; + std::vector devices = { DmAdapter::GetInstance().ToUUID(metaData_.deviceId) }; RdbServiceImpl service; bool result = service.IsNeedMetaSync(metaData_, devices); @@ -518,8 +518,8 @@ HWTEST_F(RdbServiceImplTest, IsNeedMetaSync002, TestSize.Level0) HWTEST_F(RdbServiceImplTest, ProcessResult001, TestSize.Level0) { RdbServiceImpl service; - std::map results = {{"device1", static_cast(DBStatus::OK)}, - {"device2", static_cast(DBStatus::OK)}}; + std::map results = { { "device1", static_cast(DBStatus::OK) }, + { "device2", static_cast(DBStatus::OK) } }; auto result = service.ProcessResult(results); @@ -537,9 +537,8 @@ HWTEST_F(RdbServiceImplTest, ProcessResult001, TestSize.Level0) HWTEST_F(RdbServiceImplTest, ProcessResult002, TestSize.Level0) { RdbServiceImpl service; - std::map results = {{"device1", static_cast(DBStatus::OK)}, - {"device2", static_cast(DBStatus::DB_ERROR)}, - {"device3", static_cast(DBStatus::OK)}}; + std::map results = { { "device1", static_cast(DBStatus::OK) }, + { "device2", static_cast(DBStatus::DB_ERROR) }, { "device3", static_cast(DBStatus::OK) } }; auto result = service.ProcessResult(results); @@ -584,10 +583,10 @@ HWTEST_F(RdbServiceImplTest, DoCompensateSync001, TestSize.Level0) bindInfo.user = metaData_.uid; bindInfo.storeName = TEST_STORE; bindInfo.tableName = "test_table"; - bindInfo.primaryKey = {{"key1", "value1"}, {"key2", "value2"}}; + bindInfo.primaryKey = { { "key1", "value1" }, { "key2", "value2" } }; BindEvent event(eventId, std::move(bindInfo)); - EventCenter::GetInstance().Subscribe(CloudEvent::LOCAL_CHANGE, [this] (const Event &event) { + EventCenter::GetInstance().Subscribe(CloudEvent::LOCAL_CHANGE, [this](const Event &event) { auto &evt = static_cast(event); auto mode = evt.GetMode(); EXPECT_EQ(GeneralStore::GetPriorityLevel(GeneralStore::GetHighMode(static_cast(mode))), 1); @@ -644,7 +643,7 @@ HWTEST_F(RdbServiceImplTest, ReportStatistic002, TestSize.Level0) HWTEST_F(RdbServiceImplTest, GetReuseDevice001, TestSize.Level0) { RdbServiceImpl service; - std::vector devices = {"device1"}; + std::vector devices = { "device1" }; StoreMetaData metaData; auto result = service.GetReuseDevice(devices, metaData); EXPECT_EQ(result.size(), 0); @@ -660,9 +659,9 @@ HWTEST_F(RdbServiceImplTest, GetReuseDevice001, TestSize.Level0) HWTEST_F(RdbServiceImplTest, DoAutoSync001, TestSize.Level0) { RdbServiceImpl service; - std::vector devices = {"device1"}; + std::vector devices = { "device1" }; StoreMetaData metaData; - std::vector tables = {"table1"}; + std::vector tables = { "table1" }; auto result = service.DoAutoSync(devices, metaData, tables); EXPECT_EQ(result, RDB_ERROR); @@ -686,9 +685,9 @@ HWTEST_F(RdbServiceImplTest, DoAutoSync002, TestSize.Level0) EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaMapping.GetKey(), metaMapping, true), true); RdbServiceImpl service; - std::vector devices = {"device1"}; + std::vector devices = { "device1" }; DistributedData::Database database; - std::vector tables = {"table1"}; + std::vector tables = { "table1" }; database.bundleName = "bundleName"; database.name = "storeName"; database.user = "100"; @@ -708,18 +707,18 @@ HWTEST_F(RdbServiceImplTest, DoAutoSync002, TestSize.Level0) HWTEST_F(RdbServiceImplTest, OnReady_DoAutoSync001, TestSize.Level0) { RdbServiceImpl service; - std::vector devices = {"device1"}; + std::vector devices = { "device1" }; DistributedData::Database database; database.name = TEST_STORE; DistributedData::Table table1; table1.name = "table1"; - table1.deviceSyncFields = {"field1", "field2"}; + table1.deviceSyncFields = { "field1", "field2" }; DistributedData::Table table2; table2.name = "table2"; table2.deviceSyncFields = {}; - database.tables = {table1, table2}; + database.tables = { table1, table2 }; auto [exists, metaData] = RdbServiceImpl::LoadSyncMeta(database); EXPECT_EQ(exists, false); auto result = service.DoAutoSync(devices, metaData, database.GetSyncTables()); @@ -902,11 +901,11 @@ HWTEST_F(RdbServiceImplTest, SpecialChannel003, TestSize.Level0) EXPECT_NE(executors, nullptr); RdbServiceImpl service; service.OnInitialize(); - service.OnBind({.executors = executors}); + service.OnBind({ .executors = executors }); auto result = service.IsSpecialChannel(TEST_SYNC_DEVICE); EXPECT_EQ(result, true); executors->Remove(service.saveChannelsTask_); - service.OnBind({.executors = nullptr}); + service.OnBind({ .executors = nullptr }); executors = nullptr; } @@ -987,8 +986,8 @@ HWTEST_F(RdbServiceImplTest, AfterOpen003, TestSize.Level0) RdbSyncerParam param; param.bundleName_ = metaData_.bundleName; param.storeName_ = metaData_.storeId; - param.tokenIds_ = {123}; - param.uids_ = {123}; + param.tokenIds_ = { 123 }; + param.uids_ = { 123 }; param.permissionNames_ = {}; AppIDMetaData appIdMeta; appIdMeta.bundleName = metaData_.bundleName; @@ -999,11 +998,11 @@ HWTEST_F(RdbServiceImplTest, AfterOpen003, TestSize.Level0) int32_t result = service.AfterOpen(param); EXPECT_EQ(result, RDB_OK); EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKeyWithoutPath(), false), true); - param.tokenIds_ = {123}; - param.uids_ = {456}; + param.tokenIds_ = { 123 }; + param.uids_ = { 456 }; result = service.AfterOpen(param); EXPECT_EQ(result, RDB_OK); - param.permissionNames_ = {"com.example.myapplication"}; + param.permissionNames_ = { "com.example.myapplication" }; result = service.AfterOpen(param); EXPECT_EQ(result, RDB_OK); @@ -1028,7 +1027,7 @@ HWTEST_F(RdbServiceImplTest, AfterOpen004, TestSize.Level0) param.bundleName_ = metaData_.bundleName; param.storeName_ = metaData_.storeId; int32_t result = service.AfterOpen(param); - + EXPECT_EQ(result, RDB_OK); EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKeyWithoutPath(), false), true); } @@ -1099,6 +1098,41 @@ HWTEST_F(RdbServiceImplTest, NotifyDataChange003, TestSize.Level0) EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData.GetKey(), true), true); } +/** + * @tc.name: NotifyDataChange004 + * @tc.desc: Test NotifyDataChange when Check pass. + * @tc.type: FUNC + */ +HWTEST_F(RdbServiceImplTest, NotifyDataChange004, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + param.storeName_ = metaData_.storeId; + param.bundleName_ = metaData_.bundleName; + param.user_ = metaData_.user; + param.hapName_ = metaData_.hapName; + param.customDir_ = metaData_.customDir; + param.area_ = metaData_.area; + RdbChangedData rdbChangedData; + RdbNotifyConfig rdbNotifyConfig; + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, true), true); + Database database; + database.bundleName = metaData_.bundleName; + database.name = metaData_.storeId; + database.user = metaData_.user; + database.deviceId = metaData_.deviceId; + database.autoSyncType = AutoSyncType::SYNC_ON_CHANGE_READY; + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(database.GetKey(), database, true), true); + rdbNotifyConfig.delay_ = 0; + int32_t result = service.NotifyDataChange(param, rdbChangedData, rdbNotifyConfig); + EXPECT_EQ(result, RDB_OK); + rdbNotifyConfig.delay_ = DELY_TIME; + result = service.NotifyDataChange(param, rdbChangedData, rdbNotifyConfig); + EXPECT_EQ(result, RDB_OK); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), true), true); + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(database.GetKey(), true), true); +} + /** * @tc.name: SetSearchable001 * @tc.desc: Test SetSearchable when CheckAccess fails. @@ -1363,8 +1397,7 @@ HWTEST_F(RdbServiceImplTest, SetDistributedTables002, TestSize.Level0) std::vector references; int32_t result = - service.SetDistributedTables(param, tables, references, false, - DistributedTableType::DISTRIBUTED_SEARCH); + service.SetDistributedTables(param, tables, references, false, DistributedTableType::DISTRIBUTED_SEARCH); EXPECT_EQ(result, RDB_OK); } @@ -1387,8 +1420,7 @@ HWTEST_F(RdbServiceImplTest, SetDistributedTables003, TestSize.Level0) std::vector references; int32_t result = - service.SetDistributedTables(param, tables, references, false, - DistributedTableType::DISTRIBUTED_SEARCH); + service.SetDistributedTables(param, tables, references, false, DistributedTableType::DISTRIBUTED_SEARCH); EXPECT_EQ(result, RDB_ERROR); } @@ -1413,8 +1445,7 @@ HWTEST_F(RdbServiceImplTest, SetDistributedTables004, TestSize.Level0) ASSERT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true), true); int32_t result = - service.SetDistributedTables(param, tables, references, false, - DistributedTableType::DISTRIBUTED_DEVICE); + service.SetDistributedTables(param, tables, references, false, DistributedTableType::DISTRIBUTED_DEVICE); EXPECT_EQ(result, RDB_OK); ASSERT_EQ(MetaDataManager::GetInstance().DelMeta(meta.GetKey(), true), true); } @@ -1430,7 +1461,7 @@ HWTEST_F(RdbServiceImplTest, Sync001, TestSize.Level0) { RdbServiceImpl service; RdbSyncerParam param; - RdbService::Option option {}; + RdbService::Option option{}; PredicatesMemo predicates; int32_t result = service.Sync(param, option, predicates, nullptr); @@ -1451,7 +1482,7 @@ HWTEST_F(RdbServiceImplTest, Sync002, TestSize.Level0) param.bundleName_ = TEST_BUNDLE; param.storeName_ = TEST_STORE; param.hapName_ = "test/test"; - RdbService::Option option {}; + RdbService::Option option{}; PredicatesMemo predicates; int32_t result = service.Sync(param, option, predicates, nullptr); @@ -1471,7 +1502,7 @@ HWTEST_F(RdbServiceImplTest, Sync003, TestSize.Level0) RdbSyncerParam param; param.bundleName_ = TEST_BUNDLE; param.storeName_ = "Sync003"; - RdbService::Option option { DistributedData::GeneralStore::NEARBY_BEGIN }; + RdbService::Option option{ DistributedData::GeneralStore::NEARBY_BEGIN }; PredicatesMemo predicates; auto [exists, meta] = RdbServiceImpl::LoadStoreMetaData(param); (void)exists; @@ -1494,14 +1525,13 @@ HWTEST_F(RdbServiceImplTest, Sync004, TestSize.Level0) RdbSyncerParam param; param.bundleName_ = TEST_BUNDLE; param.storeName_ = "Sync004"; - RdbService::Option option { DistributedData::GeneralStore::CLOUD_BEGIN }; + RdbService::Option option{ DistributedData::GeneralStore::CLOUD_BEGIN }; PredicatesMemo predicates; int32_t result = service.Sync(param, option, predicates, nullptr); EXPECT_EQ(result, RDB_OK); } - /** * @tc.name: QuerySharingResource001 * @tc.desc: Test QuerySharingResource when CheckParam not pass. @@ -1599,7 +1629,7 @@ HWTEST_F(RdbServiceImplTest, Subscribe001, TestSize.Level0) { RdbServiceImpl service; RdbSyncerParam param; - SubscribeOption option {}; + SubscribeOption option{}; option.mode = SubscribeMode::SUBSCRIBE_MODE_MAX; int32_t result = service.Subscribe(param, option, nullptr); @@ -1617,7 +1647,7 @@ HWTEST_F(RdbServiceImplTest, UnSubscribe001, TestSize.Level0) { RdbServiceImpl service; RdbSyncerParam param; - SubscribeOption option {}; + SubscribeOption option{}; option.mode = SubscribeMode::SUBSCRIBE_MODE_MAX; int32_t result = service.UnSubscribe(param, option, nullptr); @@ -1853,7 +1883,7 @@ HWTEST_F(RdbServiceImplTest, VerifyPromiseInfo002, TestSize.Level0) StoreMetaDataLocal localMeta; auto tokenId = IPCSkeleton::GetCallingTokenID(); localMeta.isAutoSync = true; - localMeta.promiseInfo.tokenIds = {tokenId}; + localMeta.promiseInfo.tokenIds = { tokenId }; localMeta.promiseInfo.uids = {}; localMeta.promiseInfo.permissionNames = {}; @@ -1892,7 +1922,7 @@ HWTEST_F(RdbServiceImplTest, VerifyPromiseInfo003, TestSize.Level0) StoreMetaDataLocal localMeta; auto tokenId = IPCSkeleton::GetCallingTokenID(); localMeta.isAutoSync = true; - localMeta.promiseInfo.tokenIds = {tokenId}; + localMeta.promiseInfo.tokenIds = { tokenId }; localMeta.promiseInfo.uids = {}; localMeta.promiseInfo.permissionNames = {}; metaData_.dataDir = "path"; @@ -1977,7 +2007,7 @@ HWTEST_F(RdbServiceImplTest, CheckParam002, TestSize.Level0) result = service.IsValidParam(param); EXPECT_EQ(result, false); - + param.hapName_ = "test\\..test"; result = service.IsValidParam(param); @@ -2220,7 +2250,7 @@ HWTEST_F(RdbServiceImplTest, Delete_001, TestSize.Level1) EXPECT_EQ(errCode, RDB_ERROR); param.bundleName_ = "bundleName"; param.storeName_ = "storeName"; - param.user_ = "0"; + param.user_ = "0"; errCode = service.Delete(param); EXPECT_EQ(errCode, RDB_OK); } @@ -2259,7 +2289,7 @@ HWTEST_F(RdbServiceImplTest, Delete_002, TestSize.Level1) meta2.user = "0"; meta2.bundleName = "bundleName"; meta2.storeId = "storeName"; - meta2.dataDir ="path2"; + meta2.dataDir = "path2"; meta2.instanceId = 1; EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta2.GetKey(), meta2, true), true); @@ -2311,7 +2341,7 @@ HWTEST_F(RdbServiceImplTest, Delete_003, TestSize.Level1) meta2.user = "0"; meta2.bundleName = "bundleName"; meta2.storeId = "storeName"; - meta2.dataDir ="path2"; + meta2.dataDir = "path2"; EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta2.GetKey(), meta2, true), true); RdbServiceImpl service; @@ -2414,7 +2444,6 @@ HWTEST_F(RdbServiceImplTest, RegisterEvent_002, TestSize.Level1) EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaMapping.GetKey(), true), true); } - /** * @tc.name: RegisterEvent_003 * @tc.desc: Test RegisterEvent_003. @@ -2424,8 +2453,8 @@ HWTEST_F(RdbServiceImplTest, RegisterEvent_003, TestSize.Level1) { StoreMetaMapping metaMapping; InitMapping(metaMapping); - metaMapping.cloudPath ="path1"; - metaMapping.dataDir ="path"; + metaMapping.cloudPath = "path1"; + metaMapping.dataDir = "path"; EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaMapping.GetKey(), metaMapping, true), true); StoreMetaData meta; @@ -2433,7 +2462,7 @@ HWTEST_F(RdbServiceImplTest, RegisterEvent_003, TestSize.Level1) meta.user = "100"; meta.bundleName = "bundleName"; meta.storeId = "storeName"; - meta.dataDir ="path1"; + meta.dataDir = "path1"; EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta, true), true); RdbServiceImpl service; DistributedData::StoreInfo storeInfo; @@ -2459,8 +2488,8 @@ HWTEST_F(RdbServiceImplTest, RegisterEvent_004, TestSize.Level1) { StoreMetaMapping metaMapping; InitMapping(metaMapping); - metaMapping.cloudPath ="path"; - metaMapping.dataDir ="path"; + metaMapping.cloudPath = "path"; + metaMapping.dataDir = "path"; metaMapping.storeType = StoreMetaData::STORE_KV_BEGIN; EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaMapping.GetKey(), metaMapping, true), true); @@ -2487,8 +2516,8 @@ HWTEST_F(RdbServiceImplTest, RegisterEvent_005, TestSize.Level1) { StoreMetaMapping metaMapping; InitMapping(metaMapping); - metaMapping.cloudPath ="path"; - metaMapping.dataDir ="path"; + metaMapping.cloudPath = "path"; + metaMapping.dataDir = "path"; metaMapping.storeType = StoreMetaData::STORE_OBJECT_BEGIN; EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaMapping.GetKey(), metaMapping, true), true); @@ -2515,8 +2544,8 @@ HWTEST_F(RdbServiceImplTest, RegisterEvent_006, TestSize.Level1) { StoreMetaMapping metaMapping; InitMapping(metaMapping); - metaMapping.cloudPath ="path1"; - metaMapping.dataDir ="path"; + metaMapping.cloudPath = "path1"; + metaMapping.dataDir = "path"; EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaMapping.GetKey(), metaMapping, true), true); RdbServiceImpl service; @@ -2546,8 +2575,8 @@ HWTEST_F(RdbServiceImplTest, QuerySharingResource_PermissionDenied_001, TestSize RdbSyncerParam param; // param.bundleName_ and param.storeName_ left empty to trigger CheckAccess failure PredicatesMemo predicates; - predicates.tables_ = {"table1"}; - std::vector columns = {"col1", "col2"}; + predicates.tables_ = { "table1" }; + std::vector columns = { "col1", "col2" }; auto result = service.QuerySharingResource(param, predicates, columns); EXPECT_EQ(result.first, RDB_ERROR); @@ -2568,8 +2597,8 @@ HWTEST_F(RdbServiceImplTest, QuerySharingResource_PermissionDenied_002, TestSize param.bundleName_ = TEST_BUNDLE; param.storeName_ = TEST_STORE; PredicatesMemo predicates; - predicates.tables_ = {"table1"}; - std::vector columns = {"col1", "col2"}; + predicates.tables_ = { "table1" }; + std::vector columns = { "col1", "col2" }; auto result = service.QuerySharingResource(param, predicates, columns); EXPECT_EQ(result.first, RDB_ERROR); diff --git a/services/distributeddataservice/service/test/rdb_types_utils_test.cpp b/services/distributeddataservice/service/test/rdb_types_utils_test.cpp new file mode 100644 index 000000000..aaca18bd3 --- /dev/null +++ b/services/distributeddataservice/service/test/rdb_types_utils_test.cpp @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "rdb_types_utils.h" + +#include +using namespace testing::ext; +using namespace testing; +using namespace OHOS::DistributedRdb; +namespace OHOS::Test { +class RdbTypesUtilsTest : public testing::Test { +public: + static void SetUpTestCase(void); + static void TearDownTestCase(void); + void SetUp(); + void TearDown(); +}; +void RdbTypesUtilsTest::SetUpTestCase(void) {}; +void RdbTypesUtilsTest::TearDownTestCase(void) {}; +void RdbTypesUtilsTest::SetUp() {}; +void RdbTypesUtilsTest::TearDown() {}; +/** +* @tc.name: GetSearchableTables_001 +* @tc.desc: get searchable tables from RdbChangedData. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(RdbTypesUtilsTest, GetSearchableTables_001, TestSize.Level0) +{ + RdbChangedData changedData; + changedData.tableData = { + { "table1", { .isTrackedDataChange = true } }, + { "table2", { .isP2pSyncDataChange = true } }, + { "table3", { .isP2pSyncDataChange = true } }, + { "table4", { .isTrackedDataChange = true } }, + }; + auto searchableTables = RdbTypesUtils::GetSearchableTables(changedData); + std::vector tagTables = { "table1", "table4" }; + EXPECT_EQ(searchableTables, tagTables); +} + +/** +* @tc.name: GetP2PTables_001 +* @tc.desc: get p2p sync tables from RdbChangedData. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(RdbTypesUtilsTest, GetP2PTables_001, TestSize.Level0) +{ + RdbChangedData changedData; + changedData.tableData = { + { "table1", { .isTrackedDataChange = true } }, + { "table2", { .isP2pSyncDataChange = true } }, + { "table3", { .isP2pSyncDataChange = true } }, + { "table4", { .isTrackedDataChange = true } }, + }; + auto p2pTables = RdbTypesUtils::GetP2PTables(changedData); + std::vector tagTables = { "table2", "table3" }; + EXPECT_EQ(p2pTables, tagTables); +} + +/** +* @tc.name: Convert_001 +* @tc.desc: convert DistributedRdb Reference to DistributedData::Reference. +* @tc.type: FUNC +* @tc.require: +* @tc.author: Sven Wang +*/ +HWTEST_F(RdbTypesUtilsTest, Convert_001, TestSize.Level0) +{ + std::vector references = { + { "srcTable", "tagTable", { {"uuid", "srcId"} } }, + { "srcTable1", "tagTable1", { {"uuid", "srcId"} } }, + { "srcTable2", "tagTable2", { {"uuid", "srcId"} } }, + }; + auto relations = RdbTypesUtils::Convert(references); + std::vector tagRelations = { + { "srcTable", "tagTable", { { "uuid", "srcId" } } }, + { "srcTable1", "tagTable1", { { "uuid", "srcId" } } }, + { "srcTable2", "tagTable2", { { "uuid", "srcId" } } }, + }; + EXPECT_EQ(relations.size(), tagRelations.size()); + for (int i = 0; i < tagRelations.size(); ++i) { + EXPECT_EQ(relations[i].sourceTable, tagRelations[i].sourceTable); + EXPECT_EQ(relations[i].targetTable, tagRelations[i].targetTable); + EXPECT_EQ(relations[i].refFields, tagRelations[i].refFields); + } +} +} \ No newline at end of file -- Gitee From fb3583776df296e2d0a56d91bc2d28d89e4bcc51 Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Fri, 5 Sep 2025 14:28:05 +0800 Subject: [PATCH 3/4] fixed ai review Signed-off-by: Sven Wang --- .../distributeddataservice/framework/cloud/schema_meta.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/framework/cloud/schema_meta.cpp b/services/distributeddataservice/framework/cloud/schema_meta.cpp index 4930c0902..287950eb5 100644 --- a/services/distributeddataservice/framework/cloud/schema_meta.cpp +++ b/services/distributeddataservice/framework/cloud/schema_meta.cpp @@ -80,7 +80,8 @@ std::vector Database::GetSyncTables() const std::vector Database::GetCloudTables() const { std::vector tableNames; - tableNames.reserve(tables.size()); + // reserve * 2 for the shared table names + tableNames.reserve(tables.size() * 2); for (auto &table : tables) { if (table.cloudSyncFields.empty()) { continue; -- Gitee From 9008ac6c2fd50ca8593b4e127f6f18a6021167d7 Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Fri, 5 Sep 2025 17:03:42 +0800 Subject: [PATCH 4/4] fixed ut branch coverage Signed-off-by: Sven Wang --- .../service/rdb/rdb_service_impl.cpp | 1 - .../service/test/mock/general_store_mock.cpp | 8 +++ .../service/test/rdb_service_impl_test.cpp | 60 +++++++++++++++++++ 3 files changed, 68 insertions(+), 1 deletion(-) diff --git a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 97c2ea41f..a22f43ddb 100644 --- a/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -1599,7 +1599,6 @@ int32_t RdbServiceImpl::SetSearchable(const RdbSyncerParam ¶m, bool isSearch if (!exists) { ZLOGW("bundleName:%{public}s, storeName:%{public}s. no meta", param.bundleName_.c_str(), Anonymous::Change(param.storeName_).c_str()); - return RDB_NO_META; } SetSearchableEvent::EventInfo eventInfo {}; diff --git a/services/distributeddataservice/service/test/mock/general_store_mock.cpp b/services/distributeddataservice/service/test/mock/general_store_mock.cpp index 7fc984a89..f09386987 100644 --- a/services/distributeddataservice/service/test/mock/general_store_mock.cpp +++ b/services/distributeddataservice/service/test/mock/general_store_mock.cpp @@ -72,6 +72,14 @@ std::pair> GeneralStoreMock::Query(const std::s std::pair GeneralStoreMock::Sync(const Devices &devices, GenQuery &query, DetailAsync async, const SyncParam &syncParm) { + if (!async) { + return { GeneralError::E_OK, 0 }; + } + std::map details; + for (auto &device : devices) { + details[device] = { .progress = SYNC_FINISH, .code = 0, .dbCode = 0 }; + } + async(details); return { GeneralError::E_OK, 0 }; } diff --git a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp index 51b81568d..148ef2d41 100644 --- a/services/distributeddataservice/service/test/rdb_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/rdb_service_impl_test.cpp @@ -468,6 +468,31 @@ HWTEST_F(RdbServiceImplTest, DoSync002, TestSize.Level0) EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKeyWithoutPath(), false), true); } +/** + * @tc.name: DoSync003 + * @tc.desc: Test DoSync when meta sync with device. + * @tc.type: FUNC + * @tc.require: + * @tc.author: Sven Wang + */ +HWTEST_F(RdbServiceImplTest, DoSync003, TestSize.Level0) +{ + EXPECT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKeyWithoutPath(), metaData_, false), true); + + RdbServiceImpl service; + RdbService::Option option; + option.mode = DistributedData::GeneralStore::AUTO_SYNC_MODE; + option.seqNum = 1; + + PredicatesMemo predicates; + AsyncDetail async; + predicates.devices_ = { TEST_SYNC_DEVICE }; + auto result = service.DoSync(metaData_, option, predicates, async); + EXPECT_EQ(result, RDB_OK); + + EXPECT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKeyWithoutPath(), false), true); +} + /** * @tc.name: IsNeedMetaSync001 * @tc.desc: Test IsNeedMetaSync when LoadMeta fails for CapMetaData. @@ -1450,6 +1475,41 @@ HWTEST_F(RdbServiceImplTest, SetDistributedTables004, TestSize.Level0) ASSERT_EQ(MetaDataManager::GetInstance().DelMeta(meta.GetKey(), true), true); } +/** + * @tc.name: SetDistributedTables005 + * @tc.desc: Test SetDistributedTables when type is device. + * @tc.type: FUNC + * @tc.require: + * @tc.author: Sven Wang + */ +HWTEST_F(RdbServiceImplTest, SetDistributedTables005, TestSize.Level0) +{ + RdbServiceImpl service; + RdbSyncerParam param; + param.bundleName_ = metaData_.bundleName; + param.storeName_ = metaData_.storeId; + param.type_ = metaData_.storeType; + param.area_ = metaData_.area; + param.level_ = metaData_.securityLevel; + param.isEncrypt_ = metaData_.isEncrypt; + ASSERT_EQ(MetaDataManager::GetInstance().SaveMeta(metaData_.GetKey(), metaData_, true), true); + auto result = service.SetDistributedTables(param, {}, {}, false, DistributedTableType::DISTRIBUTED_DEVICE); + EXPECT_EQ(result, RDB_OK); + Database database; + database.bundleName = metaData_.bundleName; + database.name = metaData_.storeId; + database.user = metaData_.user; + ASSERT_EQ(MetaDataManager::GetInstance().SaveMeta(database.GetKey(), database, true), true); + result = service.SetDistributedTables(param, {}, {}, false, DistributedTableType::DISTRIBUTED_DEVICE); + + EXPECT_EQ(result, RDB_OK); + StoreMetaMapping metaMapping(metaData_); + ASSERT_EQ(MetaDataManager::GetInstance().DelMeta(metaMapping.GetKey(), true), true); + ASSERT_EQ(MetaDataManager::GetInstance().DelMeta(database.GetKey(), true), true); + ASSERT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKey(), true), true); + ASSERT_EQ(MetaDataManager::GetInstance().DelMeta(metaData_.GetKeyWithoutPath()), true); +} + /** * @tc.name: Sync001 * @tc.desc: Test Sync when CheckAccess not pass. -- Gitee