From bc8e054ae154fe52c627783a9f97063ee808191a Mon Sep 17 00:00:00 2001 From: htt1997 Date: Fri, 15 Sep 2023 14:02:39 +0800 Subject: [PATCH] update Signed-off-by: htt1997 --- .../include/adaptor/object_service.h | 38 +++ .../include/common/string_utils.h | 1 - .../adaptor/distributed_object_store_impl.cpp | 1 + .../adaptor/flat_object_storage_engine.cpp | 4 - .../src/communicator/app_pipe_mgr.cpp | 4 - .../include/mock_app_device_change_listener.h | 1 - .../jskitsimpl/include/adaptor/js_common.h | 62 ++--- .../jskitsimpl/include/common/js_util.h | 4 +- .../jskitsimpl/include/common/napi_queue.h | 4 +- .../src/adaptor/js_distributedobject.cpp | 108 ++++----- .../src/adaptor/js_distributedobjectstore.cpp | 196 +++++++-------- .../jskitsimpl/src/adaptor/js_module_init.cpp | 2 +- .../src/adaptor/js_object_wrapper.cpp | 4 - .../jskitsimpl/src/adaptor/js_watcher.cpp | 32 ++- .../jskitsimpl/src/adaptor/notifier_impl.cpp | 4 - .../jskitsimpl/src/common/js_util.cpp | 9 +- .../jskitsimpl/src/common/napi_queue.cpp | 18 +- data_share/bundle.json | 1 - .../napi/common/include/datashare_js_utils.h | 2 +- .../include/datashare_predicates_proxy.h | 6 +- .../include/datashare_result_set_proxy.h | 6 +- .../include/napi_datashare_values_bucket.h | 6 +- .../js/napi/dataShare/include/async_call.h | 6 +- .../dataShare/include/data_share_common.h | 6 +- .../include/napi_datashare_inner_observer.h | 6 +- .../dataShare/src/native_datashare_module.cpp | 4 +- .../js/napi/observer/include/napi_observer.h | 6 +- .../include/napi_subscriber_manager.h | 6 +- .../consumer/src/datashare_connection.cpp | 2 + .../provider/include/datashare_uv_queue.h | 6 +- .../include/js_datashare_ext_ability.h | 6 +- .../src/js_datashare_ext_ability_context.cpp | 2 +- data_share/interfaces/inner_api/BUILD.gn | 4 +- .../src/main/ets/MainAbility/MainAbility.ts | 60 ++++- .../include/mediadatashare_unit_test.h | 3 +- .../src/errorcode_test.cpp | 12 +- .../mediadatashare_test/src/join_test.cpp | 17 +- .../src/mediadatashare_unit_test.cpp | 14 +- .../src/slientaccess_test.cpp | 13 +- .../src/process_communicator_impl.cpp | 4 +- .../unittest/device_manager_adapter_test.cpp | 2 +- .../communicator/device_manager_adapter.h | 2 +- .../distributeddataservice/app/BUILD.gn | 3 + .../app/src/flowctrl_manager/BUILD.gn | 1 + .../app/src/kvstore_data_service.cpp | 105 +++++--- .../app/src/kvstore_data_service.h | 6 +- .../app/src/kvstore_data_service_stub.cpp | 91 +++++++ .../app/src/kvstore_data_service_stub.h | 39 +++ .../app/src/uninstaller/BUILD.gn | 1 + .../distributeddataservice/app/test/BUILD.gn | 5 + .../fuzztest/dataservicestub_fuzzer/BUILD.gn | 3 + .../test/unittest/session_manager_test.cpp | 2 +- .../distributeddataservice/framework/BUILD.gn | 1 + .../framework/cloud/cloud_event.cpp | 2 +- .../framework/feature/feature_system.cpp | 11 + .../framework/feature/static_acts.cpp | 35 +++ .../include/feature/feature_system.h | 4 + .../framework/include/feature/static_acts.h | 31 +++ .../framework/include/store/general_store.h | 4 - .../framework/store/auto_cache.cpp | 2 +- .../service/cloud/cloud_service_impl.cpp | 47 ++-- .../service/cloud/cloud_service_impl.h | 12 +- .../service/cloud/sync_manager.cpp | 1 + .../data_share/data_share_service_impl.cpp | 6 +- .../data_share/data_share_service_impl.h | 10 +- .../src/executor/document/check_common.cpp | 6 +- .../src/executor/document/check_common.h | 4 +- .../src/interface/src/result_set.cpp | 2 +- .../src/sqlite_store_executor_impl.cpp | 2 +- .../unittest/api/documentdb_data_test.cpp | 4 - .../service/object/object_service_impl.cpp | 4 +- .../service/object/object_service_impl.h | 10 +- .../service/rdb/rdb_cloud.cpp | 2 +- .../service/rdb/rdb_cloud_data_translate.cpp | 4 +- .../service/rdb/rdb_general_store.cpp | 14 -- .../service/rdb/rdb_general_store.h | 3 - .../service/rdb/rdb_query.cpp | 12 +- .../service/rdb/rdb_query.h | 4 +- .../service/rdb/rdb_service_impl.cpp | 160 +++++++------ .../service/rdb/rdb_service_impl.h | 42 ++-- .../service/test/BUILD.gn | 83 ------- .../fuzztest/cloudservicestub_fuzzer/BUILD.gn | 2 + .../fuzztest/kvdbservicestub_fuzzer/BUILD.gn | 2 + .../objectservicestub_fuzzer/BUILD.gn | 2 + .../fuzztest/rdbresultsetstub_fuzzer/BUILD.gn | 2 + .../fuzztest/rdbservicestub_fuzzer/BUILD.gn | 2 + .../test/fuzztest/udmfservice_fuzzer/BUILD.gn | 1 + .../service/test/mock/db_store_mock.cpp | 7 - .../service/test/mock/db_store_mock.h | 1 - .../udmf/lifecycle/lifecycle_manager.cpp | 53 +++-- .../udmf/lifecycle/lifecycle_manager.h | 3 +- .../service/udmf/lifecycle/lifecycle_policy.h | 3 +- .../udmf/permission/checker_manager.cpp | 3 + .../service/udmf/store/runtime_store.cpp | 19 +- .../service/udmf/store/store_cache.cpp | 4 +- .../service/udmf/udmf_service_stub.cpp | 4 - kv_store/bundle.json | 10 + kv_store/frameworks/CMakeLists.txt | 5 + .../common/test/concurrent_map_test.cpp | 1 + .../common/test/task_scheduler_test.cpp | 1 - .../src/kvstore_service_death_notifier.cpp | 3 +- .../distributeddatafwk/test/BUILD.gn | 5 +- .../test/unittest/device_kvstore_test.cpp | 2 - ...stributed_kv_data_manager_encrypt_test.cpp | 4 +- .../distributed_kv_data_manager_test.cpp | 19 -- .../single_kvstore_client_query_test.cpp | 3 - .../unittest/single_kvstore_client_test.cpp | 6 +- .../include/datamgr_service_proxy.h | 33 +++ .../distributeddata_ipc_interface_code.h | 3 +- .../include/ikvstore_data_service.h | 39 +-- .../include/kvstore_data_service_mgr.h | 29 +++ .../src/datamgr_service_proxy.cpp} | 76 +++--- .../src/distributed_data_mgr.cpp | 27 +++ .../src/kvstore_data_service_mgr.cpp | 38 +++ .../innerkitsimpl/kvdb/test/BUILD.gn | 5 +- .../kvdb/test/backup_manager_test.cpp | 2 - .../kvdb/test/single_store_impl_test.cpp | 2 - .../kvdb/test/store_factory_test.cpp | 4 +- .../include/js_const_properties.h | 6 +- .../distributeddata/include/js_util.h | 6 +- .../distributeddata/include/napi_queue.h | 6 +- .../distributeddata/include/uv_queue.h | 6 +- .../include/js_const_properties.h | 6 +- .../include/js_error_utils.h | 2 +- .../distributedkvstore/include/js_util.h | 6 +- .../distributedkvstore/include/napi_queue.h | 6 +- .../distributedkvstore/include/uv_queue.h | 6 +- .../frameworks/libs/distributeddb/BUILD.gn | 1 - .../common/include/cloud/cloud_db_types.h | 5 - .../distributeddb/common/include/db_common.h | 4 + .../common/include/db_constant.h | 3 +- .../common/include/performance_analysis.h | 2 + .../common/include/relational/table_info.h | 5 + .../distributeddb/common/src/db_common.cpp | 15 ++ .../distributeddb/common/src/db_constant.cpp | 4 +- .../common/src/performance_analysis.cpp | 3 +- .../common/src/relational/table_info.cpp | 10 + .../common/src/task_pool_impl.cpp | 16 +- .../distributeddb/common/src/task_pool_impl.h | 1 + .../distributeddb/common/src/task_queue.cpp | 10 + .../distributeddb/common/src/task_queue.h | 2 +- .../relational/relational_store_client.h | 37 +++ .../relational/relational_store_manager.h | 5 +- .../interfaces/include/store_types.h | 7 + .../relational_store_delegate_impl.h | 2 - .../relational/relational_store_manager.cpp | 42 +++- .../relational_store_sqlite_ext.cpp | 196 +++++++++++++-- .../storage/include/cloud/cloud_meta_data.h | 4 +- .../include/cloud/cloud_storage_utils.h | 20 +- .../storage/include/storage_proxy.h | 2 + .../storage/src/cloud/cloud_meta_data.cpp | 13 + .../storage/src/cloud/cloud_storage_utils.cpp | 43 +++- .../storage/src/cloud/schema_mgr.cpp | 24 +- .../src/relational_sync_able_storage.cpp | 13 +- .../sqlite/cloud_sync_log_table_manager.cpp | 45 +++- .../collaboration_log_table_manager.cpp | 8 +- .../sqlite_relational_database_upgrader.cpp | 8 +- ...qlite_single_relational_storage_engine.cpp | 6 + .../sqlite/split_device_log_table_manager.cpp | 6 +- .../sqlite_single_ver_natural_store.cpp | 2 +- ...single_ver_relational_storage_executor.cpp | 45 +++- ...e_single_ver_relational_storage_executor.h | 3 + .../storage/src/sqlite/sqlite_utils.cpp | 62 ++++- .../storage/src/sqlite/sqlite_utils.h | 4 + .../storage/src/storage_engine.cpp | 2 + .../storage/src/storage_proxy.cpp | 10 + .../src/cloud/cloud_force_pull_strategy.cpp | 6 +- .../src/cloud/cloud_force_pull_strategy.h | 3 +- .../src/cloud/cloud_force_push_strategy.cpp | 4 +- .../src/cloud/cloud_force_push_strategy.h | 3 +- .../syncer/src/cloud/cloud_merge_strategy.cpp | 6 +- .../syncer/src/cloud/cloud_merge_strategy.h | 3 +- .../syncer/src/cloud/cloud_sync_strategy.h | 4 +- .../syncer/src/cloud/cloud_sync_utils.h | 8 + .../syncer/src/cloud/cloud_syncer.cpp | 165 +++++++++---- .../syncer/src/cloud/cloud_syncer.h | 25 +- .../syncer/src/single_ver_data_sync.cpp | 4 +- .../syncer/src/single_ver_data_sync_utils.cpp | 13 +- .../syncer/src/single_ver_data_sync_utils.h | 3 +- .../libs/distributeddb/test/BUILD.gn | 1 - .../common/distributeddb_common_test.cpp | 26 +- .../common/distributeddb_tools_unit_test.cpp | 48 ++-- .../common/distributeddb_tools_unit_test.h | 5 +- ...b_cloud_interfaces_relational_ext_test.cpp | 225 +++++++++++++++++- ...ces_relational_remove_device_data_test.cpp | 1 - .../distributeddb_interfaces_log_test.cpp | 4 +- ...uteddb_interfaces_relational_sync_test.cpp | 6 +- ..._cloud_interfaces_relational_sync_test.cpp | 2 +- .../distributeddb_cloud_meta_data_test.cpp | 32 ++- ...stributeddb_cloud_save_cloud_data_test.cpp | 2 + ...relational_cloud_syncable_storage_test.cpp | 8 +- ...e_sqlite_single_ver_natural_store_test.cpp | 2 +- ...distributeddb_cloud_asset_compare_test.cpp | 16 +- .../distributeddb_cloud_strategy_test.cpp | 59 ++--- .../common/syncer/cloud/virtual_cloud_db.cpp | 16 ++ .../common/syncer/cloud/virtual_cloud_db.h | 2 + ...stributeddb_relational_multi_user_test.cpp | 1 - ...ributeddb_relational_ver_p2p_sync_test.cpp | 151 +++++++++++- ...buteddb_single_ver_p2p_sync_check_test.cpp | 46 ++++ .../virtual_single_ver_sync_db_Interface.cpp | 8 + .../virtual_single_ver_sync_db_Interface.h | 4 + .../innerkits/distributeddata/BUILD.gn | 7 +- .../innerkits/distributeddatamgr/BUILD.gn | 50 ++++ .../include/distributed_data_mgr.h | 44 ++++ .../interfaces/mock/napi_base_context.h | 2 +- .../napi/ace_napi/include/napi/native_api.h | 7 + mock/src/mock_js_napi.cpp | 15 +- .../js/napi/common/include/js_ability.h | 6 +- .../js/napi/common/include/js_utils.h | 6 +- .../js/napi/common/include/napi_async_call.h | 14 +- .../include/napi_preferences_observer.h | 2 +- .../js/napi/common/include/uv_queue.h | 6 +- .../mock/cross_platform/include/js_ability.h | 6 +- .../js/napi/common/mock/include/js_ability.h | 6 +- .../js/napi/common/src/napi_async_call.cpp | 4 +- .../preferences/include/napi_preferences.h | 6 +- .../include/napi_preferences_helper.h | 6 +- .../js/napi/preferences/src/entry_point.cpp | 4 +- .../js/napi/storage/include/napi_storage.h | 7 +- .../storage/include/napi_storage_helper.h | 6 +- .../napi/storage/src/entry_point_storage.cpp | 4 +- .../js/napi/storage/src/napi_storage.cpp | 7 +- .../include/napi_system_storage.h | 6 +- .../src/entry_point_system_storage.cpp | 4 +- .../native/include/preferences_xml_utils.h | 1 - .../fuzztest/preferences_fuzzer/BUILD.gn | 2 +- .../native/unittest/preferences_file_test.cpp | 2 +- .../unittest/preferences_xml_utils_test.cpp | 4 +- .../cloud_data/include/js_const_properties.h | 6 +- .../napi/cloud_data/include/js_error_utils.h | 2 +- .../js/napi/cloud_data/include/napi_queue.h | 6 +- .../js/napi/common/include/js_ability.h | 6 +- .../js/napi/common/include/js_utils.h | 12 +- .../js/napi/common/include/js_uv_queue.h | 6 +- .../js/napi/common/mock/include/js_ability.h | 6 +- .../common/mock/include/napi_async_proxy.h | 6 +- .../js/napi/common/src/js_utils.cpp | 8 +- .../dataability/include/napi_async_proxy.h | 6 +- .../include/napi_data_ability_predicates.h | 6 +- .../include/napi_predicates_utils.h | 6 +- .../js/napi/dataability/src/entry_point.cpp | 4 +- .../js/napi/rdb/include/napi_async_call.h | 6 +- .../rdb/include/napi_rdb_const_properties.h | 6 +- .../js/napi/rdb/include/napi_rdb_error.h | 1 - .../js/napi/rdb/include/napi_rdb_predicates.h | 6 +- .../js/napi/rdb/include/napi_rdb_store.h | 6 +- .../napi/rdb/include/napi_rdb_store_helper.h | 6 +- .../js/napi/rdb/include/napi_result_set.h | 6 +- .../js/napi/rdb/include/napi_uv_queue.h | 6 +- .../js/napi/rdb/include/napi_values_bucket.h | 6 +- .../rdb/mock/include/napi_rdb_predicates.h | 6 +- .../js/napi/rdb/mock/include/napi_rdb_store.h | 6 +- .../napi/rdb/mock/include/napi_result_set.h | 6 +- .../js/napi/rdb/src/napi_rdb_store.cpp | 10 +- .../relationalstore/include/napi_async_call.h | 6 +- .../include/napi_rdb_const_properties.h | 6 +- .../include/napi_rdb_predicates.h | 6 +- .../relationalstore/include/napi_rdb_store.h | 6 +- .../include/napi_rdb_store_helper.h | 6 +- .../relationalstore/include/napi_result_set.h | 6 +- .../relationalstore/include/napi_uv_queue.h | 6 +- .../mock/include/napi_rdb_store.h | 6 +- .../mock/include/napi_result_set.h | 6 +- .../napi/relationalstore/src/entry_point.cpp | 2 +- .../src/napi_rdb_predicates.cpp | 4 - .../relationalstore/src/napi_rdb_store.cpp | 8 +- .../native/rdb/include/rdb_service_proxy.h | 8 +- .../native/rdb/include/rdb_store_manager.h | 1 - .../native/rdb/src/rdb_service_proxy.cpp | 71 ++---- .../native/rdb/src/rdb_store_manager.cpp | 2 - .../native/rdb/src/sqlite_statement.cpp | 5 +- .../src/RdbStoreAssetResultSetJsunit.test.js | 4 +- .../src/RdbstoreCallBackJsunit.test.js | 140 ++++++----- .../unittest/src/RdbstoreInsertJsunit.test.js | 100 ++++++++ .../src/RdbstorePromiseJsunit.test.js | 146 +++++++----- .../rdb/fuzztest/rdbimpl_fuzzer/BUILD.gn | 2 +- .../rdb/fuzztest/rdbstore_fuzzer/BUILD.gn | 2 +- .../rdb/unittest/rdb_store_impl_test.cpp | 8 +- .../test/fuzztest/udmfclient_fuzzer/BUILD.gn | 2 +- .../framework/service/udmf_service_client.cpp | 3 +- udmf/interfaces/innerkits/BUILD.gn | 2 + .../jskits/common/napi_data_utils.h | 6 +- .../jskits/common/napi_error_utils.h | 2 +- udmf/interfaces/jskits/common/napi_queue.h | 6 +- .../data/application_defined_record_napi.h | 4 +- udmf/interfaces/jskits/data/audio_napi.h | 4 +- udmf/interfaces/jskits/data/file_napi.h | 4 +- udmf/interfaces/jskits/data/folder_napi.h | 4 +- udmf/interfaces/jskits/data/html_napi.h | 4 +- udmf/interfaces/jskits/data/image_napi.h | 4 +- udmf/interfaces/jskits/data/link_napi.h | 4 +- udmf/interfaces/jskits/data/plain_text_napi.h | 4 +- udmf/interfaces/jskits/data/summary_napi.h | 4 +- .../jskits/data/system_defined_appitem_napi.h | 4 +- .../jskits/data/system_defined_form_napi.h | 4 +- .../data/system_defined_pixelmap_napi.h | 4 +- .../jskits/data/system_defined_record_napi.h | 4 +- udmf/interfaces/jskits/data/text_napi.h | 4 +- .../jskits/data/unified_data_channel_napi.h | 4 +- .../jskits/data/unified_data_napi.h | 2 +- .../jskits/data/unified_record_napi.h | 4 +- .../data/uniform_type_descriptor_napi.h | 4 +- udmf/interfaces/jskits/data/video_napi.h | 4 +- 303 files changed, 3064 insertions(+), 1528 deletions(-) create mode 100644 data_object/frameworks/innerkitsimpl/include/adaptor/object_service.h create mode 100644 datamgr_service/services/distributeddataservice/app/src/kvstore_data_service_stub.cpp create mode 100644 datamgr_service/services/distributeddataservice/app/src/kvstore_data_service_stub.h create mode 100644 datamgr_service/services/distributeddataservice/framework/feature/static_acts.cpp create mode 100644 datamgr_service/services/distributeddataservice/framework/include/feature/static_acts.h create mode 100644 kv_store/frameworks/innerkitsimpl/distributeddatasvc/include/datamgr_service_proxy.h rename kv_store/frameworks/innerkitsimpl/{distributeddatafwk => distributeddatasvc}/include/distributeddata_ipc_interface_code.h (93%) rename kv_store/frameworks/innerkitsimpl/{distributeddatafwk => distributeddatasvc}/include/ikvstore_data_service.h (47%) create mode 100644 kv_store/frameworks/innerkitsimpl/distributeddatasvc/include/kvstore_data_service_mgr.h rename kv_store/frameworks/innerkitsimpl/{distributeddatafwk/src/ikvstore_data_service.cpp => distributeddatasvc/src/datamgr_service_proxy.cpp} (51%) create mode 100644 kv_store/frameworks/innerkitsimpl/distributeddatasvc/src/distributed_data_mgr.cpp create mode 100644 kv_store/frameworks/innerkitsimpl/distributeddatasvc/src/kvstore_data_service_mgr.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/interfaces/include/relational/relational_store_client.h create mode 100644 kv_store/interfaces/innerkits/distributeddatamgr/BUILD.gn create mode 100644 kv_store/interfaces/innerkits/distributeddatamgr/include/distributed_data_mgr.h diff --git a/data_object/frameworks/innerkitsimpl/include/adaptor/object_service.h b/data_object/frameworks/innerkitsimpl/include/adaptor/object_service.h new file mode 100644 index 00000000..f56f5a29 --- /dev/null +++ b/data_object/frameworks/innerkitsimpl/include/adaptor/object_service.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2022 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 DISTRIBUTED_OBJECT_SERVICE_H +#define DISTRIBUTED_OBJECT_SERVICE_H + +#include +#include +#include + +#include "object_callback.h" +namespace OHOS::ObjectStore { +class ObjectService { +public: + virtual int32_t ObjectStoreSave(const std::string &bundleName, const std::string &sessionId, + const std::string &deviceId, const std::map> &data, + sptr callback) = 0; + virtual int32_t ObjectStoreRetrieve( + const std::string &bundleName, const std::string &sessionId, sptr callback) = 0; + virtual int32_t ObjectStoreRevokeSave( + const std::string &bundleName, const std::string &sessionId, sptr callback) = 0; + virtual int32_t RegisterDataObserver( + const std::string &bundleName, const std::string &sessionId, sptr callback) = 0; +}; +} // namespace OHOS::ObjectStore +#endif diff --git a/data_object/frameworks/innerkitsimpl/include/common/string_utils.h b/data_object/frameworks/innerkitsimpl/include/common/string_utils.h index d750f000..de81a4fe 100644 --- a/data_object/frameworks/innerkitsimpl/include/common/string_utils.h +++ b/data_object/frameworks/innerkitsimpl/include/common/string_utils.h @@ -46,7 +46,6 @@ public: result.assign(reinterpret_cast(rstStr.data()), rstStr.size()); return result; } - static uint32_t BytesToStrWithType(Bytes input, std::string &str) { uint32_t len = input.end() - input.begin(); diff --git a/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_store_impl.cpp b/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_store_impl.cpp index 79662004..7929938d 100644 --- a/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_store_impl.cpp +++ b/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_store_impl.cpp @@ -223,6 +223,7 @@ DistributedObjectStore *DistributedObjectStore::GetInstance(const std::string &b // This operation needn't to malloc memory, we needn't to check nullptr. instPtr = new (std::nothrow) DistributedObjectStoreImpl(flatObjectStore); if (instPtr == nullptr) { + delete flatObjectStore; LOG_ERROR("no memory for DistributedObjectStoreImpl malloc!"); return nullptr; } diff --git a/data_object/frameworks/innerkitsimpl/src/adaptor/flat_object_storage_engine.cpp b/data_object/frameworks/innerkitsimpl/src/adaptor/flat_object_storage_engine.cpp index 401d3c19..b761b509 100644 --- a/data_object/frameworks/innerkitsimpl/src/adaptor/flat_object_storage_engine.cpp +++ b/data_object/frameworks/innerkitsimpl/src/adaptor/flat_object_storage_engine.cpp @@ -49,10 +49,6 @@ uint32_t FlatObjectStorageEngine::Open(const std::string &bundleName) LOG_ERROR("set distributed db communicator failed."); } storeManager_ = std::make_shared(bundleName, "default"); - if (storeManager_ == nullptr) { - LOG_ERROR("FlatObjectStorageEngine::make shared fail"); - return ERR_NOMEM; - } DistributedDB::KvStoreConfig config; config.dataDir = "/data/log"; diff --git a/data_object/frameworks/innerkitsimpl/src/communicator/app_pipe_mgr.cpp b/data_object/frameworks/innerkitsimpl/src/communicator/app_pipe_mgr.cpp index b4f78f11..b3827ed0 100644 --- a/data_object/frameworks/innerkitsimpl/src/communicator/app_pipe_mgr.cpp +++ b/data_object/frameworks/innerkitsimpl/src/communicator/app_pipe_mgr.cpp @@ -91,10 +91,6 @@ Status AppPipeMgr::Start(const PipeInfo &pipeInfo) } LOG_DEBUG("Start pipeInfo:%{public}s ", pipeInfo.pipeId.c_str()); auto handler = std::make_shared(pipeInfo); - if (handler == nullptr) { - LOG_WARN("pipeInfo:%{public}s. new failed", pipeInfo.pipeId.c_str()); - return Status::ILLEGAL_STATE; - } int ret = handler->CreateSessionServer(pipeInfo.pipeId); if (ret != 0) { LOG_WARN("Start pipeInfo:%{public}s, failed ret:%{public}d.", pipeInfo.pipeId.c_str(), ret); diff --git a/data_object/frameworks/innerkitsimpl/test/unittest/mock/include/mock_app_device_change_listener.h b/data_object/frameworks/innerkitsimpl/test/unittest/mock/include/mock_app_device_change_listener.h index 378534e9..a1413732 100644 --- a/data_object/frameworks/innerkitsimpl/test/unittest/mock/include/mock_app_device_change_listener.h +++ b/data_object/frameworks/innerkitsimpl/test/unittest/mock/include/mock_app_device_change_listener.h @@ -19,7 +19,6 @@ #include #include -#include #include "app_device_status_change_listener.h" namespace OHOS { diff --git a/data_object/frameworks/jskitsimpl/include/adaptor/js_common.h b/data_object/frameworks/jskitsimpl/include/adaptor/js_common.h index dddd4732..7eeb7dc9 100644 --- a/data_object/frameworks/jskitsimpl/include/adaptor/js_common.h +++ b/data_object/frameworks/jskitsimpl/include/adaptor/js_common.h @@ -17,47 +17,31 @@ #define JS_COMMON_H #include "hilog/log.h" namespace OHOS::ObjectStore { -#define CHECK_EQUAL_WITH_RETURN_NULL(status, value) \ - { \ - if (status != value) { \ - LOG_ERROR("error! %{public}d %{public}d", status, value); \ - return nullptr; \ - } \ - } - -#define CHECK_EQUAL_WITH_RETURN_VOID(status, value) \ - { \ - if (status != value) { \ - LOG_ERROR("error! %{public}d %{public}d", status, value); \ - return; \ - } \ - } - -#define CHECK_EQUAL_WITH_RETURN_FALSE(status, value) \ - { \ - if (status != value) { \ - LOG_ERROR("error! %{public}d %{public}d", status, value); \ - return false; \ - } \ - } +class Constants { +public: + static constexpr const char *CHANGE = "change"; + static constexpr const char *STATUS = "status"; +}; +#define OBJECT_REVT_NOTHING -#define ASSERT_MATCH_ELSE_RETURN_VOID(condition) \ - { \ +#define NOT_MATCH_RETURN(condition, res) \ + do { \ if (!(condition)) { \ LOG_ERROR("error! %{public}s", #condition); \ - return; \ + return res; \ } \ - } + } while (0) -#define ASSERT_MATCH_ELSE_RETURN_NULL(condition) \ - { \ - if (!(condition)) { \ - LOG_ERROR("error! %{public}s", #condition); \ - return nullptr; \ - } \ - } +#define NOT_MATCH_RETURN_VOID(condition) \ + NOT_MATCH_RETURN(condition, OBJECT_REVT_NOTHING) + +#define NOT_MATCH_RETURN_NULL(condition) \ + NOT_MATCH_RETURN(condition, nullptr) + +#define NOT_MATCH_RETURN_FALSE(condition) \ + NOT_MATCH_RETURN(condition, false) -#define ASSERT_MATCH_ELSE_GOTO_ERROR(condition) \ +#define NOT_MATCH_GOTO_ERROR(condition) \ { \ if (!(condition)) { \ LOG_ERROR("error! %{public}s", #condition); \ @@ -65,7 +49,7 @@ namespace OHOS::ObjectStore { } \ } -#define CHECK_API_VALID_ELSE_RETURN_VOID(assertion) \ +#define INVALID_API_THROW_ERROR(assertion) \ do { \ if (!(assertion)) { \ std::shared_ptr apiError = std::make_shared(); \ @@ -75,7 +59,7 @@ namespace OHOS::ObjectStore { } \ } while (0) -#define CHECK_VALID_ELSE_RETURN_VOID(assertion, msg) \ +#define INVALID_STATUS_THROW_ERROR(assertion, msg) \ do { \ if (!(assertion)) { \ std::shared_ptr innerError = std::make_shared(); \ @@ -86,6 +70,4 @@ namespace OHOS::ObjectStore { } \ } while (0) } // namespace OHOS::ObjectStore -static const char *CHANGE = "change"; -static const char *STATUS = "status"; -#endif // JS_COMMON_H +#endif // JS_COMMON_H \ No newline at end of file diff --git a/data_object/frameworks/jskitsimpl/include/common/js_util.h b/data_object/frameworks/jskitsimpl/include/common/js_util.h index 72b762a3..ad7e559e 100644 --- a/data_object/frameworks/jskitsimpl/include/common/js_util.h +++ b/data_object/frameworks/jskitsimpl/include/common/js_util.h @@ -49,7 +49,7 @@ public: static void GenerateNapiError(napi_env env, int32_t status, int32_t &errCode, std::string &errMessage); }; -#define NAPI_ASSERT_ERRCODE(env, assertion, version, err) \ +#define NAPI_ASSERT_ERRCODE_V9(env, assertion, version, err) \ do { \ if (!(assertion)) { \ if ((version) >= 9) { \ @@ -59,7 +59,7 @@ public: } \ } while (0) -#define CHECH_STATUS_ERRCODE(env, condition, err) \ +#define NAPI_ASSERT_ERRCODE(env, condition, err) \ do { \ if (!(condition)) { \ napi_throw_error((env), std::to_string((err)->GetCode()).c_str(), (err)->GetMessage().c_str()); \ diff --git a/data_object/frameworks/jskitsimpl/include/common/napi_queue.h b/data_object/frameworks/jskitsimpl/include/common/napi_queue.h index 8841acf9..a4c5d37a 100644 --- a/data_object/frameworks/jskitsimpl/include/common/napi_queue.h +++ b/data_object/frameworks/jskitsimpl/include/common/napi_queue.h @@ -66,7 +66,7 @@ private: }; /* check condition related to argc/argv, return and logging. */ -#define CHECK_ARGS_RETURN_VOID(ctxt, condition, message, err) \ +#define INVALID_ARGS_RETURN_ERROR(ctxt, condition, message, err) \ do { \ if (!(condition)) { \ (ctxt)->status = napi_invalid_arg; \ @@ -76,7 +76,7 @@ private: } \ } while (0) -#define CHECK_STATUS_RETURN_VOID(ctxt, error) \ +#define INVALID_STATUS_RETURN_ERROR(ctxt, error) \ do { \ if ((ctxt)->status != napi_ok) { \ (ctxt)->message = error; \ diff --git a/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobject.cpp b/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobject.cpp index d6686780..110bdf1c 100644 --- a/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobject.cpp +++ b/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobject.cpp @@ -34,7 +34,7 @@ napi_value JSDistributedObject::JSConstructor(napi_env env, napi_callback_info i napi_value thisVar = nullptr; void *data = nullptr; napi_status status = napi_get_cb_info(env, info, nullptr, 0, &thisVar, &data); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); return thisVar; } @@ -49,15 +49,14 @@ napi_value JSDistributedObject::JSGet(napi_env env, napi_callback_info info) char key[KEY_SIZE] = { 0 }; size_t keyLen = 0; napi_status status = napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); - ASSERT_MATCH_ELSE_RETURN_NULL(argc >= requireArgc); + NOT_MATCH_RETURN_NULL(status == napi_ok && argc >= requireArgc); + status = napi_get_value_string_utf8(env, argv[0], key, KEY_SIZE, &keyLen); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); + JSObjectWrapper *wrapper = nullptr; status = napi_unwrap(env, thisVar, (void **)&wrapper); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); - ASSERT_MATCH_ELSE_RETURN_NULL(wrapper != nullptr); - ASSERT_MATCH_ELSE_RETURN_NULL(wrapper->GetObject() != nullptr); + NOT_MATCH_RETURN_NULL(status == napi_ok && wrapper != nullptr && wrapper->GetObject() != nullptr); napi_value result = nullptr; if (wrapper->isUndefined(key)) { napi_get_undefined(env, &result); @@ -78,20 +77,17 @@ napi_value JSDistributedObject::JSPut(napi_env env, napi_callback_info info) size_t keyLen = 0; napi_valuetype valueType; napi_status status = napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); - ASSERT_MATCH_ELSE_RETURN_NULL(argc >= requireArgc); - status = napi_typeof(env, argv[0], &valueType); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); - CHECK_EQUAL_WITH_RETURN_NULL(valueType, napi_string); + NOT_MATCH_RETURN_NULL(status == napi_ok && argc >= requireArgc); + status = napi_get_value_string_utf8(env, argv[0], key, KEY_SIZE, &keyLen); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); - status = napi_typeof(env, argv[1], &valueType); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); + JSObjectWrapper *wrapper = nullptr; status = napi_unwrap(env, thisVar, (void **)&wrapper); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); - ASSERT_MATCH_ELSE_RETURN_NULL(wrapper != nullptr); - ASSERT_MATCH_ELSE_RETURN_NULL(wrapper->GetObject() != nullptr); + NOT_MATCH_RETURN_NULL(status == napi_ok && wrapper != nullptr && wrapper->GetObject() != nullptr); + + status = napi_typeof(env, argv[1], &valueType); + NOT_MATCH_RETURN_NULL(status == napi_ok); if (valueType == napi_undefined) { wrapper->AddUndefined(key); return nullptr; @@ -108,7 +104,7 @@ napi_value JSDistributedObject::GetCons(napi_env env) napi_value distributedObjectClass = nullptr; if (g_instance != nullptr) { napi_status status = napi_get_reference_value(env, g_instance, &distributedObjectClass); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); return distributedObjectClass; } const char *distributedObjectName = "DistributedObject"; @@ -122,10 +118,10 @@ napi_value JSDistributedObject::GetCons(napi_env env) napi_status status = napi_define_class(env, distributedObjectName, strlen(distributedObjectName), JSDistributedObject::JSConstructor, nullptr, sizeof(distributedObjectDesc) / sizeof(distributedObjectDesc[0]), distributedObjectDesc, &distributedObjectClass); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); if (g_instance == nullptr) { status = napi_create_reference(env, distributedObjectClass, 1, &g_instance); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); } return distributedObjectClass; } @@ -138,28 +134,28 @@ void JSDistributedObject::DoPut( case napi_boolean: { bool putValue = false; napi_status status = JSUtil::GetValue(env, value, putValue); - CHECK_EQUAL_WITH_RETURN_VOID(status, napi_ok); + NOT_MATCH_RETURN_VOID(status == napi_ok); wrapper->GetObject()->PutBoolean(keyString, putValue); break; } case napi_number: { double putValue = 0; napi_status status = JSUtil::GetValue(env, value, putValue); - CHECK_EQUAL_WITH_RETURN_VOID(status, napi_ok); + NOT_MATCH_RETURN_VOID(status == napi_ok); wrapper->GetObject()->PutDouble(keyString, putValue); break; } case napi_string: { std::string putValue; napi_status status = JSUtil::GetValue(env, value, putValue); - CHECK_EQUAL_WITH_RETURN_VOID(status, napi_ok); + NOT_MATCH_RETURN_VOID(status == napi_ok); wrapper->GetObject()->PutString(keyString, putValue); break; } case napi_object: { std::vector putValue; napi_status status = JSUtil::GetValue(env, value, putValue); - CHECK_EQUAL_WITH_RETURN_VOID(status, napi_ok); + NOT_MATCH_RETURN_VOID(status == napi_ok); wrapper->GetObject()->PutComplex(keyString, putValue); break; } @@ -180,35 +176,35 @@ void JSDistributedObject::DoGet(napi_env env, JSObjectWrapper *wrapper, char *ke case TYPE_STRING: { std::string result; uint32_t ret = wrapper->GetObject()->GetString(keyString, result); - ASSERT_MATCH_ELSE_RETURN_VOID(ret == SUCCESS) + NOT_MATCH_RETURN_VOID(ret == SUCCESS); napi_status status = JSUtil::SetValue(env, result, value); - ASSERT_MATCH_ELSE_RETURN_VOID(status == napi_ok) + NOT_MATCH_RETURN_VOID(status == napi_ok); break; } case TYPE_DOUBLE: { double result; uint32_t ret = wrapper->GetObject()->GetDouble(keyString, result); LOG_DEBUG("%{public}f", result); - ASSERT_MATCH_ELSE_RETURN_VOID(ret == SUCCESS) + NOT_MATCH_RETURN_VOID(ret == SUCCESS); napi_status status = JSUtil::SetValue(env, result, value); - ASSERT_MATCH_ELSE_RETURN_VOID(status == napi_ok) + NOT_MATCH_RETURN_VOID(status == napi_ok); break; } case TYPE_BOOLEAN: { bool result; uint32_t ret = wrapper->GetObject()->GetBoolean(keyString, result); LOG_DEBUG("%{public}d", result); - ASSERT_MATCH_ELSE_RETURN_VOID(ret == SUCCESS) + NOT_MATCH_RETURN_VOID(ret == SUCCESS); napi_status status = JSUtil::SetValue(env, result, value); - ASSERT_MATCH_ELSE_RETURN_VOID(status == napi_ok) + NOT_MATCH_RETURN_VOID(status == napi_ok); break; } case TYPE_COMPLEX: { std::vector result; uint32_t ret = wrapper->GetObject()->GetComplex(keyString, result); - ASSERT_MATCH_ELSE_RETURN_VOID(ret == SUCCESS) + NOT_MATCH_RETURN_VOID(ret == SUCCESS); napi_status status = JSUtil::SetValue(env, result, value); - ASSERT_MATCH_ELSE_RETURN_VOID(status == napi_ok) + NOT_MATCH_RETURN_VOID(status == napi_ok); break; } default: { @@ -230,31 +226,27 @@ napi_value JSDistributedObject::JSSave(napi_env env, napi_callback_info info) }; auto ctxt = std::make_shared(); std::function getCbOpe = [env, ctxt](size_t argc, napi_value *argv) { - CHECK_ARGS_RETURN_VOID(ctxt, argc >= 2, "arguments error", std::make_shared("1 or 2")); - napi_valuetype valueType = napi_undefined; - ctxt->status = napi_typeof(env, argv[0], &valueType); - CHECK_ARGS_RETURN_VOID(ctxt, valueType == napi_string, "arguments error", - std::make_shared("deviceId", "string")); + INVALID_ARGS_RETURN_ERROR(ctxt, argc >= 2, "arguments error", std::make_shared("1 or 2")); ctxt->status = JSUtil::GetValue(env, argv[0], ctxt->deviceId); - CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[0], i.e. invalid deviceId!"); + INVALID_ARGS_RETURN_ERROR(ctxt, ctxt->status == napi_ok, "arguments error", + std::make_shared("deviceId", "string")); + ctxt->status = JSUtil::GetValue(env, argv[1], ctxt->version); - CHECK_STATUS_RETURN_VOID(ctxt, "invalid arg[1], i.e. invalid version!"); + INVALID_STATUS_RETURN_ERROR(ctxt, "invalid arg[1], i.e. invalid version!"); JSObjectWrapper *wrapper = nullptr; napi_status status = napi_unwrap(env, ctxt->self, (void **)&wrapper); - CHECK_EQUAL_WITH_RETURN_VOID(status, napi_ok); - ASSERT_MATCH_ELSE_RETURN_VOID(wrapper != nullptr); - ASSERT_MATCH_ELSE_RETURN_VOID(wrapper->GetObject() != nullptr); + NOT_MATCH_RETURN_VOID(status == napi_ok && wrapper != nullptr && wrapper->GetObject() != nullptr); ctxt->wrapper = wrapper; }; ctxt->GetCbInfo(env, info, getCbOpe); - CHECH_STATUS_ERRCODE(env, ctxt->status != napi_invalid_arg, ctxt->error); + NAPI_ASSERT_ERRCODE(env, ctxt->status != napi_invalid_arg, ctxt->error); auto execute = [ctxt]() { LOG_INFO("start"); CHECH_STATUS_RETURN_VOID(env, ctxt->wrapper != nullptr, ctxt, "wrapper is null"); CHECH_STATUS_RETURN_VOID(env, ctxt->wrapper->GetObject() != nullptr, ctxt, "object is null"); uint32_t status = ctxt->wrapper->GetObject()->Save(ctxt->deviceId); - CHECK_API_VALID_ELSE_RETURN_VOID(status != ERR_PROCESSING); - CHECK_VALID_ELSE_RETURN_VOID(status == SUCCESS, "operation failed"); + INVALID_API_THROW_ERROR(status != ERR_PROCESSING); + INVALID_STATUS_THROW_ERROR(status == SUCCESS, "operation failed"); ctxt->status = napi_ok; LOG_INFO("end"); }; @@ -265,7 +257,7 @@ napi_value JSDistributedObject::JSSave(napi_env env, napi_callback_info info) std::string &sessionId = ctxt->wrapper->GetObject()->GetSessionId(); ctxt->status = napi_new_instance( env, GetSaveResultCons(env, sessionId, ctxt->version, ctxt->deviceId), 0, nullptr, &result); - CHECK_STATUS_RETURN_VOID(ctxt, "output failed!"); + INVALID_STATUS_RETURN_ERROR(ctxt, "output failed!"); } }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); @@ -284,9 +276,7 @@ napi_value JSDistributedObject::JSRevokeSave(napi_env env, napi_callback_info in // required 1 arguments :: JSObjectWrapper *wrapper = nullptr; napi_status status = napi_unwrap(env, ctxt->self, (void **)&wrapper); - CHECK_EQUAL_WITH_RETURN_VOID(status, napi_ok); - ASSERT_MATCH_ELSE_RETURN_VOID(wrapper != nullptr); - ASSERT_MATCH_ELSE_RETURN_VOID(wrapper->GetObject() != nullptr); + NOT_MATCH_RETURN_VOID(status == napi_ok && wrapper != nullptr && wrapper->GetObject() != nullptr); ctxt->wrapper = wrapper; }; ctxt->GetCbInfo(env, info, getCbOpe); @@ -298,8 +288,8 @@ napi_value JSDistributedObject::JSRevokeSave(napi_env env, napi_callback_info in CHECH_STATUS_RETURN_VOID(env, ctxt->wrapper != nullptr, ctxt, "wrapper is null"); CHECH_STATUS_RETURN_VOID(env, ctxt->wrapper->GetObject() != nullptr, ctxt, "object is null"); uint32_t status = ctxt->wrapper->GetObject()->RevokeSave(); - CHECK_API_VALID_ELSE_RETURN_VOID(status != ERR_PROCESSING); - CHECK_VALID_ELSE_RETURN_VOID(status == SUCCESS, "operation failed"); + INVALID_API_THROW_ERROR(status != ERR_PROCESSING); + INVALID_STATUS_THROW_ERROR(status == SUCCESS, "operation failed"); ctxt->status = napi_ok; LOG_INFO("end"); }; @@ -310,7 +300,7 @@ napi_value JSDistributedObject::JSRevokeSave(napi_env env, napi_callback_info in ctxt->status = napi_new_instance(env, JSDistributedObject::GetRevokeSaveResultCons(env, ctxt->wrapper->GetObject()->GetSessionId()), 0, nullptr, &result); - CHECK_STATUS_RETURN_VOID(ctxt, "output failed!"); + INVALID_STATUS_RETURN_ERROR(ctxt, "output failed!"); } }; return NapiQueue::AsyncWork(env, ctxt, std::string(__FUNCTION__), execute, output); @@ -324,11 +314,11 @@ napi_value JSDistributedObject::GetSaveResultCons( napi_value result; napi_status status = JSUtil::SetValue(env, sessionId, napiSessionId); - ASSERT_MATCH_ELSE_RETURN_NULL(status == napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); status = JSUtil::SetValue(env, version, napiVersion); - ASSERT_MATCH_ELSE_RETURN_NULL(status == napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); status = JSUtil::SetValue(env, deviceId, napiDeviceId); - ASSERT_MATCH_ELSE_RETURN_NULL(status == napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); napi_property_descriptor desc[] = { DECLARE_NAPI_PROPERTY("sessionId", napiSessionId), DECLARE_NAPI_PROPERTY("version", napiVersion), @@ -337,7 +327,7 @@ napi_value JSDistributedObject::GetSaveResultCons( status = napi_define_class(env, objectName, strlen(objectName), JSDistributedObject::JSConstructor, nullptr, sizeof(desc) / sizeof(desc[0]), desc, &result); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); return result; } @@ -348,14 +338,14 @@ napi_value JSDistributedObject::GetRevokeSaveResultCons(napi_env env, std::strin napi_value result; napi_status status = JSUtil::SetValue(env, sessionId, napiSessionId); - ASSERT_MATCH_ELSE_RETURN_NULL(status == napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); napi_property_descriptor desc[] = { DECLARE_NAPI_PROPERTY("sessionId", napiSessionId) }; status = napi_define_class(env, objectName, strlen(objectName), JSDistributedObject::JSConstructor, nullptr, sizeof(desc) / sizeof(desc[0]), desc, &result); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); return result; } } // namespace OHOS::ObjectStore \ No newline at end of file diff --git a/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobjectstore.cpp b/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobjectstore.cpp index bbcf8b58..7a06ac30 100644 --- a/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobjectstore.cpp +++ b/data_object/frameworks/jskitsimpl/src/adaptor/js_distributedobjectstore.cpp @@ -59,7 +59,7 @@ bool DeleteAllCallback(napi_env env, std::list &lists) continue; } napi_status status = napi_delete_reference(env, *iter); - CHECK_EQUAL_WITH_RETURN_FALSE(status, napi_ok); + NOT_MATCH_RETURN_FALSE(status == napi_ok); iter = lists.erase(iter); } return false; @@ -74,7 +74,7 @@ bool DeleteSingleCallback(napi_env env, std::list &lists, napi_value c continue; } napi_status status = napi_get_reference_value(env, *iter, &callbackTmp); - CHECK_EQUAL_WITH_RETURN_FALSE(status, napi_ok); + NOT_MATCH_RETURN_FALSE(status == napi_ok); bool isEquals = false; napi_strict_equals(env, callbackTmp, callback, &isEquals); if (isEquals) { @@ -106,7 +106,7 @@ napi_value JSDistributedObjectStore::NewDistributedObject( { napi_value result; napi_status status = napi_new_instance(env, JSDistributedObject::GetCons(env), 0, nullptr, &result); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); JSObjectWrapper *objectWrapper = new (std::nothrow) JSObjectWrapper(objectStore, object); if (objectWrapper == nullptr) { LOG_ERROR("JSDistributedObjectStore::NewDistributedObject no memory for objectWrapper malloc!"); @@ -143,7 +143,7 @@ napi_value JSDistributedObjectStore::NewDistributedObject( RestoreWatchers(env, objectWrapper, objectId); objectStore->NotifyCachedStatus(object->GetSessionId()); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); return result; } @@ -160,43 +160,37 @@ napi_value JSDistributedObjectStore::JSCreateObjectSync(napi_env env, napi_callb std::string sessionId; std::string objectId; napi_status status = napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); auto innerError = std::make_shared(); - NAPI_ASSERT_ERRCODE(env, argc >= 1, version, innerError); - napi_valuetype valueType = napi_undefined; - status = napi_typeof(env, argv[0], &valueType); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NAPI_ASSERT_ERRCODE_V9(env, argc >= 1, version, innerError); + status = JSUtil::GetValue(env, argv[0], version); - NAPI_ASSERT_ERRCODE(env, argc >= requireArgc, version, std::make_shared("1 or 2")); - NAPI_ASSERT_ERRCODE(env, !IsSandBox(), version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok && argc >= requireArgc, version, + std::make_shared("1 or 2")); + NAPI_ASSERT_ERRCODE_V9(env, !IsSandBox(), version, innerError); LOG_INFO("start JSCreateObjectSync"); - NAPI_ASSERT_ERRCODE(env, JSDistributedObjectStore::CheckSyncPermission(), version, + NAPI_ASSERT_ERRCODE_V9(env, JSDistributedObjectStore::CheckSyncPermission(), version, std::make_shared()); - status = napi_typeof(env, argv[1], &valueType); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - NAPI_ASSERT_ERRCODE(env, valueType == napi_string, version, - std::make_shared("sessionId", "string")); + status = JSUtil::GetValue(env, argv[1], sessionId); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - status = napi_typeof(env, argv[2], &valueType); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - CHECK_EQUAL_WITH_RETURN_NULL(valueType, napi_string); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok, version, + std::make_shared("sessionId", "string")); + status = JSUtil::GetValue(env, argv[2], objectId); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok, version, innerError); std::string bundleName = ""; if (argc > requireArgc) { bool executeResult = JSDistributedObjectStore::GetBundleNameWithContext(env, argv[3], bundleName); - NAPI_ASSERT_ERRCODE(env, executeResult, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, executeResult, version, innerError); } else { bundleName = JSDistributedObjectStore::GetBundleName(env); } DistributedObjectStore *objectInfo = DistributedObjectStore::GetInstance(bundleName); - NAPI_ASSERT_ERRCODE(env, objectInfo != nullptr, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, objectInfo != nullptr, version, innerError); uint32_t result = 0; DistributedObject *object = objectInfo->CreateObject(sessionId, result); - NAPI_ASSERT_ERRCODE(env, result != ERR_EXIST, version, std::make_shared()); - NAPI_ASSERT_ERRCODE(env, result == SUCCESS, version, innerError); - NAPI_ASSERT_ERRCODE(env, object != nullptr, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, result != ERR_EXIST, version, std::make_shared()); + NAPI_ASSERT_ERRCODE_V9(env, result == SUCCESS && object != nullptr, version, innerError); return NewDistributedObject(env, objectInfo, object, objectId); } @@ -213,20 +207,21 @@ napi_value JSDistributedObjectStore::JSDestroyObjectSync(napi_env env, napi_call std::string sessionId; std::string bundleName; napi_status status = napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); status = JSUtil::GetValue(env, argv[0], version); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); - ASSERT_MATCH_ELSE_RETURN_NULL(argc >= requireArgc); + NOT_MATCH_RETURN_NULL(status == napi_ok && argc >= requireArgc); + JSObjectWrapper *objectWrapper = nullptr; status = napi_unwrap(env, argv[1], (void **)&objectWrapper); auto innerError = std::make_shared(); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - NAPI_ASSERT_ERRCODE(env, objectWrapper != nullptr, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok && objectWrapper != nullptr, version, innerError); + DistributedObjectStore *objectInfo = DistributedObjectStore::GetInstance(JSDistributedObjectStore::GetBundleName(env)); - NAPI_ASSERT_ERRCODE(env, objectInfo != nullptr && objectWrapper->GetObject() != nullptr, version, innerError); - objectWrapper->DeleteWatch(env, CHANGE); - objectWrapper->DeleteWatch(env, STATUS); + NAPI_ASSERT_ERRCODE_V9(env, objectInfo != nullptr && objectWrapper->GetObject() != nullptr, version, innerError); + + objectWrapper->DeleteWatch(env, Constants::CHANGE); + objectWrapper->DeleteWatch(env, Constants::STATUS); objectInfo->DeleteObject(objectWrapper->GetObject()->GetSessionId()); objectWrapper->DestroyObject(); return nullptr; @@ -246,37 +241,31 @@ napi_value JSDistributedObjectStore::JSOn(napi_env env, napi_callback_info info) napi_value thisVar = nullptr; void *data = nullptr; napi_status status = napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); auto innerError = std::make_shared(); - NAPI_ASSERT_ERRCODE(env, argc >= 1, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok && argc >= 1, version, innerError); + status = JSUtil::GetValue(env, argv[0], version); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); - NAPI_ASSERT_ERRCODE(env, argc >= requireArgc, version, std::make_shared("2")); + NOT_MATCH_RETURN_NULL(status == napi_ok); + NAPI_ASSERT_ERRCODE_V9(env, argc >= requireArgc, version, std::make_shared("2")); + char type[TYPE_SIZE] = { 0 }; size_t eventTypeLen = 0; - napi_valuetype valueType = napi_undefined; - status = napi_typeof(env, argv[1], &valueType); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - NAPI_ASSERT_ERRCODE(env, valueType == napi_string, version, std::make_shared("type", "string")); status = napi_get_value_string_utf8(env, argv[1], type, TYPE_SIZE, &eventTypeLen); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok, version, std::make_shared("type", "string")); - napi_valuetype objectType = napi_undefined; - status = napi_typeof(env, argv[2], &objectType); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - ASSERT_MATCH_ELSE_RETURN_NULL(objectType == napi_object); + napi_valuetype valueType = napi_undefined; + status = napi_typeof(env, argv[2], &valueType); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok && valueType == napi_object, version, innerError); JSObjectWrapper *wrapper = nullptr; status = napi_unwrap(env, argv[2], (void **)&wrapper); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - NAPI_ASSERT_ERRCODE(env, wrapper != nullptr, version, innerError); - napi_valuetype callbackType = napi_undefined; - status = napi_typeof(env, argv[3], &callbackType); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - NAPI_ASSERT_ERRCODE(env, callbackType == napi_function, version, + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok && wrapper != nullptr, version, innerError); + + status = napi_typeof(env, argv[3], &valueType); + NAPI_ASSERT_ERRCODE_V9(env, valueType == napi_function, version, std::make_shared("callback", "function")); bool addResult = wrapper->AddWatch(env, type, argv[3]); - NAPI_ASSERT_ERRCODE(env, addResult, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, addResult, version, innerError); napi_value result = nullptr; napi_get_undefined(env, &result); return result; @@ -298,38 +287,36 @@ napi_value JSDistributedObjectStore::JSOff(napi_env env, napi_callback_info info char type[TYPE_SIZE] = { 0 }; size_t typeLen = 0; napi_status status = napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); auto innerError = std::make_shared(); - NAPI_ASSERT_ERRCODE(env, argc >= 1, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok && argc >= 1, version, innerError); + status = JSUtil::GetValue(env, argv[0], version); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); - NAPI_ASSERT_ERRCODE(env, argc >= requireArgc, version, std::make_shared("1")); - napi_valuetype valueType = napi_undefined; - status = napi_typeof(env, argv[1], &valueType); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - NAPI_ASSERT_ERRCODE(env, valueType == napi_string, version, std::make_shared("type", "string")); + NOT_MATCH_RETURN_NULL(status == napi_ok); + NAPI_ASSERT_ERRCODE_V9(env, argc >= requireArgc, version, std::make_shared("1")); + status = napi_get_value_string_utf8(env, argv[1], type, TYPE_SIZE, &typeLen); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok, version, std::make_shared("type", "string")); + napi_valuetype valueType = napi_undefined; status = napi_typeof(env, argv[2], &valueType); - ASSERT_MATCH_ELSE_RETURN_NULL(valueType == napi_object); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok && valueType == napi_object, version, innerError); + JSObjectWrapper *wrapper = nullptr; status = napi_unwrap(env, argv[2], (void **)&wrapper); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - NAPI_ASSERT_ERRCODE(env, wrapper != nullptr, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok && wrapper != nullptr, version, innerError); if (argc == requireArgc) { LOG_INFO("delete all"); wrapper->DeleteWatch(env, type); } else { LOG_INFO("delete"); status = napi_typeof(env, argv[3], &valueType); - NAPI_ASSERT_ERRCODE(env, valueType == napi_function, version, + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok && valueType == napi_function, version, std::make_shared("callback", "function")); wrapper->DeleteWatch(env, type, argv[3]); } napi_value result = nullptr; status = napi_get_undefined(env, &result); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok, version, innerError); return result; } @@ -370,7 +357,7 @@ void JSDistributedObjectStore::RestoreWatchers(napi_env env, JSObjectWrapper *wr LOG_ERROR("error! %{public}d", status); continue; } - wrapper->AddWatch(env, CHANGE, callbackValue); + wrapper->AddWatch(env, Constants::CHANGE, callbackValue); } return true; }); @@ -384,7 +371,7 @@ void JSDistributedObjectStore::RestoreWatchers(napi_env env, JSObjectWrapper *wr LOG_ERROR("error! %{public}d", status); continue; } - wrapper->AddWatch(env, STATUS, callbackValue); + wrapper->AddWatch(env, Constants::STATUS, callbackValue); } return true; }); @@ -407,38 +394,34 @@ napi_value JSDistributedObjectStore::JSRecordCallback(napi_env env, napi_callbac napi_value thisVar = nullptr; void *data = nullptr; napi_status status = napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); auto innerError = std::make_shared(); - NAPI_ASSERT_ERRCODE(env, argc >= 1, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok && argc >= 1, version, innerError); + status = JSUtil::GetValue(env, argv[0], version); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); - NAPI_ASSERT_ERRCODE(env, argc >= requireArgc, version, std::make_shared("2")); + NOT_MATCH_RETURN_NULL(status == napi_ok); + NAPI_ASSERT_ERRCODE_V9(env, argc >= requireArgc, version, std::make_shared("2")); + char type[TYPE_SIZE] = { 0 }; size_t eventTypeLen = 0; - napi_valuetype valueType = napi_undefined; - status = napi_typeof(env, argv[1], &valueType); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - NAPI_ASSERT_ERRCODE(env, valueType == napi_string, version, std::make_shared("type", "string")); status = napi_get_value_string_utf8(env, argv[1], type, TYPE_SIZE, &eventTypeLen); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok, version, std::make_shared("type", "string")); + std::string objectId; - status = napi_typeof(env, argv[2], &valueType); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - CHECK_EQUAL_WITH_RETURN_NULL(valueType, napi_string); status = JSUtil::GetValue(env, argv[2], objectId); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); + NOT_MATCH_RETURN_NULL(status == napi_ok); + napi_valuetype callbackType = napi_undefined; status = napi_typeof(env, argv[3], &callbackType); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - NAPI_ASSERT_ERRCODE(env, callbackType == napi_function, version, + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok && callbackType == napi_function, version, std::make_shared("callback", "function")); + bool addResult = true; - if (!strcmp(CHANGE, type)) { + if (!strcmp(Constants::CHANGE, type)) { addResult = AddCallback(env, g_changeCallBacks, objectId, argv[3]); - } else if (!strcmp(STATUS, type)) { + } else if (!strcmp(Constants::STATUS, type)) { addResult = AddCallback(env, g_statusCallBacks, objectId, argv[3]); } - NAPI_ASSERT_ERRCODE(env, addResult, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, addResult, version, innerError); napi_value result = nullptr; napi_get_undefined(env, &result); return result; @@ -458,47 +441,42 @@ napi_value JSDistributedObjectStore::JSDeleteCallback(napi_env env, napi_callbac napi_value thisVar = nullptr; void *data = nullptr; napi_status status = napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); auto innerError = std::make_shared(); - NAPI_ASSERT_ERRCODE(env, argc >= 1, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok && argc >= 1, version, innerError); + status = JSUtil::GetValue(env, argv[0], version); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); - NAPI_ASSERT_ERRCODE(env, argc >= requireArgc, version, std::make_shared("1 or 2")); + NOT_MATCH_RETURN_NULL(status == napi_ok); + NAPI_ASSERT_ERRCODE_V9(env, argc >= requireArgc, version, std::make_shared("1 or 2")); + char type[TYPE_SIZE] = { 0 }; size_t eventTypeLen = 0; - napi_valuetype valueType = napi_undefined; - status = napi_typeof(env, argv[1], &valueType); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - NAPI_ASSERT_ERRCODE(env, valueType == napi_string, version, std::make_shared("type", "string")); + status = napi_get_value_string_utf8(env, argv[1], type, TYPE_SIZE, &eventTypeLen); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok, version, std::make_shared("type", "string")); std::string objectId; - status = napi_typeof(env, argv[2], &valueType); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - CHECK_EQUAL_WITH_RETURN_NULL(valueType, napi_string); status = JSUtil::GetValue(env, argv[2], objectId); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); + NOT_MATCH_RETURN_NULL(status == napi_ok); + bool delResult = true; if (argc == 3) { - if (!strcmp(CHANGE, type)) { + if (!strcmp(Constants::CHANGE, type)) { delResult = DelCallback(env, g_changeCallBacks, objectId); - } else if (!strcmp(STATUS, type)) { + } else if (!strcmp(Constants::STATUS, type)) { delResult = DelCallback(env, g_statusCallBacks, objectId); } } else { napi_valuetype callbackType = napi_undefined; status = napi_typeof(env, argv[3], &callbackType); - NAPI_ASSERT_ERRCODE(env, status == napi_ok, version, innerError); - NAPI_ASSERT_ERRCODE(env, callbackType == napi_function, version, + NAPI_ASSERT_ERRCODE_V9(env, status == napi_ok && callbackType == napi_function, version, std::make_shared("callback", "function")); - if (!strcmp(CHANGE, type)) { + if (!strcmp(Constants::CHANGE, type)) { delResult = DelCallback(env, g_changeCallBacks, objectId, argv[3]); - } else if (!strcmp(STATUS, type)) { + } else if (!strcmp(Constants::STATUS, type)) { delResult = DelCallback(env, g_statusCallBacks, objectId, argv[3]); } } - NAPI_ASSERT_ERRCODE(env, delResult, version, innerError); + NAPI_ASSERT_ERRCODE_V9(env, delResult, version, innerError); napi_value result = nullptr; napi_get_undefined(env, &result); return result; @@ -511,7 +489,7 @@ napi_value JSDistributedObjectStore::JSEquenceNum(napi_env env, napi_callback_in std::string str = std::to_string(distribution(randomDevice)); napi_value result = nullptr; napi_status status = napi_create_string_utf8(env, str.c_str(), str.size(), &result); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); return result; } diff --git a/data_object/frameworks/jskitsimpl/src/adaptor/js_module_init.cpp b/data_object/frameworks/jskitsimpl/src/adaptor/js_module_init.cpp index e09cfb8e..88c757cd 100644 --- a/data_object/frameworks/jskitsimpl/src/adaptor/js_module_init.cpp +++ b/data_object/frameworks/jskitsimpl/src/adaptor/js_module_init.cpp @@ -40,7 +40,7 @@ static napi_value DistributedDataObjectExport(napi_env env, napi_value exports) }; status = napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc); - CHECK_EQUAL_WITH_RETURN_NULL(status, napi_ok); + NOT_MATCH_RETURN_NULL(status == napi_ok); return exports; } diff --git a/data_object/frameworks/jskitsimpl/src/adaptor/js_object_wrapper.cpp b/data_object/frameworks/jskitsimpl/src/adaptor/js_object_wrapper.cpp index 4df37cb2..790da68e 100644 --- a/data_object/frameworks/jskitsimpl/src/adaptor/js_object_wrapper.cpp +++ b/data_object/frameworks/jskitsimpl/src/adaptor/js_object_wrapper.cpp @@ -42,10 +42,6 @@ bool JSObjectWrapper::AddWatch(napi_env env, const char *type, napi_value handle std::unique_lock cacheLock(watchMutex_); if (watcher_ == nullptr) { watcher_ = std::make_shared(env, objectStore_, object_); - if (watcher_ == nullptr) { - LOG_ERROR("JSObjectWrapper::new JSWatcher fail"); - return false; - } } return watcher_->On(type, handler); } diff --git a/data_object/frameworks/jskitsimpl/src/adaptor/js_watcher.cpp b/data_object/frameworks/jskitsimpl/src/adaptor/js_watcher.cpp index 901436b6..e9422aa5 100644 --- a/data_object/frameworks/jskitsimpl/src/adaptor/js_watcher.cpp +++ b/data_object/frameworks/jskitsimpl/src/adaptor/js_watcher.cpp @@ -70,19 +70,19 @@ void JSWatcher::ProcessChange(napi_env env, std::list &args) napi_value param[ARGV_SIZE]; napi_value result; napi_status status = napi_get_global(env, &global); - ASSERT_MATCH_ELSE_GOTO_ERROR(status == napi_ok); + NOT_MATCH_GOTO_ERROR(status == napi_ok); for (auto item : args) { ChangeArgs *changeArgs = static_cast(item); status = napi_get_reference_value(env, changeArgs->callback_, &callback); - ASSERT_MATCH_ELSE_GOTO_ERROR(status == napi_ok); + NOT_MATCH_GOTO_ERROR(status == napi_ok); status = JSUtil::SetValue(env, changeArgs->sessionId_, param[0]); - ASSERT_MATCH_ELSE_GOTO_ERROR(status == napi_ok); + NOT_MATCH_GOTO_ERROR(status == napi_ok); JSUtil::SetValue(env, changeArgs->changeData_, param[1]); - ASSERT_MATCH_ELSE_GOTO_ERROR(status == napi_ok); + NOT_MATCH_GOTO_ERROR(status == napi_ok); LOG_INFO("start %{public}s, %{public}zu", changeArgs->sessionId_.c_str(), changeArgs->changeData_.size()); status = napi_call_function(env, global, callback, ARGV_SIZE, param, &result); LOG_INFO("end %{public}s, %{public}zu", changeArgs->sessionId_.c_str(), changeArgs->changeData_.size()); - ASSERT_MATCH_ELSE_GOTO_ERROR(status == napi_ok); + NOT_MATCH_GOTO_ERROR(status == napi_ok); } ERROR: for (auto item : args) { @@ -116,10 +116,10 @@ void JSWatcher::Emit(const char *type, const std::string &sessionId, const std:: EventListener *JSWatcher::Find(const char *type) { - if (!strcmp(CHANGE, type)) { + if (!strcmp(Constants::CHANGE, type)) { return changeEventListener_; } - if (!strcmp(STATUS, type)) { + if (!strcmp(Constants::STATUS, type)) { return statusEventListener_; } return nullptr; @@ -133,23 +133,23 @@ void JSWatcher::ProcessStatus(napi_env env, std::list &args) napi_value param[ARGV_SIZE]; napi_value result; napi_status status = napi_get_global(env, &global); - ASSERT_MATCH_ELSE_GOTO_ERROR(status == napi_ok); + NOT_MATCH_GOTO_ERROR(status == napi_ok); for (auto item : args) { StatusArgs *statusArgs = static_cast(item); status = napi_get_reference_value(env, statusArgs->callback_, &callback); - ASSERT_MATCH_ELSE_GOTO_ERROR(status == napi_ok); + NOT_MATCH_GOTO_ERROR(status == napi_ok); status = JSUtil::SetValue(env, statusArgs->sessionId_, param[0]); - ASSERT_MATCH_ELSE_GOTO_ERROR(status == napi_ok); + NOT_MATCH_GOTO_ERROR(status == napi_ok); status = JSUtil::SetValue(env, statusArgs->networkId_, param[1]); - ASSERT_MATCH_ELSE_GOTO_ERROR(status == napi_ok); + NOT_MATCH_GOTO_ERROR(status == napi_ok); status = JSUtil::SetValue(env, statusArgs->status_, param[2]); - ASSERT_MATCH_ELSE_GOTO_ERROR(status == napi_ok); + NOT_MATCH_GOTO_ERROR(status == napi_ok); LOG_INFO("start %{public}s, %{public}s, %{public}s", statusArgs->sessionId_.c_str(), statusArgs->networkId_.c_str(), statusArgs->status_.c_str()); status = napi_call_function(env, global, callback, ARGV_SIZE, param, &result); LOG_INFO("end %{public}s, %{public}s, %{public}s", statusArgs->sessionId_.c_str(), statusArgs->networkId_.c_str(), statusArgs->status_.c_str()); - ASSERT_MATCH_ELSE_GOTO_ERROR(status == napi_ok); + NOT_MATCH_GOTO_ERROR(status == napi_ok); } ERROR: LOG_DEBUG("do clear"); @@ -281,7 +281,7 @@ void WatcherImpl::OnChanged(const std::string &sessionid, const std::vectorEmit(CHANGE, sessionid, changedData); + watcher_->Emit(Constants::CHANGE, sessionid, changedData); } WatcherImpl::~WatcherImpl() @@ -294,10 +294,6 @@ bool ChangeEventListener::Add(napi_env env, napi_value handler) { if (!isWatched_ && object_ != nullptr) { std::shared_ptr watcher = std::make_shared(watcher_); - if (watcher == nullptr) { - LOG_ERROR("new %{public}s error", object_->GetSessionId().c_str()); - return false; - } uint32_t ret = objectStore_->Watch(object_, watcher); if (ret != SUCCESS) { LOG_ERROR("Watch %{public}s error", object_->GetSessionId().c_str()); diff --git a/data_object/frameworks/jskitsimpl/src/adaptor/notifier_impl.cpp b/data_object/frameworks/jskitsimpl/src/adaptor/notifier_impl.cpp index 394a4553..65a61fde 100644 --- a/data_object/frameworks/jskitsimpl/src/adaptor/notifier_impl.cpp +++ b/data_object/frameworks/jskitsimpl/src/adaptor/notifier_impl.cpp @@ -27,10 +27,6 @@ std::shared_ptr NotifierImpl::GetInstance() std::lock_guard lockGuard(instanceLock); if (instance == nullptr) { instance = std::make_shared(); - if (instance == nullptr) { - LOG_ERROR("Failed to alloc NotifierImpl!"); - return nullptr; - } uint32_t ret = DistributedObjectStore::GetInstance()->SetStatusNotifier(instance); if (ret != SUCCESS) { LOG_ERROR("SetStatusNotifier %{public}d error", ret); diff --git a/data_object/frameworks/jskitsimpl/src/common/js_util.cpp b/data_object/frameworks/jskitsimpl/src/common/js_util.cpp index ae82150e..dc326406 100644 --- a/data_object/frameworks/jskitsimpl/src/common/js_util.cpp +++ b/data_object/frameworks/jskitsimpl/src/common/js_util.cpp @@ -55,18 +55,15 @@ napi_status JSUtil::GetValue(napi_env env, napi_value in, std::string &out) size_t maxLen = STR_MAX_LENGTH; napi_status status = napi_get_value_string_utf8(env, in, NULL, 0, &maxLen); if (maxLen <= 0) { - GET_AND_THROW_LAST_ERROR(env); - return status; + return napi_generic_failure; } char *buf = new (std::nothrow) char[maxLen + STR_TAIL_LENGTH]; if (buf != nullptr) { size_t len = 0; status = napi_get_value_string_utf8(env, in, buf, maxLen + STR_TAIL_LENGTH, &len); - if (status != napi_ok) { - GET_AND_THROW_LAST_ERROR(env); + if (status == napi_ok) { + out = std::string(buf); } - buf[len] = 0; - out = std::string(buf); delete[] buf; } else { status = napi_generic_failure; diff --git a/data_object/frameworks/jskitsimpl/src/common/napi_queue.cpp b/data_object/frameworks/jskitsimpl/src/common/napi_queue.cpp index 9011659e..83035f83 100644 --- a/data_object/frameworks/jskitsimpl/src/common/napi_queue.cpp +++ b/data_object/frameworks/jskitsimpl/src/common/napi_queue.cpp @@ -40,12 +40,12 @@ void ContextBase::GetCbInfo(napi_env envi, napi_callback_info info, NapiCbInfoPa size_t argc = ARGC_MAX; napi_value argv[ARGC_MAX] = { nullptr }; status = napi_get_cb_info(env, info, &argc, argv, &self, nullptr); - CHECK_STATUS_RETURN_VOID(this, "napi_get_cb_info failed!"); - CHECK_ARGS_RETURN_VOID(this, argc <= ARGC_MAX, "too many arguments!", std::make_shared()); - CHECK_ARGS_RETURN_VOID(this, self != nullptr, "no JavaScript this argument!", std::make_shared()); + INVALID_STATUS_RETURN_ERROR(this, "napi_get_cb_info failed!"); + INVALID_ARGS_RETURN_ERROR(this, argc <= ARGC_MAX, "too many arguments!", std::make_shared()); + INVALID_ARGS_RETURN_ERROR(this, self != nullptr, "no JavaScript this argument!", std::make_shared()); napi_create_reference(env, self, 1, &selfRef); status = napi_unwrap(env, self, &native); - CHECK_STATUS_RETURN_VOID(this, "self unwrap failed!"); + INVALID_STATUS_RETURN_ERROR(this, "self unwrap failed!"); if (!sync && (argc > 0)) { // get the last arguments :: @@ -54,11 +54,11 @@ void ContextBase::GetCbInfo(napi_env envi, napi_callback_info info, NapiCbInfoPa napi_status tyst = napi_typeof(env, argv[index], &type); if ((tyst == napi_ok) && (type == napi_function)) { status = napi_create_reference(env, argv[index], 1, &callbackRef); - CHECK_STATUS_RETURN_VOID(this, "ref callback failed!"); + INVALID_STATUS_RETURN_ERROR(this, "ref callback failed!"); argc = index; LOG_DEBUG("async callback, no promise"); } else { - CHECK_ARGS_RETURN_VOID(this, type == napi_undefined, "arguments error!", + INVALID_ARGS_RETURN_ERROR(this, type == napi_undefined, "arguments error!", std::make_shared("callback", "function")); LOG_DEBUG("no callback, async promise"); } @@ -67,7 +67,7 @@ void ContextBase::GetCbInfo(napi_env envi, napi_callback_info info, NapiCbInfoPa if (parse) { parse(argc, argv); } else { - CHECK_ARGS_RETURN_VOID(this, argc == 0, "required no arguments!", std::make_shared()); + INVALID_ARGS_RETURN_ERROR(this, argc == 0, "required no arguments!", std::make_shared()); } } @@ -89,7 +89,7 @@ napi_value NapiQueue::AsyncWork(napi_env env, std::shared_ptr ctxt, napi_create_async_work( ctxt->env, nullptr, resource, [](napi_env env, void* data) { - ASSERT_MATCH_ELSE_RETURN_VOID(data != nullptr); + NOT_MATCH_RETURN_VOID(data != nullptr); auto ctxt = reinterpret_cast(data); LOG_DEBUG("napi_async_execute_callback ctxt->status=%{public}d", ctxt->status); if (ctxt->execute && ctxt->status == napi_ok) { @@ -97,7 +97,7 @@ napi_value NapiQueue::AsyncWork(napi_env env, std::shared_ptr ctxt, } }, [](napi_env env, napi_status status, void* data) { - ASSERT_MATCH_ELSE_RETURN_VOID(data != nullptr); + NOT_MATCH_RETURN_VOID(data != nullptr); auto ctxt = reinterpret_cast(data); LOG_DEBUG("napi_async_complete_callback status=%{public}d, ctxt->status=%{public}d", status, ctxt->status); if ((status != napi_ok) && (ctxt->status == napi_ok)) { diff --git a/data_share/bundle.json b/data_share/bundle.json index 4ffb7437..be7b8ba7 100644 --- a/data_share/bundle.json +++ b/data_share/bundle.json @@ -59,7 +59,6 @@ "hitrace", "hilog", "ipc", - "ipc_js", "napi", "relational_store", "samgr" diff --git a/data_share/frameworks/js/napi/common/include/datashare_js_utils.h b/data_share/frameworks/js/napi/common/include/datashare_js_utils.h index 2d18255b..3e096353 100644 --- a/data_share/frameworks/js/napi/common/include/datashare_js_utils.h +++ b/data_share/frameworks/js/napi/common/include/datashare_js_utils.h @@ -24,7 +24,7 @@ #include "datashare_template.h" #include "datashare_value_object.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" +#include "napi/native_api.h" #define NAPI_ASSERT_ERRCODE(env, assertion, error) \ do { \ diff --git a/data_share/frameworks/js/napi/common/include/datashare_predicates_proxy.h b/data_share/frameworks/js/napi/common/include/datashare_predicates_proxy.h index dea5ae3a..6971c25a 100644 --- a/data_share/frameworks/js/napi/common/include/datashare_predicates_proxy.h +++ b/data_share/frameworks/js/napi/common/include/datashare_predicates_proxy.h @@ -18,9 +18,9 @@ #include #include "datashare_abs_predicates.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace DataShare { diff --git a/data_share/frameworks/js/napi/common/include/datashare_result_set_proxy.h b/data_share/frameworks/js/napi/common/include/datashare_result_set_proxy.h index d20d266e..20681411 100644 --- a/data_share/frameworks/js/napi/common/include/datashare_result_set_proxy.h +++ b/data_share/frameworks/js/napi/common/include/datashare_result_set_proxy.h @@ -18,9 +18,9 @@ #include #include "datashare_result_set.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace DataShare { diff --git a/data_share/frameworks/js/napi/common/include/napi_datashare_values_bucket.h b/data_share/frameworks/js/napi/common/include/napi_datashare_values_bucket.h index 666caaf7..1c80ed41 100644 --- a/data_share/frameworks/js/napi/common/include/napi_datashare_values_bucket.h +++ b/data_share/frameworks/js/napi/common/include/napi_datashare_values_bucket.h @@ -16,9 +16,9 @@ #ifndef NAPI_DATASHARE_VALUES_BUCKET_H #define NAPI_DATASHARE_VALUES_BUCKET_H -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "datashare_values_bucket.h" #include "datashare_js_utils.h" diff --git a/data_share/frameworks/js/napi/dataShare/include/async_call.h b/data_share/frameworks/js/napi/dataShare/include/async_call.h index 62a2d96d..1e54c316 100644 --- a/data_share/frameworks/js/napi/dataShare/include/async_call.h +++ b/data_share/frameworks/js/napi/dataShare/include/async_call.h @@ -19,9 +19,9 @@ #include #include "datashare_js_utils.h" #include "datashare_error_impl.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_common.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS::DataShare { class AsyncCall final { diff --git a/data_share/frameworks/js/napi/dataShare/include/data_share_common.h b/data_share/frameworks/js/napi/dataShare/include/data_share_common.h index 420a4106..07474f80 100644 --- a/data_share/frameworks/js/napi/dataShare/include/data_share_common.h +++ b/data_share/frameworks/js/napi/dataShare/include/data_share_common.h @@ -16,9 +16,9 @@ #ifndef DATASHARE_COMMON_H #define DATASHARE_COMMON_H #include "ability.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_common_data.h" #include "datashare_helper.h" diff --git a/data_share/frameworks/js/napi/dataShare/include/napi_datashare_inner_observer.h b/data_share/frameworks/js/napi/dataShare/include/napi_datashare_inner_observer.h index a18bc968..efe95abe 100644 --- a/data_share/frameworks/js/napi/dataShare/include/napi_datashare_inner_observer.h +++ b/data_share/frameworks/js/napi/dataShare/include/napi_datashare_inner_observer.h @@ -18,9 +18,9 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_common.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace DataShare { diff --git a/data_share/frameworks/js/napi/dataShare/src/native_datashare_module.cpp b/data_share/frameworks/js/napi/dataShare/src/native_datashare_module.cpp index 05580e74..27007ab7 100644 --- a/data_share/frameworks/js/napi/dataShare/src/native_datashare_module.cpp +++ b/data_share/frameworks/js/napi/dataShare/src/native_datashare_module.cpp @@ -13,8 +13,8 @@ * limitations under the License. */ -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" #include "datashare_log.h" #include "napi_datashare_helper.h" diff --git a/data_share/frameworks/js/napi/observer/include/napi_observer.h b/data_share/frameworks/js/napi/observer/include/napi_observer.h index a50a768b..56554fec 100644 --- a/data_share/frameworks/js/napi/observer/include/napi_observer.h +++ b/data_share/frameworks/js/napi/observer/include/napi_observer.h @@ -19,9 +19,9 @@ #include #include "datashare_template.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace DataShare { diff --git a/data_share/frameworks/js/napi/observer/include/napi_subscriber_manager.h b/data_share/frameworks/js/napi/observer/include/napi_subscriber_manager.h index 246aedfd..16068300 100644 --- a/data_share/frameworks/js/napi/observer/include/napi_subscriber_manager.h +++ b/data_share/frameworks/js/napi/observer/include/napi_subscriber_manager.h @@ -21,9 +21,9 @@ #include "napi_callbacks_manager.h" #include "datashare_helper.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_observer.h" namespace OHOS { diff --git a/data_share/frameworks/native/consumer/src/datashare_connection.cpp b/data_share/frameworks/native/consumer/src/datashare_connection.cpp index 5d133790..9c0d87f0 100644 --- a/data_share/frameworks/native/consumer/src/datashare_connection.cpp +++ b/data_share/frameworks/native/consumer/src/datashare_connection.cpp @@ -91,6 +91,8 @@ std::shared_ptr DataShareConnection::ConnectDataShareExtAbility( if (condition_.condition.wait_for(lock, std::chrono::seconds(WAIT_TIME), [this] { return dataShareProxy_ != nullptr; })) { LOG_DEBUG("connect ability ended successfully"); + } else { + LOG_WARN("connect timeout"); } return dataShareProxy_; } diff --git a/data_share/frameworks/native/provider/include/datashare_uv_queue.h b/data_share/frameworks/native/provider/include/datashare_uv_queue.h index deffbac9..6a511082 100644 --- a/data_share/frameworks/native/provider/include/datashare_uv_queue.h +++ b/data_share/frameworks/native/provider/include/datashare_uv_queue.h @@ -20,9 +20,9 @@ #include #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "uv.h" namespace OHOS { diff --git a/data_share/frameworks/native/provider/include/js_datashare_ext_ability.h b/data_share/frameworks/native/provider/include/js_datashare_ext_ability.h index ad6b2598..bd8b333a 100644 --- a/data_share/frameworks/native/provider/include/js_datashare_ext_ability.h +++ b/data_share/frameworks/native/provider/include/js_datashare_ext_ability.h @@ -21,9 +21,9 @@ #include "datashare_predicates.h" #include "datashare_ext_ability.h" #include "js_runtime.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "datashare_business_error.h" namespace OHOS { diff --git a/data_share/frameworks/native/provider/src/js_datashare_ext_ability_context.cpp b/data_share/frameworks/native/provider/src/js_datashare_ext_ability_context.cpp index 2ed0c5ee..96c367f3 100644 --- a/data_share/frameworks/native/provider/src/js_datashare_ext_ability_context.cpp +++ b/data_share/frameworks/native/provider/src/js_datashare_ext_ability_context.cpp @@ -21,7 +21,7 @@ #include "js_extension_context.h" #include "js_runtime.h" #include "js_runtime_utils.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" +#include "napi/native_api.h" #include "napi_common_want.h" #include "napi_remote_object.h" #include "napi_common_start_options.h" diff --git a/data_share/interfaces/inner_api/BUILD.gn b/data_share/interfaces/inner_api/BUILD.gn index 44567d4f..41f542f5 100644 --- a/data_share/interfaces/inner_api/BUILD.gn +++ b/data_share/interfaces/inner_api/BUILD.gn @@ -81,8 +81,8 @@ datashare_consumer_external_deps = [ "c_utils:utils", "common_event_service:cesfwk_innerkits", "hilog:libhilog", + "ipc:ipc_js", "ipc:ipc_single", - "ipc_js:rpc", "napi:ace_napi", "samgr:samgr_proxy", ] @@ -135,8 +135,8 @@ ohos_shared_library("datashare_provider") { "c_utils:utils", "common_event_service:cesfwk_innerkits", "hilog:libhilog", + "ipc:ipc_js", "ipc:ipc_single", - "ipc_js:rpc", "napi:ace_napi", "samgr:samgr_proxy", ] diff --git a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/MainAbility/MainAbility.ts b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/MainAbility/MainAbility.ts index 49007213..cf043091 100644 --- a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/MainAbility/MainAbility.ts +++ b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/MainAbility/MainAbility.ts @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2023 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 @@ -45,18 +45,44 @@ export default class MainAbility extends Ability { console.log("[ttt] [DataShareTest] <> MainAbility onWindowStageCreate") globalThis.abilityContext = this.context; console.log("[ttt] [DataShareTest] <> MainAbility this.context.databaseDir:" + this.context.databaseDir); + + this.connectDataShareExtAbility(); + this.disconnectDataShareExtAbility(); + this.on(); + this.off(); + this.openFile(); + this.query(); + this.insert(); + this.update(); + this.delete(); + this.batchInsert(); + this.notifyChange(); + this.getType(); + this.getFileTypes(); + this.normalizeUri(); + this.denormalizeUri(); + + windowStage.setUIContent(this.context, "pages/index", null) + } + + connectDataShareExtAbility() { globalThis.connectDataShareExtAbility = (async () => { console.log("[ttt] [DataShareTest] <> connectDataShareExtAbility begin"); globalThis.dsHelper = await dataShare.createDataShareHelper(this.context, dseUri); console.log("[ttt] [DataShareTest] <> connectDataShareExtAbility end"); }) + } + disconnectDataShareExtAbility() { globalThis.disconnectDataShareExtAbility = (async () => { console.log("[ttt] [DataShareTest] <> disconnectDataShareExtAbility begin"); globalThis.dsHelper = null; console.log("[ttt] [DataShareTest] <> disconnectDataShareExtAbility end"); }) + } + + on() { globalThis.on = (async () => { console.log("[ttt] [DataShareTest] <> on begin"); if (globalThis.dsHelper == null) { @@ -65,8 +91,10 @@ export default class MainAbility extends Ability { } await globalThis.dsHelper.on("dataChange", uri, onCallback); console.log("[ttt] [DataShareTest] <> on end"); - }) - + }) + } + + off() { globalThis.off = (async () => { console.log("[ttt] [DataShareTest] <> off begin"); if (globalThis.dsHelper == null) { @@ -77,7 +105,9 @@ export default class MainAbility extends Ability { await globalThis.dsHelper.off("dataChange", uri, offCallback); console.log("[ttt] [DataShareTest] <> off end"); }) + } + openFile() { globalThis.openFile = (async () => { console.log("[ttt] [DataShareTest] <> openFile begin"); if (globalThis.dsHelper == null) { @@ -88,7 +118,9 @@ export default class MainAbility extends Ability { console.log("[ttt] [DataShareTest] <> openFile end, result:" + result); return result; }) + } + query() { globalThis.query = (async () => { console.log("[ttt] [DataShareTest] <> query begin"); let da = new dataSharePredicates.DataSharePredicates(); @@ -109,7 +141,9 @@ export default class MainAbility extends Ability { console.log("[ttt] [DataShareTest] <> query end, count:" + count); return count; }) + } + insert() { globalThis.insert = (async () => { console.log("[ttt] [DataShareTest] <> insert begin"); if (globalThis.dsHelper == null) { @@ -123,7 +157,9 @@ export default class MainAbility extends Ability { await console.log("[ttt] [DataShareTest] <> insert end, ret:" + ret); return ret; }) + } + update() { globalThis.update = (async () => { console.log("[ttt] [DataShareTest] <> update begin"); if (globalThis.dsHelper == null) { @@ -143,7 +179,9 @@ export default class MainAbility extends Ability { console.log("[ttt] [DataShareTest] <> update end, result:" + ret); return ret; }) + } + delete() { globalThis.delete = (async () => { console.log("[ttt] [DataShareTest] <> delete begin"); if (globalThis.dsHelper == null) { @@ -160,7 +198,9 @@ export default class MainAbility extends Ability { console.log("[ttt] [DataShareTest] <> delete end, result:" + ret); return ret; }) + } + batchInsert() { globalThis.batchInsert = (async () => { console.log("[ttt] [DataShareTest] <> batchInsert begin"); if (globalThis.dsHelper == null) { @@ -177,7 +217,9 @@ export default class MainAbility extends Ability { console.log("[ttt] [DataShareTest] <> batchInsert end, result:" + ret); return ret; }) + } + notifyChange() { globalThis.notifyChange = (async () => { console.log("[ttt] [DataShareTest] <> notifyChange begin"); if (globalThis.dsHelper == null) { @@ -187,7 +229,9 @@ export default class MainAbility extends Ability { await globalThis.dsHelper.notifyChange(dseUri); console.log("[ttt] [DataShareTest] <> notifyChange end"); }) - + } + + getType() { globalThis.getType = (async () => { console.log("[ttt] [DataShareTest] <> getType begin"); if (globalThis.dsHelper == null) { @@ -198,7 +242,9 @@ export default class MainAbility extends Ability { console.log("[ttt] [DataShareTest] <> getType end, result:" + result); return result; }) + } + getFileTypes() { globalThis.getFileTypes = (async () => { console.log("[ttt] [DataShareTest] <> getFileTypes begin"); if (globalThis.dsHelper == null) { @@ -209,7 +255,9 @@ export default class MainAbility extends Ability { console.log("[ttt] [DataShareTest] <> getFileTypes end, result:" + result); return result; }) + } + normalizeUri() { globalThis.normalizeUri = (async () => { console.log("[ttt] [DataShareTest] <> normalizeUri begin"); if (globalThis.dsHelper == null) { @@ -220,7 +268,9 @@ export default class MainAbility extends Ability { console.log("[ttt] [DataShareTest] <> normalizeUri end, result:" + result); return result; }) + } + denormalizeUri() { globalThis.denormalizeUri = (async () => { console.log("[ttt] [DataShareTest] <> denormalizeUri begin"); if (globalThis.dsHelper == null) { @@ -231,8 +281,6 @@ export default class MainAbility extends Ability { console.log("[ttt] [DataShareTest] <> denormalizeUri end, result:" + result); return result; }) - - windowStage.setUIContent(this.context, "pages/index", null) } onWindowStageDestroy() { diff --git a/data_share/test/native/unittest/mediadatashare_test/include/mediadatashare_unit_test.h b/data_share/test/native/unittest/mediadatashare_test/include/mediadatashare_unit_test.h index 65e0458e..31b34467 100644 --- a/data_share/test/native/unittest/mediadatashare_test/include/mediadatashare_unit_test.h +++ b/data_share/test/native/unittest/mediadatashare_test/include/mediadatashare_unit_test.h @@ -20,6 +20,7 @@ #include #include "data_ability_observer_interface.h" #include "datashare_helper.h" +#include "data_ability_observer_stub.h" namespace OHOS { namespace DataShare { @@ -41,7 +42,7 @@ public: bool ChangeInfoEqual(const ChangeInfo &changeInfo, const ChangeInfo &expectChangeInfo); }; -class IDataAbilityObserverTest : public AAFwk::IDataAbilityObserver { +class IDataAbilityObserverTest : public AAFwk::DataAbilityObserverStub { public: IDataAbilityObserverTest(); ~IDataAbilityObserverTest() diff --git a/data_share/test/native/unittest/mediadatashare_test/src/errorcode_test.cpp b/data_share/test/native/unittest/mediadatashare_test/src/errorcode_test.cpp index 168c40e1..a5402f36 100644 --- a/data_share/test/native/unittest/mediadatashare_test/src/errorcode_test.cpp +++ b/data_share/test/native/unittest/mediadatashare_test/src/errorcode_test.cpp @@ -28,12 +28,12 @@ namespace DataShare { using namespace testing::ext; using namespace OHOS::Security::AccessToken; constexpr int STORAGE_MANAGER_MANAGER_ID = 5003; -static std::string DATA_SHARE_URI = "datashare:///com.acts.errorcodetest"; -static std::string SLIENT_ACCESS_URI = "datashare:///com.acts.errorcodetest/entry/DB00/TBL00?Proxy=true"; -static std::string TBL_STU_NAME = "name"; -static std::string TBL_STU_AGE = "age"; -static std::shared_ptr g_slientAccessHelper; -static std::shared_ptr dataShareHelper; +std::string DATA_SHARE_URI = "datashare:///com.acts.errorcodetest"; +std::string SLIENT_ACCESS_URI = "datashare:///com.acts.errorcodetest/entry/DB00/TBL00?Proxy=true"; +std::string TBL_STU_NAME = "name"; +std::string TBL_STU_AGE = "age"; +std::shared_ptr g_slientAccessHelper; +std::shared_ptr dataShareHelper; class ErrorCodeTest : public testing::Test { public: diff --git a/data_share/test/native/unittest/mediadatashare_test/src/join_test.cpp b/data_share/test/native/unittest/mediadatashare_test/src/join_test.cpp index b3c59e69..20015ea1 100644 --- a/data_share/test/native/unittest/mediadatashare_test/src/join_test.cpp +++ b/data_share/test/native/unittest/mediadatashare_test/src/join_test.cpp @@ -29,13 +29,13 @@ namespace DataShare { using namespace testing::ext; using namespace OHOS::Security::AccessToken; constexpr int STORAGE_MANAGER_MANAGER_ID = 5003; -static std::string DATA_SHARE_URI = "datashare:///com.acts.datasharetest"; -static std::string SLIENT_ACCESS_URI = "datashare:///com.acts.datasharetest?Proxy=true"; -static std::string USER_URI = "datashare:///com.acts.datasharetest/entry/DB00/user?Proxy=true"; -static std::string BOOK_URI = "datashare:///com.acts.datasharetest/entry/DB00/book?Proxy=true"; -static std::string TBL_STU_NAME = "name"; -static std::string TBL_STU_AGE = "age"; -static std::shared_ptr g_slientAccessHelper; +std::string DATA_SHARE_URI = "datashare:///com.acts.datasharetest"; +std::string SLIENT_ACCESS_URI = "datashare:///com.acts.datasharetest?Proxy=true"; +std::string USER_URI = "datashare:///com.acts.datasharetest/entry/DB00/user?Proxy=true"; +std::string BOOK_URI = "datashare:///com.acts.datasharetest/entry/DB00/book?Proxy=true"; +std::string TBL_STU_NAME = "name"; +std::string TBL_STU_AGE = "age"; +std::shared_ptr g_slientAccessHelper; class JoinTest : public testing::Test { public: @@ -46,10 +46,9 @@ public: static void InsertUserDates(); static void InsertBookDates(); int ResultSize(std::shared_ptr &resultSet); - static std::shared_ptr CreateDataShareHelper(int32_t systemAbilityId, std::string uri); }; -std::shared_ptr JoinTest::CreateDataShareHelper(int32_t systemAbilityId, std::string uri) +std::shared_ptr CreateDataShareHelper(int32_t systemAbilityId, std::string uri) { LOG_INFO("CreateDataShareHelper start"); auto saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); diff --git a/data_share/test/native/unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp b/data_share/test/native/unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp index 6757f174..1f198f6b 100644 --- a/data_share/test/native/unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp +++ b/data_share/test/native/unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp @@ -95,13 +95,13 @@ public: }; constexpr int STORAGE_MANAGER_MANAGER_ID = 5003; -static std::string DATA_SHARE_URI = "datashare:///com.acts.datasharetest"; -static std::string MEDIALIBRARY_DATA_URI = "datashare:///com.acts.datasharetest"; -static std::string MEDIALIBRARY_DATA_URI_ERROR = "test:///com.acts.datasharetest"; -static std::string FILE_DATA_URI = "file://com.acts.datasharetest"; -static std::string NORMALIZE_URI = "normalize+datashare:///com.acts.datasharetest"; -static std::string DENORMALIZE_URI = "denormalize+datashare:///com.acts.datasharetest"; -static std::shared_ptr g_dataShareHelper; +std::string DATA_SHARE_URI = "datashare:///com.acts.datasharetest"; +std::string MEDIALIBRARY_DATA_URI = "datashare:///com.acts.datasharetest"; +std::string MEDIALIBRARY_DATA_URI_ERROR = "test:///com.acts.datasharetest"; +std::string FILE_DATA_URI = "file://com.acts.datasharetest"; +std::string NORMALIZE_URI = "normalize+datashare:///com.acts.datasharetest"; +std::string DENORMALIZE_URI = "denormalize+datashare:///com.acts.datasharetest"; +std::shared_ptr g_dataShareHelper; std::shared_ptr CreateDataShareHelper(int32_t systemAbilityId) { diff --git a/data_share/test/native/unittest/mediadatashare_test/src/slientaccess_test.cpp b/data_share/test/native/unittest/mediadatashare_test/src/slientaccess_test.cpp index 28481574..b1470258 100644 --- a/data_share/test/native/unittest/mediadatashare_test/src/slientaccess_test.cpp +++ b/data_share/test/native/unittest/mediadatashare_test/src/slientaccess_test.cpp @@ -28,11 +28,11 @@ namespace DataShare { using namespace testing::ext; using namespace OHOS::Security::AccessToken; constexpr int STORAGE_MANAGER_MANAGER_ID = 5003; -static std::string DATA_SHARE_URI = "datashare:///com.acts.datasharetest"; -static std::string SLIENT_ACCESS_URI = "datashare:///com.acts.datasharetest/entry/DB00/TBL00?Proxy=true"; -static std::string TBL_STU_NAME = "name"; -static std::string TBL_STU_AGE = "age"; -static std::shared_ptr g_slientAccessHelper; +std::string DATA_SHARE_URI = "datashare:///com.acts.datasharetest"; +std::string SLIENT_ACCESS_URI = "datashare:///com.acts.datasharetest/entry/DB00/TBL00?Proxy=true"; +std::string TBL_STU_NAME = "name"; +std::string TBL_STU_AGE = "age"; +std::shared_ptr g_slientAccessHelper; class SlientAccessTest : public testing::Test { public: @@ -40,10 +40,9 @@ public: static void TearDownTestCase(void); void SetUp(); void TearDown(); - static std::shared_ptr CreateDataShareHelper(int32_t systemAbilityId, std::string uri); }; -std::shared_ptr SlientAccessTest::CreateDataShareHelper(int32_t systemAbilityId, std::string uri) +std::shared_ptr CreateDataShareHelper(int32_t systemAbilityId, std::string uri) { LOG_INFO("CreateDataShareHelper start"); auto saManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); diff --git a/datamgr_service/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp b/datamgr_service/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp index 4b435d1e..54418409 100644 --- a/datamgr_service/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp +++ b/datamgr_service/services/distributeddataservice/adapter/communicator/src/process_communicator_impl.cpp @@ -203,7 +203,7 @@ void ProcessCommunicatorImpl::OnMessage(const DeviceInfo &info, const uint8_t *p void ProcessCommunicatorImpl::OnDeviceChanged(const DeviceInfo &info, const DeviceChangeType &type) const { - if (type == DeviceChangeType::DEVICE_ONREADY) { + if (type == DeviceChangeType::DEVICE_ONREADY || info.uuid == DmAdapter::CLOUD_DEVICE_UUID) { return; } std::lock_guard onDeviceChangeLockGuard(onDeviceChangeMutex_); @@ -250,4 +250,4 @@ DBStatus ProcessCommunicatorImpl::CheckAndGetDataHeadInfo( return DBStatus::OK; } } // namespace AppDistributedKv -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/adapter/communicator/test/unittest/device_manager_adapter_test.cpp b/datamgr_service/services/distributeddataservice/adapter/communicator/test/unittest/device_manager_adapter_test.cpp index 2842a2fc..b3f03b75 100644 --- a/datamgr_service/services/distributeddataservice/adapter/communicator/test/unittest/device_manager_adapter_test.cpp +++ b/datamgr_service/services/distributeddataservice/adapter/communicator/test/unittest/device_manager_adapter_test.cpp @@ -41,7 +41,7 @@ void GrantPermissionNative() { const char **perms = new const char *[2]; perms[0] = "ohos.permission.DISTRIBUTED_DATASYNC"; - perms[1] = "ohos.permission.ACCERSS_SERVICE_DM"; + perms[1] = "ohos.permission.ACCESS_SERVICE_DM"; TokenInfoParams infoInstance = { .dcapsNum = 0, .permsNum = 2, diff --git a/datamgr_service/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h b/datamgr_service/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h index a22f203f..1806e569 100644 --- a/datamgr_service/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h +++ b/datamgr_service/services/distributeddataservice/adapter/include/communicator/device_manager_adapter.h @@ -85,7 +85,7 @@ private: static constexpr int32_t SYNC_TIMEOUT = 10 * 1000; // ms ConcurrentMap syncTask_ {}; std::shared_ptr executors_; - bool isNetAvailable_ = true; + bool isNetAvailable_ = false; }; } // namespace DistributedData } // namespace OHOS diff --git a/datamgr_service/services/distributeddataservice/app/BUILD.gn b/datamgr_service/services/distributeddataservice/app/BUILD.gn index ccb08f5b..b703e19e 100644 --- a/datamgr_service/services/distributeddataservice/app/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/app/BUILD.gn @@ -39,6 +39,7 @@ config("module_private_config") { visibility = [ ":*" ] include_dirs = [ "${kv_store_common_path}", + "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service/bootstrap/include", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/service/config/include", @@ -79,6 +80,7 @@ ohos_shared_library("distributeddataservice") { "src/feature_stub_impl.cpp", "src/kvstore_account_observer.cpp", "src/kvstore_data_service.cpp", + "src/kvstore_data_service_stub.cpp", "src/kvstore_device_listener.cpp", "src/kvstore_meta_manager.cpp", "src/security/security.cpp", @@ -123,6 +125,7 @@ ohos_shared_library("distributeddataservice") { "hitrace:libhitracechain", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", "kv_store:distributeddb", "safwk:system_ability_fwk", "samgr:samgr_proxy", diff --git a/datamgr_service/services/distributeddataservice/app/src/flowctrl_manager/BUILD.gn b/datamgr_service/services/distributeddataservice/app/src/flowctrl_manager/BUILD.gn index eae2ee83..274d8847 100644 --- a/datamgr_service/services/distributeddataservice/app/src/flowctrl_manager/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/app/src/flowctrl_manager/BUILD.gn @@ -20,6 +20,7 @@ ohos_static_library("distributeddata_flowctrl_static") { include_dirs = [ "../../../adapter/include/account", "../../src", + "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", "${kv_store_path}/interfaces/innerkits/distributeddata/include", "//third_party/json/single_include", diff --git a/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.cpp b/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.cpp index 1de9f38e..23de8bd5 100644 --- a/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.cpp +++ b/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.cpp @@ -19,6 +19,7 @@ #include #include +#include "accesstoken_kit.h" #include "auth_delegate.h" #include "auto_launch_export.h" #include "bootstrap.h" @@ -59,6 +60,7 @@ namespace OHOS::DistributedKv { using namespace std::chrono; using namespace OHOS::DistributedData; using namespace OHOS::DistributedDataDfx; +using namespace OHOS::Security::AccessToken; using KvStoreDelegateManager = DistributedDB::KvStoreDelegateManager; using SecretKeyMeta = DistributedData::SecretKeyMetaData; using DmAdapter = DistributedData::DeviceManagerAdapter; @@ -67,7 +69,7 @@ using DBConfig = DistributedDB::RuntimeConfig; REGISTER_SYSTEM_ABILITY_BY_ID(KvStoreDataService, DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID, true); KvStoreDataService::KvStoreDataService(bool runOnCreate) - : SystemAbility(runOnCreate), clients_() + : SystemAbility(runOnCreate), mutex_(), clients_() { ZLOGI("begin."); if (executors_ == nullptr) { @@ -79,7 +81,7 @@ KvStoreDataService::KvStoreDataService(bool runOnCreate) } KvStoreDataService::KvStoreDataService(int32_t systemAbilityId, bool runOnCreate) - : SystemAbility(systemAbilityId, runOnCreate), clients_() + : SystemAbility(systemAbilityId, runOnCreate), mutex_(), clients_() { ZLOGI("begin"); if (executors_ == nullptr) { @@ -93,7 +95,7 @@ KvStoreDataService::KvStoreDataService(int32_t systemAbilityId, bool runOnCreate KvStoreDataService::~KvStoreDataService() { ZLOGI("begin."); - clients_.Clear(); + clients_.clear(); features_.Clear(); } @@ -188,23 +190,22 @@ Status KvStoreDataService::RegisterClientDeathObserver(const AppId &appId, sptr< ZLOGW("check bundleName:%{public}s uid:%{public}d failed.", appId.appId.c_str(), info.uid); return Status::PERMISSION_DENIED; } - auto pid = IPCSkeleton::GetCallingPid(); - bool isSuccess = true; - clients_.Compute(info.tokenId, - [&isSuccess, &appId, &info, pid, this, obs = std::move(observer)](const auto tokenId, auto &clients) { - auto res = clients.try_emplace(info.tokenId, appId, *this, std::move(obs)); - isSuccess = res.second; - if (!isSuccess) { - ZLOGW("bundleName:%{public}s, uid:%{public}d, pid:%{public}d has already registered.", - appId.appId.c_str(), info.uid, IPCSkeleton::GetCallingPid()); - } else { - ZLOGI("bundleName:%{public}s, uid:%{public}d, pid:%{public}d inserted:success.", appId.appId.c_str(), - info.uid, pid, isSuccess ? "success" : "failed"); - } - return !clients.empty(); - }); - return isSuccess ? Status::SUCCESS : Status::ERROR; + std::lock_guard lg(mutex_); + auto iter = clients_.find(info.tokenId); + // Ignore register with same tokenId and pid + if (iter != clients_.end() && IPCSkeleton::GetCallingPid() == iter->second.GetPid()) { + ZLOGW("bundleName:%{public}s, uid:%{public}d, pid:%{public}d has already registered.", + appId.appId.c_str(), info.uid, IPCSkeleton::GetCallingPid()); + return Status::SUCCESS; + } + + clients_.erase(info.tokenId); + auto it = clients_.emplace(std::piecewise_construct, std::forward_as_tuple(info.tokenId), + std::forward_as_tuple(appId, *this, std::move(observer))); + ZLOGI("bundleName:%{public}s, uid:%{public}d, pid:%{public}d inserted:%{public}s.", + appId.appId.c_str(), info.uid, IPCSkeleton::GetCallingPid(), it.second ? "success" : "failed"); + return it.second ? Status::SUCCESS : Status::ERROR; } Status KvStoreDataService::AppExit(pid_t uid, pid_t pid, uint32_t token, const AppId &appId) @@ -213,10 +214,8 @@ Status KvStoreDataService::AppExit(pid_t uid, pid_t pid, uint32_t token, const A // memory of parameter appId locates in a member of clientDeathObserverMap_ and will be freed after // clientDeathObserverMap_ erase, so we have to take a copy if we want to use this parameter after erase operation. AppId appIdTmp = appId; - clients_.ComputeIfPresent(token, [pid](const auto tokenId, auto &clients) { - clients.erase(pid); - return !clients.empty(); - }); + std::lock_guard lg(mutex_); + clients_.erase(token); return Status::SUCCESS; } @@ -597,7 +596,7 @@ void KvStoreDataService::AccountEventChanged(const AccountEventInfo &eventInfo) if (meta.user != eventInfo.userId) { continue; } - ZLOGI("bundleName:%{public}s, user:%{public}s", meta.bundleName.c_str(), meta.user.c_str()); + ZLOGI("bundlname:%s, user:%s", meta.bundleName.c_str(), meta.user.c_str()); MetaDataManager::GetInstance().DelMeta(meta.GetKey()); MetaDataManager::GetInstance().DelMeta(meta.GetStrategyKey()); MetaDataManager::GetInstance().DelMeta(meta.GetSecretKey(), true); @@ -690,21 +689,61 @@ void KvStoreDataService::OnDeviceOnReady(const AppDistributedKv::DeviceInfo &inf int32_t KvStoreDataService::OnUninstall(const std::string &bundleName, int32_t user, int32_t index) { - features_.ForEachCopies( - [bundleName, user, index](const auto &, sptr &value) { - value->OnAppUninstall(bundleName, user, index); - return false; - }); + auto staticActs = FeatureSystem::GetInstance().GetStaticActs(); + staticActs.ForEachCopies([bundleName, user, index](const auto &, const std::shared_ptr& acts) { + acts->OnAppUninstall(bundleName, user, index); + return false; + }); return SUCCESS; } int32_t KvStoreDataService::OnUpdate(const std::string &bundleName, int32_t user, int32_t index) { - features_.ForEachCopies( - [bundleName, user, index](const auto &, sptr &value) { - value->OnAppUpdate(bundleName, user, index); + auto staticActs = FeatureSystem::GetInstance().GetStaticActs(); + staticActs.ForEachCopies([bundleName, user, index](const auto &, const std::shared_ptr& acts) { + acts->OnAppUpdate(bundleName, user, index); + return false; + }); + return SUCCESS; +} + +int32_t KvStoreDataService::ClearAppStorage(const std::string &bundleName, int32_t userId, int32_t appIndex, + int32_t tokenId) +{ + HapTokenInfo hapTokenInfo; + if (AccessTokenKit::GetHapTokenInfo(tokenId, hapTokenInfo) != RET_SUCCESS || + hapTokenInfo.tokenID != static_cast(tokenId)) { + ZLOGE("passed wrong tokenId: %{public}d", tokenId); + return ERROR; + } + auto staticActs = FeatureSystem::GetInstance().GetStaticActs(); + staticActs.ForEachCopies( + [bundleName, userId, appIndex, tokenId](const auto &, const std::shared_ptr &acts) { + acts->OnClearAppStorage(bundleName, userId, appIndex, tokenId); return false; }); - return 0; + + std::vector metaData; + std::string prefix = StoreMetaData::GetPrefix( + { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid, std::to_string(userId), "default", bundleName }); + if (!MetaDataManager::GetInstance().LoadMeta(prefix, metaData)) { + ZLOGE("Clear data load meta failed, bundleName:%{public}s, user:%{public}d, appIndex:%{public}d", + bundleName.c_str(), userId, appIndex); + return ERROR; + } + + for (auto &meta : metaData) { + if (meta.instanceId == appIndex && !meta.appId.empty() && !meta.storeId.empty()) { + ZLOGI("data cleared bundleName:%{public}s, stordId:%{public}s, appIndex:%{public}d", bundleName.c_str(), + Anonymous::Change(meta.storeId).c_str(), appIndex); + MetaDataManager::GetInstance().DelMeta(meta.GetKey()); + MetaDataManager::GetInstance().DelMeta(meta.GetSecretKey(), true); + MetaDataManager::GetInstance().DelMeta(meta.GetStrategyKey()); + MetaDataManager::GetInstance().DelMeta(meta.appId, true); + MetaDataManager::GetInstance().DelMeta(meta.GetKeyLocal(), true); + PermitDelegate::GetInstance().DelCache(meta.GetKey()); + } + } + return SUCCESS; } } // namespace OHOS::DistributedKv diff --git a/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.h b/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.h index 90b9be7d..b67fbd97 100644 --- a/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.h +++ b/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service.h @@ -27,6 +27,7 @@ #include "ithread_pool.h" #include "kvstore_device_listener.h" #include "kvstore_meta_manager.h" +#include "kvstore_data_service_stub.h" #include "metadata/store_meta_data.h" #include "reporter.h" #include "runtime_config.h" @@ -53,6 +54,8 @@ public: sptr GetFeatureInterface(const std::string &name) override; + int32_t ClearAppStorage(const std::string &bundleName, int32_t userId, int32_t appIndex, int32_t tokenId) override; + void OnDump() override; int Dump(int fd, const std::vector &args) override; @@ -129,7 +132,8 @@ private: static constexpr int TEN_SEC = 10; - ConcurrentMap> clients_; + std::mutex mutex_; + std::map clients_; std::shared_ptr accountEventObserver_; std::shared_ptr security_; diff --git a/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service_stub.cpp b/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service_stub.cpp new file mode 100644 index 00000000..f8a13daa --- /dev/null +++ b/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service_stub.cpp @@ -0,0 +1,91 @@ +/* +* Copyright (c) 2023 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. +*/ + +#define LOG_TAG "KvStoreDataServiceStub" + +#include "kvstore_data_service_stub.h" +#include +#include "itypes_util.h" +#include "message_parcel.h" +#include "types.h" +#include "log_print.h" + +namespace OHOS { +namespace DistributedKv { +constexpr KvStoreDataServiceStub::RequestHandler + KvStoreDataServiceStub::HANDLERS[static_cast(KvStoreDataServiceInterfaceCode::SERVICE_CMD_LAST)]; + +int32_t KvStoreDataServiceStub::RegisterClientDeathObserverOnRemote(MessageParcel &data, MessageParcel &reply) +{ + AppId appId = { data.ReadString() }; + sptr kvStoreClientDeathObserverProxy = data.ReadRemoteObject(); + if (kvStoreClientDeathObserverProxy == nullptr) { + return -1; + } + Status status = RegisterClientDeathObserver(appId, std::move(kvStoreClientDeathObserverProxy)); + if (!reply.WriteInt32(static_cast(status))) { + return -1; + } + return 0; +} + +int32_t KvStoreDataServiceStub::GetFeatureInterfaceOnRemote(MessageParcel &data, MessageParcel &reply) +{ + std::string name; + if (!ITypesUtil::Unmarshal(data, name)) { + return -1; + } + auto remoteObject = GetFeatureInterface(name); + if (!ITypesUtil::Marshal(reply, remoteObject)) { + return -1; + } + return 0; +} + +int32_t KvStoreDataServiceStub::ClearAppStorageOnRemote(MessageParcel &data, MessageParcel &reply) +{ + std::string bundleName; + int32_t userId; + int32_t appIndex; + int32_t tokenId; + if (!ITypesUtil::Unmarshal(data, bundleName, userId, appIndex, tokenId)) { + return -1; + } + auto remoteObject = ClearAppStorage(bundleName, userId, appIndex, tokenId); + if (!ITypesUtil::Marshal(reply, remoteObject)) { + return -1; + } + return 0; +} + +int32_t KvStoreDataServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) +{ + ZLOGD("code:%{public}u, callingPid:%{public}d", code, IPCSkeleton::GetCallingPid()); + std::u16string descriptor = KvStoreDataServiceStub::GetDescriptor(); + std::u16string remoteDescriptor = data.ReadInterfaceToken(); + if (descriptor != remoteDescriptor) { + ZLOGE("local descriptor is not equal to remote"); + return -1; + } + if (code >= 0 && code < static_cast(KvStoreDataServiceInterfaceCode::SERVICE_CMD_LAST)) { + return (this->*HANDLERS[code])(data, reply); + } else { + MessageOption mo{ MessageOption::TF_SYNC }; + return IPCObjectStub::OnRemoteRequest(code, data, reply, mo); + } +} +} // namespace DistributedKv +} // namespace OHOS diff --git a/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service_stub.h b/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service_stub.h new file mode 100644 index 00000000..08767f6d --- /dev/null +++ b/datamgr_service/services/distributeddataservice/app/src/kvstore_data_service_stub.h @@ -0,0 +1,39 @@ +/* +* Copyright (c) 2023 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 KVSTORE_DATA_SERVICE_STUB_H +#define KVSTORE_DATA_SERVICE_STUB_H +#include "ikvstore_data_service.h" +#include "distributeddata_ipc_interface_code.h" +namespace OHOS::DistributedKv { +class API_EXPORT KvStoreDataServiceStub : public IRemoteStub { +public: + int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, + MessageOption &option) override; + +private: + int32_t GetFeatureInterfaceOnRemote(MessageParcel &data, MessageParcel &reply); + int32_t RegisterClientDeathObserverOnRemote(MessageParcel &data, MessageParcel &reply); + int32_t ClearAppStorageOnRemote(MessageParcel &data, MessageParcel &reply); + + using RequestHandler = int32_t (KvStoreDataServiceStub::*)(MessageParcel &, MessageParcel &); + using code = KvStoreDataServiceInterfaceCode; + static constexpr RequestHandler HANDLERS[static_cast(code::SERVICE_CMD_LAST)] = { + &KvStoreDataServiceStub::GetFeatureInterfaceOnRemote, + &KvStoreDataServiceStub::RegisterClientDeathObserverOnRemote, + &KvStoreDataServiceStub::ClearAppStorageOnRemote, + }; +}; +} // namespace OHOS::DistributedKv +#endif // KVSTORE_DATA_SERVICE_STUB_H diff --git a/datamgr_service/services/distributeddataservice/app/src/uninstaller/BUILD.gn b/datamgr_service/services/distributeddataservice/app/src/uninstaller/BUILD.gn index aa9913b8..87cf3b89 100644 --- a/datamgr_service/services/distributeddataservice/app/src/uninstaller/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/app/src/uninstaller/BUILD.gn @@ -23,6 +23,7 @@ ohos_static_library("distributeddata_uninstaller_static") { include_dirs = [ "../../../adapter/include/account", "../../src", + "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", "${kv_store_path}/interfaces/innerkits/distributeddata/include", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework/include", diff --git a/datamgr_service/services/distributeddataservice/app/test/BUILD.gn b/datamgr_service/services/distributeddataservice/app/test/BUILD.gn index 0b51ae59..42bdfd5c 100644 --- a/datamgr_service/services/distributeddataservice/app/test/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/app/test/BUILD.gn @@ -19,6 +19,7 @@ module_output_path = "datamgr_service/distributeddataservice" config("module_private_config") { visibility = [ ":*" ] include_dirs = [ + "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "//foundation/distributeddatamgr/kv_store/frameworks/common", "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/include", "//foundation/distributeddatamgr/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src", @@ -69,6 +70,7 @@ ohos_unittest("KvStoreDataServiceTest") { "../src/feature_stub_impl.cpp", "../src/kvstore_account_observer.cpp", "../src/kvstore_data_service.cpp", + "../src/kvstore_data_service_stub.cpp", "../src/kvstore_device_listener.cpp", "../src/kvstore_meta_manager.cpp", "../src/security/security.cpp", @@ -104,6 +106,7 @@ ohos_unittest("KvStoreDataServiceTest") { } deps = [ + "${kv_store_path}/interfaces/innerkits/distributeddatamgr:distributeddata_mgr", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter:distributeddata_adapter", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter/broadcaster:distributeddata_broadcaster_static", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter/utils:distributeddata_utils_static", @@ -154,6 +157,7 @@ ohos_unittest("SessionManagerTest") { } deps = [ + "${kv_store_path}/interfaces/innerkits/distributeddatamgr:distributeddata_mgr", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter:distributeddata_adapter", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter/broadcaster:distributeddata_broadcaster_static", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter/utils:distributeddata_utils_static", @@ -193,6 +197,7 @@ ohos_unittest("KvStoreFlowCtrlManagerTest") { } deps = [ + "${kv_store_path}/interfaces/innerkits/distributeddatamgr:distributeddata_mgr", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/adapter:distributeddata_adapter", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/app/src/flowctrl_manager:distributeddata_flowctrl_static", "//foundation/distributeddatamgr/datamgr_service/services/distributeddataservice/framework:distributeddatasvcfwk", diff --git a/datamgr_service/services/distributeddataservice/app/test/fuzztest/dataservicestub_fuzzer/BUILD.gn b/datamgr_service/services/distributeddataservice/app/test/fuzztest/dataservicestub_fuzzer/BUILD.gn index 3e594bee..822c306c 100644 --- a/datamgr_service/services/distributeddataservice/app/test/fuzztest/dataservicestub_fuzzer/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/app/test/fuzztest/dataservicestub_fuzzer/BUILD.gn @@ -22,6 +22,7 @@ ohos_fuzztest("DataServiceStubFuzzTest") { include_dirs = [ "${kv_store_common_path}", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", + "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "${data_service_path}/service/bootstrap/include", "${data_service_path}/service/config/include", "${data_service_path}/service/crypto/include", @@ -65,6 +66,7 @@ ohos_fuzztest("DataServiceStubFuzzTest") { "${data_service_path}/app/src/feature_stub_impl.cpp", "${data_service_path}/app/src/kvstore_account_observer.cpp", "${data_service_path}/app/src/kvstore_data_service.cpp", + "${data_service_path}/app/src/kvstore_data_service_stub.cpp", "${data_service_path}/app/src/kvstore_device_listener.cpp", "${data_service_path}/app/src/kvstore_meta_manager.cpp", "${data_service_path}/app/src/security/security.cpp", @@ -102,6 +104,7 @@ ohos_fuzztest("DataServiceStubFuzzTest") { "hitrace:libhitracechain", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] diff --git a/datamgr_service/services/distributeddataservice/app/test/unittest/session_manager_test.cpp b/datamgr_service/services/distributeddataservice/app/test/unittest/session_manager_test.cpp index 82c25f56..9244c065 100644 --- a/datamgr_service/services/distributeddataservice/app/test/unittest/session_manager_test.cpp +++ b/datamgr_service/services/distributeddataservice/app/test/unittest/session_manager_test.cpp @@ -40,7 +40,7 @@ void GrantPermissionNative() { const char **perms = new const char *[2]; perms[0] = "ohos.permission.DISTRIBUTED_DATASYNC"; - perms[1] = "ohos.permission.ACCERSS_SERVICE_DM"; + perms[1] = "ohos.permission.ACCESS_SERVICE_DM"; TokenInfoParams infoInstance = { .dcapsNum = 0, .permsNum = 2, diff --git a/datamgr_service/services/distributeddataservice/framework/BUILD.gn b/datamgr_service/services/distributeddataservice/framework/BUILD.gn index b13f8c45..692ed9a8 100644 --- a/datamgr_service/services/distributeddataservice/framework/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/framework/BUILD.gn @@ -56,6 +56,7 @@ ohos_shared_library("distributeddatasvcfwk") { "eventcenter/event.cpp", "eventcenter/event_center.cpp", "feature/feature_system.cpp", + "feature/static_acts.cpp", "metadata/appid_meta_data.cpp", "metadata/capability_meta_data.cpp", "metadata/capability_range.cpp", diff --git a/datamgr_service/services/distributeddataservice/framework/cloud/cloud_event.cpp b/datamgr_service/services/distributeddataservice/framework/cloud/cloud_event.cpp index 3152bf14..8146446d 100644 --- a/datamgr_service/services/distributeddataservice/framework/cloud/cloud_event.cpp +++ b/datamgr_service/services/distributeddataservice/framework/cloud/cloud_event.cpp @@ -25,4 +25,4 @@ const CloudEvent::StoreInfo& CloudEvent::GetStoreInfo() const { return storeInfo_; } -} +} \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/framework/feature/feature_system.cpp b/datamgr_service/services/distributeddataservice/framework/feature/feature_system.cpp index 98f67a10..b94ef987 100644 --- a/datamgr_service/services/distributeddataservice/framework/feature/feature_system.cpp +++ b/datamgr_service/services/distributeddataservice/framework/feature/feature_system.cpp @@ -38,6 +38,17 @@ FeatureSystem::Creator FeatureSystem::GetCreator(const std::string &name) return creator; } +int32_t FeatureSystem::RegisterStaticActs(const std::string &name, std::shared_ptr staticActs) +{ + staticActs_.InsertOrAssign(name, std::move(staticActs)); + return E_OK; +} + +const ConcurrentMap> &FeatureSystem::GetStaticActs() +{ + return staticActs_; +} + std::vector FeatureSystem::GetFeatureName(int32_t flag) { std::vector features; diff --git a/datamgr_service/services/distributeddataservice/framework/feature/static_acts.cpp b/datamgr_service/services/distributeddataservice/framework/feature/static_acts.cpp new file mode 100644 index 00000000..817441af --- /dev/null +++ b/datamgr_service/services/distributeddataservice/framework/feature/static_acts.cpp @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2023 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 "feature/static_acts.h" +namespace OHOS::DistributedData { +StaticActs::~StaticActs() +{ +} + +int32_t StaticActs::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) +{ + return E_OK; +} + +int32_t StaticActs::OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index) +{ + return E_OK; +} + +int32_t StaticActs::OnClearAppStorage(const std::string &bundleName, int32_t user, int32_t index, int32_t tokenId) +{ + return E_OK; +} +} diff --git a/datamgr_service/services/distributeddataservice/framework/include/feature/feature_system.h b/datamgr_service/services/distributeddataservice/framework/include/feature/feature_system.h index a94f0157..cc803596 100644 --- a/datamgr_service/services/distributeddataservice/framework/include/feature/feature_system.h +++ b/datamgr_service/services/distributeddataservice/framework/include/feature/feature_system.h @@ -19,6 +19,7 @@ #include "concurrent_map.h" #include "error/general_error.h" #include "executor_pool.h" +#include "static_acts.h" #include "visibility.h" namespace DistributedDB { struct AutoLaunchParam; @@ -58,6 +59,8 @@ public: static FeatureSystem &GetInstance(); int32_t RegisterCreator(const std::string &name, Creator creator, int32_t flag = BIND_LAZY); Creator GetCreator(const std::string &name); + int32_t RegisterStaticActs(const std::string &name, std::shared_ptr staticActs); + const ConcurrentMap> &GetStaticActs(); std::vector GetFeatureName(int32_t flag); private: @@ -68,6 +71,7 @@ private: FeatureSystem &operator=(FeatureSystem &&) = delete; ConcurrentMap> creators_; + ConcurrentMap> staticActs_; }; } // namespace DistributedData } diff --git a/datamgr_service/services/distributeddataservice/framework/include/feature/static_acts.h b/datamgr_service/services/distributeddataservice/framework/include/feature/static_acts.h new file mode 100644 index 00000000..d989f0a5 --- /dev/null +++ b/datamgr_service/services/distributeddataservice/framework/include/feature/static_acts.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2023 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_FRAMEWORK_STATIC_ACTS_H +#define OHOS_DISTRIBUTED_DATA_FRAMEWORK_STATIC_ACTS_H +#include +#include +#include "error/general_error.h" +#include "visibility.h" +namespace OHOS::DistributedData { +class API_EXPORT StaticActs { +public: + virtual ~StaticActs(); + virtual int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index); + virtual int32_t OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index); + virtual int32_t OnClearAppStorage(const std::string &bundleName, int32_t user, int32_t index, int32_t tokenId); +}; +} // namespace OHOS::DistributedData +#endif // OHOS_DISTRIBUTED_DATA_FRAMEWORK_STATIC_ACTS_H diff --git a/datamgr_service/services/distributeddataservice/framework/include/store/general_store.h b/datamgr_service/services/distributeddataservice/framework/include/store/general_store.h index c1207c4c..c39a328b 100644 --- a/datamgr_service/services/distributeddataservice/framework/include/store/general_store.h +++ b/datamgr_service/services/distributeddataservice/framework/include/store/general_store.h @@ -87,10 +87,6 @@ public: virtual int32_t Unwatch(int32_t origin, Watcher &watcher) = 0; - virtual int32_t RegisterCallback(DetailAsync detailAsync) = 0; - - virtual int32_t UnRegisterCallback() = 0; - virtual int32_t Close() = 0; virtual int32_t AddRef() = 0; diff --git a/datamgr_service/services/distributeddataservice/framework/store/auto_cache.cpp b/datamgr_service/services/distributeddataservice/framework/store/auto_cache.cpp index 0e72c243..acc206e4 100644 --- a/datamgr_service/services/distributeddataservice/framework/store/auto_cache.cpp +++ b/datamgr_service/services/distributeddataservice/framework/store/auto_cache.cpp @@ -69,7 +69,7 @@ AutoCache::Store AutoCache::GetStore(const StoreMetaData &meta, const Watchers & store = it->second; return !stores.empty(); } - auto* dbStore = creators_[meta.storeType](meta); + auto *dbStore = creators_[meta.storeType](meta); if (dbStore == nullptr) { ZLOGE("creator failed. storeName:%{public}s", meta.GetStoreAlias().c_str()); return !stores.empty(); diff --git a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp index 2e50213b..2ab6bcf8 100644 --- a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp @@ -50,6 +50,9 @@ CloudServiceImpl::Factory::Factory() noexcept return product_; }, FeatureSystem::BIND_NOW); + staticActs_ = std::make_shared(); + FeatureSystem::GetInstance().RegisterStaticActs(CloudServiceImpl::SERVICE_NAME, + staticActs_); } CloudServiceImpl::Factory::~Factory() {} @@ -63,8 +66,9 @@ CloudServiceImpl::CloudServiceImpl() int32_t CloudServiceImpl::EnableCloud(const std::string &id, const std::map &switches) { - CloudInfo cloudInfo; - auto status = GetCloudInfo(IPCSkeleton::GetCallingTokenID(), id, cloudInfo); + auto tokenId = IPCSkeleton::GetCallingTokenID(); + auto user = DistributedKv::AccountDelegate::GetInstance()->GetUserByToken(tokenId); + auto [status, cloudInfo] = GetCloudInfo(user); if (status != SUCCESS) { return status; } @@ -78,7 +82,7 @@ int32_t CloudServiceImpl::EnableCloud(const std::string &id, const std::map CloudServiceImpl::GetCloudInfo(int32_t userId) { CloudInfo cloudInfo; cloudInfo.user = userId; if (MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetKey(), cloudInfo, true)) { - return cloudInfo; + return { SUCCESS, cloudInfo }; } auto instance = CloudServer::GetInstance(); if (instance == nullptr) { - return cloudInfo; + return { SERVER_UNAVAILABLE, cloudInfo }; } cloudInfo = instance->GetServerInfo(userId); if (!cloudInfo.IsValid()) { ZLOGE("no cloud info %{public}d", userId); - return cloudInfo; + return { ERROR, cloudInfo }; } MetaDataManager::GetInstance().SaveMeta(cloudInfo.GetKey(), cloudInfo, true); - return cloudInfo; + return { SUCCESS, cloudInfo }; } -int32_t CloudServiceImpl::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) +int32_t CloudServiceImpl::CloudStatic::OnAppUninstall( + const std::string &bundleName, int32_t user, int32_t index) { - Subscription subscription; - MetaDataManager::GetInstance().LoadMeta(Subscription::GetKey(user),subscription, true); - subscription.expiresTime.erase(bundleName); - MetaDataManager::GetInstance().SaveMeta(Subscription::GetKey(user),subscription, true); - - MetaDataManager::GetInstance().DelMeta(Subscription::GetRelationKey(user, bundleName), true); MetaDataManager::GetInstance().DelMeta(CloudInfo::GetSchemaKey(user, bundleName, index), true); return E_OK; @@ -505,6 +504,11 @@ bool CloudServiceImpl::DoSubscribe(int32_t user) ZLOGW("error, there is no cloud info for user(%{public}d)", sub.userId); return false; } + if (!sub.id.empty() && sub.id != cloudInfo.id) { + CleanSubscription(sub); + sub.id.clear(); + sub.expiresTime.clear(); + } ZLOGD("begin cloud:%{public}d user:%{public}d apps:%{public}zu", cloudInfo.enableCloud, sub.userId, cloudInfo.apps.size()); @@ -541,6 +545,15 @@ bool CloudServiceImpl::DoSubscribe(int32_t user) return subDbs.empty() && unsubDbs.empty(); } +void CloudServiceImpl::CleanSubscription(Subscription &sub) +{ + ZLOGD("id:%{public}s, size:%{public}zu", Anonymous::Change(sub.id).c_str(), sub.expiresTime.size()); + MetaDataManager::GetInstance().DelMeta(sub.GetKey(), true); + for (const auto &[bundle, expireTime] : sub.expiresTime) { + MetaDataManager::GetInstance().DelMeta(sub.GetRelationKey(bundle), true); + } +} + void CloudServiceImpl::Execute(Task task) { auto executor = executor_; diff --git a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h index 85096676..deefe7f7 100644 --- a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h +++ b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h @@ -23,6 +23,7 @@ #include "cloud/schema_meta.h" #include "cloud/subscription.h" #include "cloud_service_stub.h" +#include "feature/static_acts.h" #include "sync_manager.h" namespace OHOS::CloudData { class CloudServiceImpl : public CloudServiceStub { @@ -38,17 +39,23 @@ public: int32_t OnInitialize() override; int32_t OnBind(const BindInfo &info) override; int32_t OnUserChange(uint32_t code, const std::string &user, const std::string &account) override; - int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) override; int32_t Online(const std::string &device) override; int32_t Offline(const std::string &device) override; private: + using StaticActs = DistributedData::StaticActs; + class CloudStatic : public StaticActs { + public: + ~CloudStatic() override {}; + int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) override; + }; class Factory { public: Factory() noexcept; ~Factory(); private: std::shared_ptr product_; + std::shared_ptr staticActs_; }; static Factory factory_; @@ -69,7 +76,7 @@ private: bool UpdateCloudInfo(int32_t user); bool UpdateSchema(int32_t user); SchemaMeta GetSchemaMeta(int32_t userId, const std::string &bundleName, int32_t instanceId); - CloudInfo GetCloudInfo(int32_t userId); + std::pair GetCloudInfo(int32_t userId); int32_t GetCloudInfo(uint32_t tokenId, const std::string &id, CloudInfo &cloudInfo); int32_t GetCloudInfoFromMeta(CloudInfo &cloudInfo); int32_t GetCloudInfoFromServer(CloudInfo &cloudInfo); @@ -77,6 +84,7 @@ private: void GetSchema(const Event &event); Task GenTask(int32_t retry, int32_t user, Handles handles = { WORK_SUB }); void Execute(Task task); + void CleanSubscription(Subscription &sub); bool DoSubscribe(int32_t user); int32_t DoClean(CloudInfo &cloudInfo, const std::map &actions); std::shared_ptr executor_; diff --git a/datamgr_service/services/distributeddataservice/service/cloud/sync_manager.cpp b/datamgr_service/services/distributeddataservice/service/cloud/sync_manager.cpp index 83b1a578..461d4186 100644 --- a/datamgr_service/services/distributeddataservice/service/cloud/sync_manager.cpp +++ b/datamgr_service/services/distributeddataservice/service/cloud/sync_manager.cpp @@ -15,6 +15,7 @@ #define LOG_TAG "SyncManager" #include "sync_manager.h" +#include "cloud/cloud_info.h" #include "cloud/cloud_server.h" #include "cloud/schema_meta.h" #include "cloud/sync_event.h" diff --git a/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.cpp index ca9b7216..973ed64e 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.cpp @@ -43,6 +43,8 @@ DataShareServiceImpl::Factory::Factory() FeatureSystem::GetInstance().RegisterCreator("data_share", []() { return std::make_shared(); }); + staticActs_ = std::make_shared(); + FeatureSystem::GetInstance().RegisterStaticActs("data_share", staticActs_); } DataShareServiceImpl::Factory::~Factory() {} @@ -444,8 +446,8 @@ void DataShareServiceImpl::OnConnectDone() AppConnectManager::Notify(callerBundleName); } -int32_t DataShareServiceImpl::OnAppUninstall( - const std::string &bundleName, int32_t user, int32_t index) +int32_t DataShareServiceImpl::DataShareStatic::OnAppUninstall(const std::string &bundleName, int32_t user, + int32_t index) { ZLOGI("%{public}s uninstalled", bundleName.c_str()); PublishedData::Delete(bundleName, user); diff --git a/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.h b/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.h index a71cc0d4..a505f915 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.h +++ b/datamgr_service/services/distributeddataservice/service/data_share/data_share_service_impl.h @@ -25,6 +25,7 @@ #include "datashare_template.h" #include "db_delegate.h" #include "delete_strategy.h" +#include "feature/static_acts.h" #include "get_data_strategy.h" #include "insert_strategy.h" #include "publish_strategy.h" @@ -68,15 +69,22 @@ public: const int64_t subscriberId) override; void OnConnectDone() override; int32_t OnBind(const BindInfo &binderInfo) override; - int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) override; int32_t OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId, const std::string &bundleName) override; void NotifyObserver(const std::string &uri) override; private: + using StaticActs = DistributedData::StaticActs; + class DataShareStatic : public StaticActs { + public: + ~DataShareStatic() override {}; + int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) override; + }; class Factory { public: Factory(); ~Factory(); + private: + std::shared_ptr staticActs_; }; class TimerReceiver : public EventFwk::CommonEventSubscriber { public: diff --git a/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/executor/document/check_common.cpp b/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/executor/document/check_common.cpp index 8b179159..e4af38a1 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/executor/document/check_common.cpp +++ b/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/executor/document/check_common.cpp @@ -109,10 +109,10 @@ int CheckCommon::CheckFilter(JsonObject &filterObj, std::vector> &filterPath, bool &isIdExist); - static int CheckIdFormat(JsonObject &data, bool &isIdExisit); + static int CheckFilter(JsonObject &filterObj, std::vector> &filterPath, bool &isIdExist); + static int CheckIdFormat(JsonObject &idObj, bool &isIdExisit); static int CheckDocument(JsonObject &documentObj, bool &isIdExist); static int CheckUpdata(JsonObject &updataObj); static int CheckProjection(JsonObject &projectionObj, std::vector> &path); diff --git a/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/interface/src/result_set.cpp b/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/interface/src/result_set.cpp index 4335a97f..d537dd0e 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/interface/src/result_set.cpp +++ b/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/interface/src/result_set.cpp @@ -220,7 +220,7 @@ JsonObject CreatIdObj(const std::string &idStr, int errCode) return idObj; } -int InsertId(JsonObject &cjsonObj, std::string &jsonKey) +int InsertId(JsonObject &cjsonObj, const std::string &jsonKey) { if (jsonKey.empty()) { GLOGE("Genalral Id faild"); diff --git a/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/oh_adapter/src/sqlite_store_executor_impl.cpp b/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/oh_adapter/src/sqlite_store_executor_impl.cpp index 39f34788..6750b9b5 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/oh_adapter/src/sqlite_store_executor_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/oh_adapter/src/sqlite_store_executor_impl.cpp @@ -226,7 +226,7 @@ std::string GeneralInsertSql(const std::string &collName, Key &key, int isIdExis } } -void AssignValueToData(std::string &keyStr, std::string &valueStr, std::pair &values, +void AssignValueToData(std::string &keyStr, const std::string &valueStr, std::pair &values, int &innerErrorCode, bool &isMatchOneData) { keyStr.pop_back(); // get id from really key. diff --git a/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/test/unittest/api/documentdb_data_test.cpp b/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/test/unittest/api/documentdb_data_test.cpp index 129ea35b..c0fc9afd 100644 --- a/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/test/unittest/api/documentdb_data_test.cpp +++ b/datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/test/unittest/api/documentdb_data_test.cpp @@ -118,10 +118,6 @@ HWTEST_F(DocumentDBDataTest, UpsertDataTest003, TestSize.Level0) } } -HWTEST_F(DocumentDBDataTest, UpsertDataTest004, TestSize.Level0) {} - -HWTEST_F(DocumentDBDataTest, UpsertDataTest005, TestSize.Level0) {} - /** * @tc.name: UpsertDataTest006 * @tc.desc: Test upsert data with invalid flags diff --git a/datamgr_service/services/distributeddataservice/service/object/object_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/object/object_service_impl.cpp index c38e77dd..132faa2b 100644 --- a/datamgr_service/services/distributeddataservice/service/object/object_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/object/object_service_impl.cpp @@ -44,6 +44,8 @@ ObjectServiceImpl::Factory::Factory() return std::make_shared(); }, FeatureSystem::BIND_NOW); + staticActs_ = std::make_shared(); + FeatureSystem::GetInstance().RegisterStaticActs("data_object", staticActs_); } ObjectServiceImpl::Factory::~Factory() @@ -219,7 +221,7 @@ void ObjectServiceImpl::Clear() return; } -int32_t ObjectServiceImpl::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) +int32_t ObjectServiceImpl::ObjectStatic::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) { ZLOGI("begin. %{public}s", bundleName.c_str()); int32_t result = ObjectStoreManager::GetInstance()->DeleteByAppId(bundleName); diff --git a/datamgr_service/services/distributeddataservice/service/object/object_service_impl.h b/datamgr_service/services/distributeddataservice/service/object/object_service_impl.h index f9e038a1..caa1c340 100644 --- a/datamgr_service/services/distributeddataservice/service/object/object_service_impl.h +++ b/datamgr_service/services/distributeddataservice/service/object/object_service_impl.h @@ -16,6 +16,7 @@ #ifndef DISTRIBUTEDDATASERVICE_OBJECT_SERVICE_H #define DISTRIBUTEDDATASERVICE_OBJECT_SERVICE_H +#include "feature/static_acts.h" #include "object_manager.h" #include "object_service_stub.h" #include "visibility.h" @@ -43,14 +44,21 @@ public: int32_t OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId, const std::string &appId) override; int32_t OnInitialize() override; int32_t OnUserChange(uint32_t code, const std::string &user, const std::string &account) override; - int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) override; int32_t OnBind(const BindInfo &bindInfo) override; private: + using StaticActs = DistributedData::StaticActs; + class ObjectStatic : public StaticActs { + public: + ~ObjectStatic() override {}; + int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) override; + }; class Factory { public: Factory(); ~Factory(); + private: + std::shared_ptr staticActs_; }; static Factory factory_; std::shared_ptr executors_; diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud.cpp index e41b7664..e09e1a08 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud.cpp @@ -32,7 +32,7 @@ RdbCloud::RdbCloud(std::shared_ptr cloudDB) DBStatus RdbCloud::BatchInsert( const std::string &tableName, std::vector &&record, std::vector &extend) { - DistributedData::VBuckets extends; + DistributedData::VBuckets extends = ValueProxy::Convert(std::move(extend)); auto error = cloudDB_->BatchInsert(tableName, ValueProxy::Convert(std::move(record)), extends); if (error == GeneralError::E_OK) { extend = ValueProxy::Convert(std::move(extends)); diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.cpp index 163734b4..15b2868c 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.cpp @@ -26,7 +26,9 @@ using DataAssets = NativeRdb::ValueObject::Assets; std::vector RdbCloudDataTranslate::AssetToBlob(const Asset &asset) { std::vector rawData; - DataAsset dataAsset = ValueProxy::Asset(asset); + Asset dbAsset = asset; + dbAsset.flag = static_cast(DistributedDB::AssetOpType::NO_CHANGE); + DataAsset dataAsset = ValueProxy::Asset(std::move(dbAsset)); InnerAsset innerAsset(dataAsset); auto data = Serializable::Marshall(innerAsset); auto size = DistributedData::HostToNet((uint16_t)data.length()); diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.cpp index a784ad43..5385952e 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.cpp @@ -278,7 +278,6 @@ int32_t RdbGeneralStore::Unwatch(int32_t origin, Watcher &watcher) RdbGeneralStore::DBBriefCB RdbGeneralStore::GetDBBriefCB(DetailAsync async) { - async = async ? async : detailAsync_; if (!async) { return [](auto &) {}; } @@ -300,7 +299,6 @@ RdbGeneralStore::DBBriefCB RdbGeneralStore::GetDBBriefCB(DetailAsync async) RdbGeneralStore::DBProcessCB RdbGeneralStore::GetDBProcessCB(DetailAsync async) { - async = async ? async : detailAsync_; if (!async) { return [](auto &) {}; } @@ -411,18 +409,6 @@ bool RdbGeneralStore::IsValid() return delegate_ != nullptr; } -int32_t RdbGeneralStore::RegisterCallback(DetailAsync detailAsync) -{ - detailAsync_ = std::move(detailAsync); - return GenErr::E_OK; -} - -int32_t RdbGeneralStore::UnRegisterCallback() -{ - detailAsync_ = nullptr; - return GenErr::E_OK; -} - void RdbGeneralStore::ObserverProxy::OnChange(const DBChangedIF &data) { if (!HasWatcher()) { diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.h b/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.h index 735355d4..915f7b55 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.h +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_general_store.h @@ -57,8 +57,6 @@ public: int32_t Clean(const std::vector &devices, int32_t mode, const std::string &tableName) override; int32_t Watch(int32_t origin, Watcher &watcher) override; int32_t Unwatch(int32_t origin, Watcher &watcher) override; - int32_t RegisterCallback(DetailAsync detailAsync) override; - int32_t UnRegisterCallback() override; int32_t Close() override; int32_t AddRef() override; int32_t Release() override; @@ -95,7 +93,6 @@ private: const DistributedDB::RemoteCondition &remoteCondition); ObserverProxy observer_; - DetailAsync detailAsync_; RdbManager manager_; RdbDelegate *delegate_ = nullptr; std::shared_ptr rdbCloud_ {}; diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_query.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_query.cpp index f6fca44a..733427c9 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_query.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_query.cpp @@ -19,6 +19,9 @@ #include "value_proxy.h" namespace OHOS::DistributedRdb { using namespace DistributedData; + +RdbQuery::RdbQuery(bool isRemote) : isRemote_(isRemote) {} + bool RdbQuery::IsEqual(uint64_t tid) { return tid == TYPE_ID; @@ -29,10 +32,13 @@ std::vector RdbQuery::GetTables() return tables_; } -void RdbQuery::MakeRemoteQuery(const std::string& devices, const std::string& sql, Values&& args) +void RdbQuery::SetDevices(const std::vector &devices) +{ + devices_ = devices; +} + +void RdbQuery::SetSql(const std::string &sql, DistributedData::Values &&args) { - isRemote_ = true; - devices_ = { devices }; sql_ = sql; args_ = std::move(args); } diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_query.h b/datamgr_service/services/distributeddataservice/service/rdb/rdb_query.h index 9c236121..41088bd4 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_query.h +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_query.h @@ -25,6 +25,7 @@ public: using Predicates = NativeRdb::RdbPredicates; static constexpr uint64_t TYPE_ID = 0x20000001; RdbQuery() = default; + explicit RdbQuery(bool isRemote); ~RdbQuery() override = default; @@ -34,9 +35,10 @@ public: DistributedDB::Query GetQuery() const; DistributedDB::RemoteCondition GetRemoteCondition() const; bool IsRemoteQuery(); + void SetDevices(const std::vector &devices); + void SetSql(const std::string &sql, DistributedData::Values &&args); void FromTable(const std::vector &tables); void MakeQuery(const PredicatesMemo &predicates); - void MakeRemoteQuery(const std::string &devices, const std::string &sql, DistributedData::Values &&args); private: void EqualTo(const RdbPredicateOperation& operation); diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index deff5e82..2bef5ae7 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -69,6 +69,9 @@ RdbServiceImpl::Factory::Factory() } return store; }); + staticActs_ = std::make_shared(); + FeatureSystem::GetInstance().RegisterStaticActs(RdbServiceImpl::SERVICE_NAME, + staticActs_); } RdbServiceImpl::Factory::~Factory() @@ -150,16 +153,22 @@ int32_t RdbServiceImpl::ResolveAutoLaunch(const std::string &identifier, Distrib int32_t RdbServiceImpl::OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId, const std::string &bundleName) { - ZLOGI("client dead, tokenId:%{public}d, pid:%{public}d ", tokenId, pid); - syncAgents_.ComputeIfPresent(tokenId, [pid](auto, SyncAgents& agents) { - auto it = agents.find(pid); - if (it != agents.end()) { - it->second.SetNotifier(nullptr); - agents.erase(it); + OnClientDied(pid); + return E_OK; +} + +void RdbServiceImpl::OnClientDied(pid_t pid) +{ + ZLOGI("client dead pid=%{public}d", pid); + syncAgents_.EraseIf([pid](auto &key, SyncAgent &agent) { + if (agent.pid_ != pid) { + return false; + } + if (agent.watcher_ != nullptr) { + agent.watcher_->SetNotifier(nullptr); } - return agents.empty(); + return true; }); - return E_OK; } bool RdbServiceImpl::CheckAccess(const std::string& bundleName, const std::string& storeName) @@ -201,12 +210,11 @@ int32_t RdbServiceImpl::InitNotifier(const RdbSyncerParam ¶m, const sptr(notifier); pid_t pid = IPCSkeleton::GetCallingPid(); uint32_t tokenId = IPCSkeleton::GetCallingTokenID(); - syncAgents_.Compute(tokenId, [¶m, notifierProxy, pid](auto, SyncAgents &agents) { - auto [it, _] = agents.insert_or_assign(pid, SyncAgent()); - if (it != agents.end()) { - it->second.ReInit(param.bundleName_); - it->second.SetNotifier(notifierProxy); + syncAgents_.Compute(tokenId, [¶m, notifierProxy, pid](auto, SyncAgent &agent) { + if (pid != agent.pid_) { + agent.ReInit(pid, param.bundleName_); } + agent.SetNotifier(notifierProxy); return true; }); ZLOGI("success tokenId:%{public}x, pid=%{public}d", tokenId, pid); @@ -243,19 +251,12 @@ int32_t RdbServiceImpl::SetDistributedTables(const RdbSyncerParam ¶m, const return store->SetDistributedTables(tables, type); } -void RdbServiceImpl::OnAsyncComplete(uint32_t tokenId, uint32_t pid, uint32_t seqNum, Details &&result) +void RdbServiceImpl::OnAsyncComplete(uint32_t tokenId, uint32_t seqNum, Details &&result) { ZLOGI("tokenId=%{public}x seqnum=%{public}u", tokenId, seqNum); - sptr notifier = nullptr; - syncAgents_.ComputeIfPresent(tokenId, [¬ifier, pid](auto, SyncAgents& syncAgents) { - auto it = syncAgents.find(pid); - if (it != syncAgents.end()) { - notifier = it->second.notifier_; - } - return true; - }); - if (notifier != nullptr) { - notifier->OnComplete(seqNum, std::move(result)); + auto [success, agent] = syncAgents_.Find(tokenId); + if (success && agent.notifier_ != nullptr) { + agent.notifier_->OnComplete(seqNum, std::move(result)); } } @@ -276,16 +277,11 @@ std::string RdbServiceImpl::TransferStringToHex(const std::string &origStr) AutoCache::Watchers RdbServiceImpl::GetWatchers(uint32_t tokenId, const std::string &storeName) { - AutoCache::Watchers watchers; - syncAgents_.ComputeIfPresent(tokenId, [&storeName, &watchers](auto, SyncAgents &syncAgents) { - std::for_each(syncAgents.begin(), syncAgents.end(), [&storeName, &watchers](const auto& item) { - if (item.second.watcher_ != nullptr && item.second.stores.count(storeName) != 0) { - watchers.insert(item.second.watcher_); - } - }); - return true; - }); - return watchers; + auto [success, agent] = syncAgents_.Find(tokenId); + if (agent.watcher_ == nullptr) { + return {}; + } + return { agent.watcher_ }; } int32_t RdbServiceImpl::RemoteQuery(const RdbSyncerParam& param, const std::string& device, const std::string& sql, @@ -300,8 +296,10 @@ int32_t RdbServiceImpl::RemoteQuery(const RdbSyncerParam& param, const std::stri ZLOGE("store is null"); return RDB_ERROR; } - RdbQuery rdbQuery; - rdbQuery.MakeRemoteQuery(device, sql, ValueProxy::Convert(selectionArgs)); + auto values = ValueProxy::Convert(selectionArgs); + RdbQuery rdbQuery(true); + rdbQuery.SetDevices({ device }); + rdbQuery.SetSql(sql, std::move(values)); auto cursor = store->Query("", rdbQuery); if (cursor == nullptr) { ZLOGE("Query failed, cursor is null"); @@ -356,11 +354,10 @@ int RdbServiceImpl::DoSync(const RdbSyncerParam ¶m, const RdbService::Option } ZLOGD("seqNum=%{public}u", option.seqNum); auto tokenId = IPCSkeleton::GetCallingTokenID(); - auto pid = IPCSkeleton::GetCallingPid(); return store->Sync( DmAdapter::ToUUID(DmAdapter::GetInstance().GetRemoteDevices()), option.mode, rdbQuery, - [this, tokenId, pid, seqNum = option.seqNum](const GenDetails &result) mutable { - OnAsyncComplete(tokenId, pid, seqNum, HandleGenDetails(result)); + [this, tokenId, seqNum = option.seqNum](const GenDetails &result) mutable { + OnAsyncComplete(tokenId, seqNum, HandleGenDetails(result)); }, false); } @@ -378,10 +375,9 @@ void RdbServiceImpl::DoCloudSync(const RdbSyncerParam ¶m, const RdbService:: query = std::make_shared(); query->FromTable(predicates.tables_); } - auto pid = IPCSkeleton::GetCallingPid(); - GenAsync asyncCallback = [this, tokenId = storeInfo.tokenId, pid, seqNum = option.seqNum]( + GenAsync asyncCallback = [this, tokenId = storeInfo.tokenId, seqNum = option.seqNum]( const GenDetails &result) mutable { - OnAsyncComplete(tokenId, pid, seqNum, HandleGenDetails(result)); + OnAsyncComplete(tokenId, seqNum, HandleGenDetails(result)); }; GenAsync syncCallback = [async, ¶m](const GenDetails &details) { ZLOGD("Cloud Sync complete, bundleName:%{public}s, storeName:%{public}s", param.bundleName_.c_str(), @@ -406,19 +402,21 @@ int32_t RdbServiceImpl::Subscribe(const RdbSyncerParam ¶m, const SubscribeOp } pid_t pid = IPCSkeleton::GetCallingPid(); auto tokenId = IPCSkeleton::GetCallingTokenID(); - auto storeName = RemoveSuffix(param.storeName_); - syncAgents_.Compute(tokenId, [pid, ¶m, &storeName](auto, SyncAgents& agents) { - auto [it, success] = agents.try_emplace(pid, param.bundleName_); - if (it == agents.end()) { - return !agents.empty(); + bool isCreate = false; + syncAgents_.Compute(tokenId, [pid, ¶m, &isCreate](auto &key, SyncAgent &agent) { + if (pid != agent.pid_) { + agent.ReInit(pid, param.bundleName_); } - if (it->second.watcher_ == nullptr) { - it->second.SetWatcher(std::make_shared()); + if (agent.watcher_ == nullptr) { + isCreate = true; + agent.SetWatcher(std::make_shared()); } - it->second.stores.insert(storeName); + agent.count_++; return true; }); - AutoCache::GetInstance().SetObserver(tokenId, storeName, GetWatchers(tokenId, storeName)); + if (isCreate) { + AutoCache::GetInstance().SetObserver(tokenId, param.storeName_, GetWatchers(tokenId, param.storeName_)); + } return RDB_OK; } @@ -429,18 +427,21 @@ int32_t RdbServiceImpl::UnSubscribe(const RdbSyncerParam ¶m, const Subscribe ZLOGE("mode:%{public}d error", option.mode); return RDB_ERROR; } + bool destroyed = false; auto tokenId = IPCSkeleton::GetCallingTokenID(); - auto pid = IPCSkeleton::GetCallingPid(); - auto storeName = RemoveSuffix(param.storeName_); - syncAgents_.ComputeIfPresent(tokenId, [pid, &storeName](auto, SyncAgents& agents) { - auto it = agents.find(pid); - if (it != agents.end()) { - it->second.stores.insert(storeName); - it->second.SetWatcher(nullptr); + syncAgents_.ComputeIfPresent(tokenId, [&destroyed](auto &key, SyncAgent &agent) { + if (agent.count_ > 0) { + agent.count_--; + } + if (agent.count_ == 0) { + destroyed = true; + agent.SetWatcher(nullptr); } - return !agents.empty(); + return true; }); - AutoCache::GetInstance().SetObserver(tokenId, storeName, GetWatchers(tokenId, storeName)); + if (destroyed) { + AutoCache::GetInstance().SetObserver(tokenId, param.storeName_, GetWatchers(tokenId, param.storeName_)); + } return RDB_OK; } @@ -648,19 +649,10 @@ int32_t RdbServiceImpl::OnBind(const BindInfo &bindInfo) return 0; } -int32_t RdbServiceImpl::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) +void RdbServiceImpl::SyncAgent::ReInit(pid_t pid, const std::string &bundleName) { - return CloseStore(bundleName, user, index); -} - -int32_t RdbServiceImpl::OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index) -{ - return CloseStore(bundleName, user, index); -} - -void RdbServiceImpl::SyncAgent::ReInit(const std::string& bundleName) -{ - stores.clear(); + pid_ = pid; + count_ = 0; bundleName_ = bundleName; notifier_ = nullptr; if (watcher_ != nullptr) { @@ -686,8 +678,13 @@ void RdbServiceImpl::SyncAgent::SetWatcher(std::shared_ptr watcher) } } -int32_t RdbServiceImpl::CloseStore(const std::string &bundleName, int32_t user, int32_t index) const +int32_t RdbServiceImpl::RdbStatic::CloseStore(const std::string &bundleName, int32_t user, int32_t index, + int32_t tokenId) const { + if (tokenId != RdbServiceImpl::RdbStatic::INVALID_TOKENID) { + AutoCache::GetInstance().CloseStore(tokenId); + return E_OK; + } std::string prefix = StoreMetaData::GetPrefix( { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid, std::to_string(user), "default", bundleName }); std::vector storeMetaData; @@ -709,10 +706,19 @@ int32_t RdbServiceImpl::CloseStore(const std::string &bundleName, int32_t user, return E_OK; } -RdbServiceImpl::SyncAgent::SyncAgent(std::string bundleName) : bundleName_(bundleName) +int32_t RdbServiceImpl::RdbStatic::OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) { - notifier_ = nullptr; - watcher_ = nullptr; - notifier_ = nullptr; + return CloseStore(bundleName, user, index); +} + +int32_t RdbServiceImpl::RdbStatic::OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index) +{ + return CloseStore(bundleName, user, index); +} + +int32_t RdbServiceImpl::RdbStatic::OnClearAppStorage(const std::string &bundleName, int32_t user, int32_t index, + int32_t tokenId) +{ + return CloseStore(bundleName, user, index, tokenId); } } // namespace OHOS::DistributedRdb diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h index 117c6791..c8999344 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h @@ -22,6 +22,7 @@ #include #include #include "concurrent_map.h" +#include "feature/static_acts.h" #include "metadata/secret_key_meta_data.h" #include "metadata/store_meta_data.h" #include "rdb_notifier_proxy.h" @@ -31,6 +32,7 @@ #include "store_observer.h" #include "visibility.h" #include "store/general_value.h" + namespace OHOS::DistributedRdb { class API_EXPORT RdbServiceImpl : public RdbServiceStub { public: @@ -38,6 +40,8 @@ public: using SecretKeyMetaData = DistributedData::SecretKeyMetaData; RdbServiceImpl(); + void OnClientDied(pid_t pid); + /* IPC interface */ std::string ObtainDistributedTableName(const std::string& device, const std::string& table) override; @@ -59,36 +63,41 @@ public: int32_t ResolveAutoLaunch(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) override; - int32_t OnInitialize() override; - int32_t OnAppExit(pid_t uid, pid_t pid, uint32_t tokenId, const std::string &bundleName) override; - int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) override; - - int32_t OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index) override; - int32_t GetSchema(const RdbSyncerParam ¶m) override; int32_t Delete(const RdbSyncerParam ¶m) override; int32_t OnBind(const BindInfo &bindInfo) override; - virtual std::pair GetInstIndexAndUser(uint32_t tokenId, const std::string &bundleName); + int32_t OnInitialize() override; private: using Watchers = DistributedData::AutoCache::Watchers; + using StaticActs = DistributedData::StaticActs; struct SyncAgent { - SyncAgent() = default; - SyncAgent(std::string bundleName); - std::set stores; + pid_t pid_ = 0; + int32_t count_ = 0; std::string bundleName_; sptr notifier_ = nullptr; std::shared_ptr watcher_ = nullptr; - void ReInit(const std::string &bundleName); + void ReInit(pid_t pid, const std::string &bundleName); void SetNotifier(sptr notifier); void SetWatcher(std::shared_ptr watcher); }; - using SyncAgents = std::map; + + class RdbStatic : public StaticActs { + public: + ~RdbStatic() override {}; + int32_t OnAppUninstall(const std::string &bundleName, int32_t user, int32_t index) override; + int32_t OnAppUpdate(const std::string &bundleName, int32_t user, int32_t index) override; + int32_t OnClearAppStorage(const std::string &bundleName, int32_t user, int32_t index, int32_t tokenId) override; + private: + static constexpr inline int32_t INVALID_TOKENID = 0; + int32_t CloseStore(const std::string &bundleName, int32_t user, int32_t index, + int32_t tokenId = INVALID_TOKENID) const; + }; class Factory { public: @@ -96,6 +105,7 @@ private: ~Factory(); private: std::shared_ptr product_; + std::shared_ptr staticActs_; }; static constexpr inline uint32_t WAIT_TIME = 30 * 1000; @@ -112,7 +122,7 @@ private: std::shared_ptr GetStore(const RdbSyncerParam& param); - void OnAsyncComplete(uint32_t tokenId, uint32_t pid, uint32_t seqNum, Details&& result); + void OnAsyncComplete(uint32_t tokenId, uint32_t seqNum, Details&& result); int32_t CreateMetaData(const RdbSyncerParam ¶m, StoreMetaData &old); @@ -128,12 +138,12 @@ private: static std::string RemoveSuffix(const std::string& name); - static bool GetPassword(const StoreMetaData &metaData, DistributedDB::CipherPassword &password); + static std::pair GetInstIndexAndUser(uint32_t tokenId, const std::string &bundleName); - int32_t CloseStore(const std::string &bundleName, int32_t user, int32_t index) const; + static bool GetPassword(const StoreMetaData &metaData, DistributedDB::CipherPassword &password); static Factory factory_; - ConcurrentMap syncAgents_; + ConcurrentMap syncAgents_; std::shared_ptr executors_; }; } // namespace OHOS::DistributedRdb diff --git a/datamgr_service/services/distributeddataservice/service/test/BUILD.gn b/datamgr_service/services/distributeddataservice/service/test/BUILD.gn index e0d8c344..9f814f58 100644 --- a/datamgr_service/services/distributeddataservice/service/test/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/service/test/BUILD.gn @@ -240,88 +240,6 @@ ohos_unittest("RdbResultSetImplTest") { ] } -ohos_unittest("RdbServiceImplTest") { - module_out_path = module_output_path - sources = [ - "mock/db_change_data_mock.cpp", - "mock/db_store_mock.cpp", - "mock/general_store_mock.cpp", - "rdb_service_impl_test.cpp", - "${data_service_path}/service/backup/src/backup_manager.cpp", - "${data_service_path}/service/bootstrap/src/bootstrap.cpp", - "${data_service_path}/service/config/src/config_factory.cpp", - "${data_service_path}/service/config/src/model/backup_config.cpp", - "${data_service_path}/service/config/src/model/checker_config.cpp", - "${data_service_path}/service/config/src/model/component_config.cpp", - "${data_service_path}/service/config/src/model/directory_config.cpp", - "${data_service_path}/service/config/src/model/global_config.cpp", - "${data_service_path}/service/config/src/model/network_config.cpp", - "${data_service_path}/service/config/src/model/protocol_config.cpp", - "${data_service_path}/service/crypto/src/crypto_manager.cpp", - "${data_service_path}/service/matrix/src/device_matrix.cpp", - "${data_service_path}/service/matrix/src/matrix_event.cpp", - "${data_service_path}/service/permission/src/permit_delegate.cpp", - "${data_service_path}/service/rdb/rdb_asset_loader.cpp", - "${data_service_path}/service/rdb/rdb_cloud.cpp", - "${data_service_path}/service/rdb/rdb_cursor.cpp", - "${data_service_path}/service/rdb/rdb_general_store.cpp", - "${data_service_path}/service/rdb/rdb_notifier_proxy.cpp", - "${data_service_path}/service/rdb/rdb_query.cpp", - "${data_service_path}/service/rdb/rdb_result_set_impl.cpp", - "${data_service_path}/service/rdb/rdb_result_set_stub.cpp", - "${data_service_path}/service/rdb/rdb_service_impl.cpp", - "${data_service_path}/service/rdb/rdb_service_stub.cpp", - "${data_service_path}/service/rdb/rdb_watcher.cpp", - "${data_service_path}/service/rdb/value_proxy.cpp", - "${relational_store_path}/frameworks/native/rdb/src/rdb_notifier_stub.cpp", - "${relational_store_path}/frameworks/native/rdb/src/rdb_types_util.cpp", - ] - - include_dirs = [ - "${data_service_path}/service/backup/include", - "${data_service_path}/service/bootstrap/include", - "${data_service_path}/service/cloud", - "${data_service_path}/service/config/include", - "${data_service_path}/service/crypto/include", - "${data_service_path}/service/kvdb", - "${data_service_path}/service/matrix/include", - "${data_service_path}/service/object", - "${data_service_path}/service/permission/include", - "${data_service_path}/service/rdb", - "${kv_store_distributeddb_path}", - "${relational_store_path}/frameworks/common/include", - "${relational_store_path}/frameworks/native/rdb/include", - "${relational_store_path}/interfaces/inner_api/cloud_data/include", - "${relational_store_path}/interfaces/inner_api/rdb/include", - ] - - configs = [ ":module_private_config" ] - - external_deps = [ - "ability_base:base", - "ability_base:want", - "access_token:libnativetoken", - "access_token:libaccesstoken_sdk", - "access_token:libtokenid_sdk", - "access_token:libtoken_setproc", - "c_utils:utils", - "device_auth:deviceauth_sdk", - "device_manager:devicemanagersdk", - "hilog:libhilog", - "huks:libhukssdk", - "ipc:ipc_core", - "kv_store:distributeddata_inner", - "kv_store:distributeddb", - "relational_store:native_rdb", - ] - - deps = [ - "../../adapter:distributeddata_adapter", - "../../framework:distributeddatasvcfwk", - "//third_party/googletest:gtest_main", - ] -} - ############################################################################### group("unittest") { testonly = true @@ -335,7 +253,6 @@ group("unittest") { ":DeviceMatrixTest", ":DirectoryManagerTest", ":RdbResultSetImplTest", - ":RdbServiceImplTest", ":ValueProxyTest", ] } diff --git a/datamgr_service/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn b/datamgr_service/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn index 45818b82..7683a031 100644 --- a/datamgr_service/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/service/test/fuzztest/cloudservicestub_fuzzer/BUILD.gn @@ -35,6 +35,7 @@ ohos_fuzztest("CloudServiceStubFuzzTest") { "${data_service_path}/service/rdb", "${kv_store_common_path}", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", + "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include", "${kv_store_distributeddb_path}", "${kv_store_distributeddb_path}/include/", @@ -99,6 +100,7 @@ ohos_fuzztest("CloudServiceStubFuzzTest") { "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", "relational_store:native_rdb", ] } diff --git a/datamgr_service/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn b/datamgr_service/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn index 01f380c6..58e97706 100644 --- a/datamgr_service/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/service/test/fuzztest/kvdbservicestub_fuzzer/BUILD.gn @@ -33,6 +33,7 @@ ohos_fuzztest("KvdbServiceStubFuzzTest") { "${data_service_path}/service/permission/include", "${kv_store_common_path}", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", + "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include", "${kv_store_distributeddb_path}", "${kv_store_distributeddb_path}/include/", @@ -101,6 +102,7 @@ ohos_fuzztest("KvdbServiceStubFuzzTest") { "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", ] } diff --git a/datamgr_service/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn b/datamgr_service/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn index cd27ac04..f71790cf 100644 --- a/datamgr_service/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/service/test/fuzztest/objectservicestub_fuzzer/BUILD.gn @@ -30,6 +30,7 @@ ohos_fuzztest("ObjectServiceStubFuzzTest") { "${data_service_path}/service/object", "${kv_store_common_path}", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", + "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include", "${kv_store_distributeddb_path}", "${kv_store_distributeddb_path}/include/", @@ -90,6 +91,7 @@ ohos_fuzztest("ObjectServiceStubFuzzTest") { "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", ] } diff --git a/datamgr_service/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn b/datamgr_service/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn index c8736f9f..68a76083 100644 --- a/datamgr_service/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/service/test/fuzztest/rdbresultsetstub_fuzzer/BUILD.gn @@ -26,6 +26,7 @@ ohos_fuzztest("RdbResultSetStubFuzzTest") { "${data_service_path}/service/rdb", "${kv_store_common_path}", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", + "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include", "${kv_store_distributeddb_path}", "${kv_store_distributeddb_path}/include/", @@ -74,6 +75,7 @@ ohos_fuzztest("RdbResultSetStubFuzzTest") { "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", "relational_store:native_rdb", ] } diff --git a/datamgr_service/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn b/datamgr_service/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn index b0c3923a..c3cc42bf 100644 --- a/datamgr_service/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/service/test/fuzztest/rdbservicestub_fuzzer/BUILD.gn @@ -36,6 +36,7 @@ ohos_fuzztest("RdbServiceStubFuzzTest") { "${data_service_path}/service/rdb", "${kv_store_common_path}", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", + "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "${kv_store_path}/frameworks/innerkitsimpl/kvdb/include", "${kv_store_distributeddb_path}", "${kv_store_distributeddb_path}/include/", @@ -96,6 +97,7 @@ ohos_fuzztest("RdbServiceStubFuzzTest") { "huks:libhukssdk", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", "relational_store:native_rdb", ] } diff --git a/datamgr_service/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn b/datamgr_service/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn index 4656e9aa..4a878c22 100644 --- a/datamgr_service/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn @@ -58,6 +58,7 @@ ohos_fuzztest("UdmfServiceFuzzTest") { "hilog:libhilog", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", "udmf:udmf_client", ] } diff --git a/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.cpp b/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.cpp index df8c3984..cd1e2df6 100644 --- a/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.cpp @@ -310,12 +310,5 @@ DBStatus DBStoreMock::UpdateKey(const UpdateKeyCallback &callback) { return NOT_SUPPORT; } - -void DBStoreMock::Reset() -{ - entries_.Clear(); - localEntries_.Clear(); - observers_.Clear(); -} } // namespace DistributedData } // namespace OHOS \ No newline at end of file diff --git a/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.h b/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.h index 74e8342e..e50def98 100644 --- a/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.h +++ b/datamgr_service/services/distributeddataservice/service/test/mock/db_store_mock.h @@ -89,7 +89,6 @@ public: DBStatus GetKeys(const Key &keyPrefix, std::vector &keys) const override; size_t GetSyncDataSize(const std::string &device) const override; DBStatus UpdateKey(const UpdateKeyCallback &callback) override; - void Reset(); private: static const uint32_t DEFAULT_SIZE = 0; diff --git a/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_manager.cpp b/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_manager.cpp index c285644f..fb8710e6 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_manager.cpp +++ b/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_manager.cpp @@ -24,8 +24,7 @@ namespace OHOS { namespace UDMF { std::shared_ptr LifeCycleManager::executorPool_ = std::make_shared(2, 1); - -std::unordered_map> LifeCycleManager::intentionPolicyMap_ = { +std::unordered_map> LifeCycleManager::intentionPolicy_ = { { UD_INTENTION_MAP.at(UD_INTENTION_DRAG), std::make_shared() }, }; @@ -37,8 +36,8 @@ LifeCycleManager &LifeCycleManager::GetInstance() Status LifeCycleManager::DeleteOnGet(const UnifiedKey &key) { - auto findPolicy = intentionPolicyMap_.find(key.intention); - if (findPolicy == intentionPolicyMap_.end()) { + auto findPolicy = intentionPolicy_.find(key.intention); + if (findPolicy == intentionPolicy_.end()) { ZLOGE("Invalid intention, intention: %{public}s.", key.intention.c_str()); return E_INVALID_PARAMETERS; } @@ -49,10 +48,19 @@ Status LifeCycleManager::DeleteOnGet(const UnifiedKey &key) Status LifeCycleManager::DeleteOnStart() { Status status = E_OK; - std::shared_ptr LifeCyclePolicy; - for (const auto &intentionPolicyPair : intentionPolicyMap_) { - LifeCyclePolicy = GetPolicy(intentionPolicyPair.first); - status = status == E_OK ? LifeCyclePolicy->DeleteOnStart(intentionPolicyPair.first) : status; + std::string errorInfo; + for (auto &[intention, lifeCyclePolicy] : intentionPolicy_) { + if (lifeCyclePolicy == nullptr) { + continue; + } + Status delStatus = lifeCyclePolicy->DeleteOnStart(intention); + if (delStatus != E_OK) { + status = delStatus; + errorInfo += intention + " "; + } + } + if (status != E_OK) { + ZLOGW("fail, status = %{public}d, intention = [%{public}s].", status, errorInfo.c_str()); } return status; } @@ -69,24 +77,25 @@ Status LifeCycleManager::DeleteOnSchedule() return E_OK; } -std::shared_ptr LifeCycleManager::GetPolicy(const std::string &intention) -{ - auto findPolicy = intentionPolicyMap_.find(intention); - if (findPolicy == intentionPolicyMap_.end()) { - return nullptr; - } - return findPolicy->second; -} - Status LifeCycleManager::DeleteOnTimeout() { Status status = E_OK; - std::shared_ptr LifeCyclePolicy; - for (const auto &intentionPolicyPair : intentionPolicyMap_) { - LifeCyclePolicy = LifeCycleManager::GetInstance().GetPolicy(intentionPolicyPair.first); - status = status == E_OK ? LifeCyclePolicy->DeleteOnTimeout(intentionPolicyPair.first) : status; + std::string errorInfo; + std::shared_ptr lifeCyclePolicy; + for (auto &[intention, lifeCyclePolicy] : intentionPolicy_) { + if (lifeCyclePolicy == nullptr) { + continue; + } + Status delStatus = lifeCyclePolicy->DeleteOnTimeout(intention); + if (delStatus != E_OK) { + status = delStatus; + errorInfo += intention + " "; + } + } + if (status != E_OK) { + ZLOGW("fail, status = %{public}d, intention = [%{public}s].", status, errorInfo.c_str()); } return status; } } // namespace UDMF -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_manager.h b/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_manager.h index e73032d9..dd90d0df 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_manager.h +++ b/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_manager.h @@ -38,8 +38,7 @@ public: private: static std::shared_ptr executorPool_; - static std::unordered_map> intentionPolicyMap_; - static std::shared_ptr GetPolicy(const std::string &intention); + static std::unordered_map> intentionPolicy_; static Status DeleteOnTimeout(); }; } // namespace UDMF diff --git a/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.h b/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.h index 45f8e63a..b1ba7e04 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.h +++ b/datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.h @@ -31,10 +31,11 @@ public: virtual Status DeleteOnGet(const UnifiedKey &key); virtual Status DeleteOnStart(const std::string &intention); virtual Status DeleteOnTimeout(const std::string &intention); + +private: virtual Status GetTimeoutKeys( const std::shared_ptr &store, Duration interval, std::vector &timeoutKeys); -private: static const std::string DATA_PREFIX; StoreCache storeCache_; }; diff --git a/datamgr_service/services/distributeddataservice/service/udmf/permission/checker_manager.cpp b/datamgr_service/services/distributeddataservice/service/udmf/permission/checker_manager.cpp index 3188a26c..cfb61bf0 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/permission/checker_manager.cpp +++ b/datamgr_service/services/distributeddataservice/service/udmf/permission/checker_manager.cpp @@ -52,6 +52,9 @@ bool CheckerManager::IsValid(const std::vector &privileges, const Che if (it == checkers_.end()) { return true; } + if (it->second == nullptr) { + return false; + } return it->second->IsValid(privileges, info); } } // namespace UDMF diff --git a/datamgr_service/services/distributeddataservice/service/udmf/store/runtime_store.cpp b/datamgr_service/services/distributeddataservice/service/udmf/store/runtime_store.cpp index 25bf609c..612d4ec5 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/store/runtime_store.cpp +++ b/datamgr_service/services/distributeddataservice/service/udmf/store/runtime_store.cpp @@ -59,11 +59,6 @@ Status RuntimeStore::Put(const UnifiedData &unifiedData) // add unified record for (const auto &record : unifiedData.GetRecords()) { - if (record == nullptr) { - ZLOGE("record is nullptr."); - return E_INVALID_PARAMETERS; - } - std::vector recordBytes; auto recordTlv = TLVObject(recordBytes); if (!TLVUtil::Writing(record, recordTlv)) { @@ -104,11 +99,12 @@ Status RuntimeStore::GetSummary(const std::string &key, Summary &summary) for (const auto &record : unifiedData.GetRecords()) { int64_t recordSize = record->GetSize(); - auto it = summary.summary.find(UD_TYPE_MAP.at(record->GetType())); + auto udType = UD_TYPE_MAP.at(record->GetType()); + auto it = summary.summary.find(udType); if (it == summary.summary.end()) { - summary.summary[UD_TYPE_MAP.at(record->GetType())] = recordSize; + summary.summary[udType] = recordSize; } else { - summary.summary[UD_TYPE_MAP.at(record->GetType())] += recordSize; + summary.summary[udType] += recordSize; } summary.totalSize += recordSize; } @@ -117,14 +113,14 @@ Status RuntimeStore::GetSummary(const std::string &key, Summary &summary) Status RuntimeStore::Update(const UnifiedData &unifiedData) { - UpdateTime(); std::string key = unifiedData.GetRuntime()->key.key; if (Delete(key) != E_OK) { - ZLOGE("Delete unified data failed."); + UpdateTime(); + ZLOGE("Delete unified data failed, dataPrefix: %{public}s.", key.c_str()); return E_DB_ERROR; } if (Put(unifiedData) != E_OK) { - ZLOGE("Put unified data failed."); + ZLOGE("Update unified data failed, dataPrefix: %{public}s.", key.c_str()); return E_DB_ERROR; } return E_OK; @@ -132,7 +128,6 @@ Status RuntimeStore::Update(const UnifiedData &unifiedData) Status RuntimeStore::Delete(const std::string &key) { - UpdateTime(); std::vector entries; if (GetEntries(key, entries) != E_OK) { ZLOGE("GetEntries failed, dataPrefix: %{public}s.", key.c_str()); diff --git a/datamgr_service/services/distributeddataservice/service/udmf/store/store_cache.cpp b/datamgr_service/services/distributeddataservice/service/udmf/store/store_cache.cpp index ba0c258c..4944e2d9 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/store/store_cache.cpp +++ b/datamgr_service/services/distributeddataservice/service/udmf/store/store_cache.cpp @@ -66,11 +66,11 @@ void StoreCache::GarbageCollect() }); std::unique_lock lock(taskMutex_); if (!stores_.Empty()) { - ZLOGE("GarbageCollect, stores size:%{public}zu", stores_.Size()); + ZLOGD("GarbageCollect, stores size:%{public}zu", stores_.Size()); taskId_ = executorPool_->Schedule(std::chrono::minutes(INTERVAL), std::bind(&StoreCache::GarbageCollect, this)); } else { taskId_ = ExecutorPool::INVALID_TASK_ID; } } } // namespace UDMF -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/datamgr_service/services/distributeddataservice/service/udmf/udmf_service_stub.cpp b/datamgr_service/services/distributeddataservice/service/udmf/udmf_service_stub.cpp index ca92a0fb..d07e7e09 100644 --- a/datamgr_service/services/distributeddataservice/service/udmf/udmf_service_stub.cpp +++ b/datamgr_service/services/distributeddataservice/service/udmf/udmf_service_stub.cpp @@ -63,10 +63,6 @@ int32_t UdmfServiceStub::OnSetData(MessageParcel &data, MessageParcel &reply) return E_INVALID_PARAMETERS; } for (const auto &record : unifiedData.GetRecords()) { - if (record == nullptr) { - ZLOGE("record is nullptr!"); - return E_INVALID_PARAMETERS; - } if (record->GetSize() > UdmfService::MAX_RECORD_SIZE) { ZLOGE("Exceeded record limit!"); return E_INVALID_PARAMETERS; diff --git a/kv_store/bundle.json b/kv_store/bundle.json index 0253ff77..d6a01405 100644 --- a/kv_store/bundle.json +++ b/kv_store/bundle.json @@ -77,6 +77,7 @@ "sub_component": [ "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:build_module", "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata:build_module", + "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddatamgr:build_module", "//foundation/distributeddatamgr/kv_store/interfaces/jskits/distributeddata:build_module", "//foundation/distributeddatamgr/kv_store/kvstoremock/interfaces/jskits/distributeddata:build_module", "//foundation/distributeddatamgr/kv_store/interfaces/jskits/distributedkvstore:build_module", @@ -104,6 +105,15 @@ "header_base": "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddata/include" } }, + { + "name": "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddatamgr:distributeddata_mgr", + "header": { + "header_files": [ + "distributed_data_mgr.h" + ], + "header_base": "//foundation/distributeddatamgr/kv_store/interfaces/innerkits/distributeddatamgr/include" + } + }, { "name": "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", "header": { diff --git a/kv_store/frameworks/CMakeLists.txt b/kv_store/frameworks/CMakeLists.txt index 4f07341f..66c1be0e 100644 --- a/kv_store/frameworks/CMakeLists.txt +++ b/kv_store/frameworks/CMakeLists.txt @@ -11,6 +11,7 @@ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -fprofile-arcs -ftest-coverage") set(MOCK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../mock) add_definitions(-DNAPI_EXPERIMENTAL) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/innerkitsimpl/distributeddatafwk/src kvdbSrc) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/innerkitsimpl/distributeddatasvc/src kvdbSrc) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/innerkitsimpl/kvdb/src kvdbSrc) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/jskitsimpl/distributedkvstore/src jsKVSrc) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/jskitsimpl/distributeddata/src jsDataSrc) @@ -26,8 +27,10 @@ add_library(jskvdb SHARED ${jsKVSrc}) add_library(jsolddb SHARED ${jsDataSrc}) target_link_libraries(kvdb ${links}) target_include_directories(kvdb PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../interfaces/innerkits/distributeddata/include) +target_include_directories(kvdb PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../interfaces/innerkits/distributeddatamgr/include) target_include_directories(kvdb PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/common) target_include_directories(kvdb PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/innerkitsimpl/distributeddatafwk/include) +target_include_directories(kvdb PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/innerkitsimpl/distributeddatasvc/include) target_include_directories(kvdb PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/innerkitsimpl/kvdb/include) target_include_directories(kvdb PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/innerkitsimpl/distributeddatafwk/src) @@ -45,3 +48,5 @@ target_include_directories(jskvdb PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../data target_link_libraries(jsolddb ${links} kvdb) target_include_directories(jsolddb PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/jskitsimpl/distributeddata/include) target_include_directories(jsolddb PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/common) +target_include_directories(jsolddb PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../data_share/interfaces/inner_api/provider/include) +target_include_directories(jsolddb PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../data_share/interfaces/inner_api/common/include) diff --git a/kv_store/frameworks/common/test/concurrent_map_test.cpp b/kv_store/frameworks/common/test/concurrent_map_test.cpp index deda4156..0ef31a68 100644 --- a/kv_store/frameworks/common/test/concurrent_map_test.cpp +++ b/kv_store/frameworks/common/test/concurrent_map_test.cpp @@ -58,6 +58,7 @@ HWTEST_F(ConcurrentMapTest, EmplaceWithNone, TestSize.Level0) auto it = values_.Find(""); ASSERT_TRUE(it.first); } + /** * @tc.name: EmplaceWithFilter * @tc.desc: test the function: diff --git a/kv_store/frameworks/common/test/task_scheduler_test.cpp b/kv_store/frameworks/common/test/task_scheduler_test.cpp index e6009694..e4a1c667 100644 --- a/kv_store/frameworks/common/test/task_scheduler_test.cpp +++ b/kv_store/frameworks/common/test/task_scheduler_test.cpp @@ -258,5 +258,4 @@ HWTEST_F(TaskSchedulerTest, RemoveNoWaitExecute, TestSize.Level0) blockDataWait->SetValue(testData); ASSERT_EQ(blockDataTest->GetValue(), testData + 1); } - } // namespace OHOS::Test \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_service_death_notifier.cpp b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_service_death_notifier.cpp index e73aa300..8c70fc82 100644 --- a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_service_death_notifier.cpp +++ b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/kvstore_service_death_notifier.cpp @@ -20,6 +20,7 @@ #include "ipc_skeleton.h" #include "iservice_registry.h" #include "kvstore_client_death_observer.h" +#include "datamgr_service_proxy.h" #include "log_print.h" #include "refbase.h" #include "system_ability_definition.h" @@ -86,7 +87,7 @@ sptr KvStoreServiceDeathNotifier::GetDistributedKvDataServi } auto remote = samgr->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); - instance->kvDataServiceProxy_ = iface_cast(remote); + instance->kvDataServiceProxy_ = iface_cast(remote); if (instance->kvDataServiceProxy_ == nullptr) { ZLOGE("initialize proxy failed."); return nullptr; diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/BUILD.gn b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/BUILD.gn index feca27a0..dc43f1ad 100644 --- a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/BUILD.gn +++ b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/BUILD.gn @@ -11,6 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. import("//build/test.gni") +import("//foundation/distributeddatamgr/kv_store/kv_store.gni") module_output_path = "kv_store/distributeddatafwk" @@ -21,10 +22,12 @@ config("module_private_config") { include_dirs = [ "../include/", "../src/", + "../../distributeddatasvc/include/", "../../kvdb/include/", "../../kvdb/src/", "../../../common/", "../../../../interfaces/innerkits/distributeddata/include/", + "../../../../interfaces/innerkits/distributeddatamgr/include/", # for ipc_core interfaces. "//commonlibrary/c_utils/base/include", @@ -47,7 +50,6 @@ ohos_source_set("distributeddatafwk_src_file") { "../src/data_query.cpp", "../src/distributed_kv_data_manager.cpp", "../src/ikvstore_client_death_observer.cpp", - "../src/ikvstore_data_service.cpp", "../src/ikvstore_observer.cpp", "../src/ikvstore_sync_callback.cpp", "../src/kv_utils.cpp", @@ -83,6 +85,7 @@ ohos_source_set("distributeddatafwk_src_file") { configs = [ ":module_private_config" ] deps = [ + "../../../../interfaces/innerkits/distributeddatamgr:distributeddata_mgr", "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp:devicemanagersdk", ] diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/device_kvstore_test.cpp b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/device_kvstore_test.cpp index b4858c03..53b6c29b 100644 --- a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/device_kvstore_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/device_kvstore_test.cpp @@ -59,7 +59,6 @@ Options DeviceKvStoreTest::options_; void DeviceKvStoreTest::SetUpTestCase(void) { - OHOS::SaveStringToFile("/sys/fs/selinux/enforce", "0"); DistributedKvDataManager manager; options_.area = EL1; options_.baseDir = std::string("/data/service/el1/public/database/odmf"); @@ -74,7 +73,6 @@ void DeviceKvStoreTest::SetUpTestCase(void) void DeviceKvStoreTest::TearDownTestCase(void) { - OHOS::SaveStringToFile("/sys/fs/selinux/enforce", "1"); DistributedKvDataManager manager; AppId appId = { "odmf" }; manager.DeleteAllKvStore(appId, options_.baseDir); diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/distributed_kv_data_manager_encrypt_test.cpp b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/distributed_kv_data_manager_encrypt_test.cpp index 86c19adf..93dc51b0 100644 --- a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/distributed_kv_data_manager_encrypt_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/distributed_kv_data_manager_encrypt_test.cpp @@ -68,7 +68,6 @@ void DistributedKvDataManagerEncryptTest::RemoveAllStore(DistributedKvDataManage } void DistributedKvDataManagerEncryptTest::SetUpTestCase(void) { - OHOS::SaveStringToFile("/sys/fs/selinux/enforce", "0"); createEnc.createIfMissing = true; createEnc.encrypt = true; createEnc.autoSync = true; @@ -86,7 +85,6 @@ void DistributedKvDataManagerEncryptTest::SetUpTestCase(void) void DistributedKvDataManagerEncryptTest::TearDownTestCase(void) { - OHOS::SaveStringToFile("/sys/fs/selinux/enforce", "1"); RemoveAllStore(manager); (void)remove((createEnc.baseDir + "/kvdb").c_str()); (void)remove(createEnc.baseDir.c_str()); @@ -130,4 +128,4 @@ HWTEST_F(DistributedKvDataManagerEncryptTest, kvstore_ddm_createEncryptedStore_0 EXPECT_EQ(Status::SUCCESS, statusRet) << "get data return wrong status"; EXPECT_EQ(value, valueRet) << "value and valueRet are not equal"; -} +} \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/distributed_kv_data_manager_test.cpp b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/distributed_kv_data_manager_test.cpp index e65db8d5..579f428a 100644 --- a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/distributed_kv_data_manager_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/distributed_kv_data_manager_test.cpp @@ -692,23 +692,4 @@ HWTEST_F(DistributedKvDataManagerTest, DeleteAllKvStore004, TestSize.Level1) stat = manager.DeleteAllKvStore(appId, create.baseDir); EXPECT_EQ(stat, Status::SUCCESS); } - -/** -* @tc.name: RegisterKvStoreServiceDeathRecipient001 -* @tc.desc: Register a callback called when the service dies. -* @tc.type: FUNC -* @tc.require: SR000CQDU0 AR000CQDU1 -* @tc.author: liqiao -*/ -HWTEST_F(DistributedKvDataManagerTest, RegisterKvStoreServiceDeathRecipient001, TestSize.Level1) -{ - ZLOGI("RegisterKvStoreServiceDeathRecipient001 begin."); - std::shared_ptr kvStoreDeathRecipient = nullptr; - manager.RegisterKvStoreServiceDeathRecipient(kvStoreDeathRecipient); - manager.UnRegisterKvStoreServiceDeathRecipient(kvStoreDeathRecipient); - - kvStoreDeathRecipient = std::make_shared(); - manager.RegisterKvStoreServiceDeathRecipient(kvStoreDeathRecipient); - kvStoreDeathRecipient->OnRemoteDied(); -} } // namespace OHOS::Test \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_query_test.cpp b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_query_test.cpp index e7ef8ca5..b53dc18f 100644 --- a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_query_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_query_test.cpp @@ -20,7 +20,6 @@ #include #include #include "distributed_kv_data_manager.h" -#include "file_ex.h" #include "types.h" #include "gtest/gtest.h" namespace { @@ -54,14 +53,12 @@ static constexpr uint32_t MAX_QUERY_LENGTH = 1024; void SingleKvStoreClientQueryTest::SetUpTestCase(void) { - OHOS::SaveStringToFile("/sys/fs/selinux/enforce", "0"); std::string baseDir = "/data/service/el1/public/database/SingleKvStoreClientQueryTest"; mkdir(baseDir.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); } void SingleKvStoreClientQueryTest::TearDownTestCase(void) { - OHOS::SaveStringToFile("/sys/fs/selinux/enforce", "1"); (void)remove("/data/service/el1/public/database/SingleKvStoreClientQueryTest/key"); (void)remove("/data/service/el1/public/database/SingleKvStoreClientQueryTest/kvdb"); (void)remove("/data/service/el1/public/database/SingleKvStoreClientQueryTest"); diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_test.cpp b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_test.cpp index 25da5edf..ea78fb11 100644 --- a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/distributeddatafwk/test/unittest/single_kvstore_client_test.cpp @@ -54,7 +54,6 @@ int SingleKvStoreClientTest::MAX_VALUE_SIZE = 4 * 1024 * 1024; // max value size void SingleKvStoreClientTest::SetUpTestCase(void) { - OHOS::SaveStringToFile("/sys/fs/selinux/enforce", "0"); DistributedKvDataManager manager; Options options = { .createIfMissing = true, .encrypt = false, .autoSync = true, .kvStoreType = KvStoreType::SINGLE_VERSION }; @@ -69,7 +68,6 @@ void SingleKvStoreClientTest::SetUpTestCase(void) void SingleKvStoreClientTest::TearDownTestCase(void) { - OHOS::SaveStringToFile("/sys/fs/selinux/enforce", "1"); (void)remove("/data/service/el1/public/database/odmf/key"); (void)remove("/data/service/el1/public/database/odmf/kvdb"); (void)remove("/data/service/el1/public/database/odmf"); @@ -817,7 +815,7 @@ HWTEST_F(SingleKvStoreClientTest, DdmDeleteBatch003, TestSize.Level2) { EXPECT_NE(nullptr, singleKvStore) << "singleKvStore is nullptr"; - // Store entries to KvStore. + // Store entries to KvStore. std::vector entries; Entry entry1, entry2, entry3; entry1.key = "SingleKvStoreDdmDeleteBatch003_1"; @@ -1191,4 +1189,4 @@ HWTEST_F(SingleKvStoreClientTest, UnSubscribeWithQuery001, TestSize.Level1) dataQuery.KeyPrefix("name"); auto unSubscribeStatus = singleKvStore->UnsubscribeWithQuery(deviceIds, dataQuery); EXPECT_NE(unSubscribeStatus, Status::SUCCESS) << "sync device should not return success"; -} +} \ No newline at end of file diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatasvc/include/datamgr_service_proxy.h b/kv_store/frameworks/innerkitsimpl/distributeddatasvc/include/datamgr_service_proxy.h new file mode 100644 index 00000000..510647da --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/distributeddatasvc/include/datamgr_service_proxy.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023 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 KVSTORE_DATA_SERVICE_PROXY_H +#define KVSTORE_DATA_SERVICE_PROXY_H +#include "ikvstore_data_service.h" +namespace OHOS::DistributedKv { +class DataMgrServiceProxy : public IRemoteProxy { +public: + explicit API_EXPORT DataMgrServiceProxy(const sptr &impl); + ~DataMgrServiceProxy() = default; + sptr GetFeatureInterface(const std::string &name) override; + + Status RegisterClientDeathObserver(const AppId &appId, sptr observer) override; + + int32_t ClearAppStorage(const std::string &bundleName, int32_t userId, int32_t appIndex, int32_t tokenId) override; + +private: + static inline BrokerDelegator delegator_; +}; +} +#endif //KVSTORE_DATA_SERVICE_PROXY_H diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/include/distributeddata_ipc_interface_code.h b/kv_store/frameworks/innerkitsimpl/distributeddatasvc/include/distributeddata_ipc_interface_code.h similarity index 93% rename from kv_store/frameworks/innerkitsimpl/distributeddatafwk/include/distributeddata_ipc_interface_code.h rename to kv_store/frameworks/innerkitsimpl/distributeddatasvc/include/distributeddata_ipc_interface_code.h index ea279de2..4776377e 100644 --- a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/include/distributeddata_ipc_interface_code.h +++ b/kv_store/frameworks/innerkitsimpl/distributeddatasvc/include/distributeddata_ipc_interface_code.h @@ -23,7 +23,8 @@ namespace OHOS::DistributedKv { enum class KvStoreDataServiceInterfaceCode : uint32_t { GET_FEATURE_INTERFACE = 0, REGISTERCLIENTDEATHOBSERVER, + CLEAR_APP_STORAGE, SERVICE_CMD_LAST }; } // namespace OHOS::DistributedKv -#endif // DISTRIBUTEDDATA_IPC_INTERFACE_CODE_H \ No newline at end of file +#endif // DISTRIBUTEDDATA_IPC_INTERFACE_CODE_H diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_data_service.h b/kv_store/frameworks/innerkitsimpl/distributeddatasvc/include/ikvstore_data_service.h similarity index 47% rename from kv_store/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_data_service.h rename to kv_store/frameworks/innerkitsimpl/distributeddatasvc/include/ikvstore_data_service.h index 408fbc75..8c30d51d 100644 --- a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/include/ikvstore_data_service.h +++ b/kv_store/frameworks/innerkitsimpl/distributeddatasvc/include/ikvstore_data_service.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2023 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 @@ -16,14 +16,12 @@ #ifndef I_KV_STORE_DATA_SERVICE_H #define I_KV_STORE_DATA_SERVICE_H -#include "distributeddata_ipc_interface_code.h" #include "iremote_broker.h" -#include "ikvstore_client_death_observer.h" -#include "ikvstore_observer.h" #include "iremote_proxy.h" #include "iremote_stub.h" #include "message_parcel.h" #include "types.h" +#include "distributeddata_ipc_interface_code.h" namespace OHOS::DistributedKv { class IKvStoreDataService : public IRemoteBroker { @@ -34,38 +32,13 @@ public: virtual Status RegisterClientDeathObserver(const AppId &appId, sptr observer) = 0; + virtual int32_t ClearAppStorage(const std::string &bundleName, int32_t userId, int32_t appIndex, + int32_t tokenId) = 0; + protected: static constexpr size_t MAX_IPC_CAPACITY = 800 * 1024; }; -class KvStoreDataServiceStub : public IRemoteStub { -public: - int API_EXPORT OnRemoteRequest(uint32_t code, MessageParcel &data, - MessageParcel &reply, MessageOption &option) override; - -private: - int32_t GetFeatureInterfaceOnRemote(MessageParcel &data, MessageParcel &reply); - int32_t RegisterClientDeathObserverOnRemote(MessageParcel &data, MessageParcel &reply); - - using RequestHandler = int32_t(KvStoreDataServiceStub::*)(MessageParcel&, MessageParcel&); - static constexpr RequestHandler - HANDLERS[static_cast(KvStoreDataServiceInterfaceCode::SERVICE_CMD_LAST)] = { - &KvStoreDataServiceStub::GetFeatureInterfaceOnRemote, - &KvStoreDataServiceStub::RegisterClientDeathObserverOnRemote, - }; -}; - -class API_EXPORT KvStoreDataServiceProxy : public IRemoteProxy { -public: - explicit KvStoreDataServiceProxy(const sptr &impl); - ~KvStoreDataServiceProxy() = default; - sptr GetFeatureInterface(const std::string &name) override; - - Status RegisterClientDeathObserver(const AppId &appId, sptr observer) override; - -private: - static inline BrokerDelegator delegator_; -}; } // namespace OHOS::DistributedKv -#endif // I_KV_STORE_DATA_SERVICE_H \ No newline at end of file +#endif // I_KV_STORE_DATA_SERVICE_H diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatasvc/include/kvstore_data_service_mgr.h b/kv_store/frameworks/innerkitsimpl/distributeddatasvc/include/kvstore_data_service_mgr.h new file mode 100644 index 00000000..ba2e62bd --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/distributeddatasvc/include/kvstore_data_service_mgr.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2023 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 KVSTORE_DATA_SERVICE_MGR_H +#define KVSTORE_DATA_SERVICE_MGR_H +#include +#include + +#include "ikvstore_data_service.h" +#include "iremote_object.h" + +namespace OHOS::DistributedKv { +class KvStoreDataServiceMgr { +public: + static int32_t ClearAppStorage(const std::string &bundleName, int32_t userId, int32_t appIndex, int32_t tokenId); +}; +} +#endif //KVSTORE_DATA_SERVICE_MGR_H diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp b/kv_store/frameworks/innerkitsimpl/distributeddatasvc/src/datamgr_service_proxy.cpp similarity index 51% rename from kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp rename to kv_store/frameworks/innerkitsimpl/distributeddatasvc/src/datamgr_service_proxy.cpp index 72130884..caca03a7 100644 --- a/kv_store/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp +++ b/kv_store/frameworks/innerkitsimpl/distributeddatasvc/src/datamgr_service_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2023 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 @@ -13,9 +13,9 @@ * limitations under the License. */ -#define LOG_TAG "KvStoreDataServiceProxy" +#define LOG_TAG "DataMgrServiceProxy" -#include "ikvstore_data_service.h" +#include "datamgr_service_proxy.h" #include #include "itypes_util.h" #include "message_parcel.h" @@ -24,25 +24,23 @@ namespace OHOS { namespace DistributedKv { -constexpr KvStoreDataServiceStub::RequestHandler - KvStoreDataServiceStub::HANDLERS[static_cast(KvStoreDataServiceInterfaceCode::SERVICE_CMD_LAST)]; -KvStoreDataServiceProxy::KvStoreDataServiceProxy(const sptr &impl) +DataMgrServiceProxy::DataMgrServiceProxy(const sptr &impl) : IRemoteProxy(impl) { ZLOGI("init data service proxy."); } -sptr KvStoreDataServiceProxy::GetFeatureInterface(const std::string &name) +sptr DataMgrServiceProxy::GetFeatureInterface(const std::string &name) { ZLOGI("%s", name.c_str()); MessageParcel data; - if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) { + if (!data.WriteInterfaceToken(DataMgrServiceProxy::GetDescriptor())) { ZLOGE("write descriptor failed"); return nullptr; } if (!ITypesUtil::Marshal(data, name)) { - ZLOGE("write descriptor failed"); + ZLOGE("write name failed, name is %{public}s", name.c_str()); return nullptr; } @@ -63,11 +61,11 @@ sptr KvStoreDataServiceProxy::GetFeatureInterface(const std::stri return remoteObject; } -Status KvStoreDataServiceProxy::RegisterClientDeathObserver(const AppId &appId, sptr observer) +Status DataMgrServiceProxy::RegisterClientDeathObserver(const AppId &appId, sptr observer) { MessageParcel data; MessageParcel reply; - if (!data.WriteInterfaceToken(KvStoreDataServiceProxy::GetDescriptor())) { + if (!data.WriteInterfaceToken(DataMgrServiceProxy::GetDescriptor())) { ZLOGE("write descriptor failed"); return Status::IPC_ERROR; } @@ -94,49 +92,29 @@ Status KvStoreDataServiceProxy::RegisterClientDeathObserver(const AppId &appId, return static_cast(reply.ReadInt32()); } -int32_t KvStoreDataServiceStub::RegisterClientDeathObserverOnRemote(MessageParcel &data, MessageParcel &reply) +int32_t DataMgrServiceProxy::ClearAppStorage(const std::string &bundleName, int32_t userId, int32_t appIndex, + int32_t tokenId) { - AppId appId = { data.ReadString() }; - sptr kvStoreClientDeathObserverProxy = data.ReadRemoteObject(); - if (kvStoreClientDeathObserverProxy == nullptr) { - return -1; + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(DataMgrServiceProxy::GetDescriptor())) { + ZLOGE("write descriptor failed"); + return Status::IPC_ERROR; } - Status status = RegisterClientDeathObserver(appId, std::move(kvStoreClientDeathObserverProxy)); - if (!reply.WriteInt32(static_cast(status))) { - return -1; + if (!ITypesUtil::Marshal(data, bundleName, userId, appIndex, tokenId)) { + ZLOGW("failed to write bundleName:%{public}s, user:%{public}d, appIndex:%{public}d, tokenID:%{public}d", + bundleName.c_str(), userId, appIndex, tokenId); + return Status::IPC_ERROR; } - return 0; -} -int32_t KvStoreDataServiceStub::GetFeatureInterfaceOnRemote(MessageParcel &data, MessageParcel &reply) -{ - std::string name; - if (!ITypesUtil::Unmarshal(data, name)) { - return -1; - } - auto remoteObject = GetFeatureInterface(name); - if (!ITypesUtil::Marshal(reply, remoteObject)) { - return -1; - } - return 0; -} - -int32_t KvStoreDataServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, - MessageParcel &reply, MessageOption &option) -{ - ZLOGD("code:%{public}u, callingPid:%{public}d", code, IPCSkeleton::GetCallingPid()); - std::u16string descriptor = KvStoreDataServiceStub::GetDescriptor(); - std::u16string remoteDescriptor = data.ReadInterfaceToken(); - if (descriptor != remoteDescriptor) { - ZLOGE("local descriptor is not equal to remote"); - return -1; - } - if (code >= 0 && code < static_cast(KvStoreDataServiceInterfaceCode::SERVICE_CMD_LAST)) { - return (this->*HANDLERS[code])(data, reply); - } else { - MessageOption mo { MessageOption::TF_SYNC }; - return IPCObjectStub::OnRemoteRequest(code, data, reply, mo); + MessageOption mo { MessageOption::TF_SYNC }; + int32_t error = Remote()->SendRequest( + static_cast(KvStoreDataServiceInterfaceCode::CLEAR_APP_STORAGE), data, reply, mo); + if (error != 0) { + ZLOGW("failed during IPC. errCode %d", error); + return Status::IPC_ERROR; } + return static_cast(reply.ReadInt32()); } } // namespace DistributedKv } // namespace OHOS diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatasvc/src/distributed_data_mgr.cpp b/kv_store/frameworks/innerkitsimpl/distributeddatasvc/src/distributed_data_mgr.cpp new file mode 100644 index 00000000..9fba6f7a --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/distributeddatasvc/src/distributed_data_mgr.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2023 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. + */ +#define LOG_TAG "DistributedDataMgr" +#include "kvstore_data_service_mgr.h" +#include "distributed_data_mgr.h" + +namespace OHOS::DistributedKv { +DistributedDataMgr::DistributedDataMgr() = default; +DistributedDataMgr::~DistributedDataMgr() = default; +int32_t DistributedKv::DistributedDataMgr::ClearAppStorage(const std::string &bundleName, int32_t userId, + int32_t appIndex, int32_t tokenId) +{ + return KvStoreDataServiceMgr::ClearAppStorage(bundleName, userId, appIndex, tokenId); +} +} // namespace OHOS::DistributedKv diff --git a/kv_store/frameworks/innerkitsimpl/distributeddatasvc/src/kvstore_data_service_mgr.cpp b/kv_store/frameworks/innerkitsimpl/distributeddatasvc/src/kvstore_data_service_mgr.cpp new file mode 100644 index 00000000..5b916bc0 --- /dev/null +++ b/kv_store/frameworks/innerkitsimpl/distributeddatasvc/src/kvstore_data_service_mgr.cpp @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2023 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. + */ +#define LOG_TAG "KvStoreDataServiceMgr" +#include "kvstore_data_service_mgr.h" +#include "log_print.h" +#include "system_ability_definition.h" +#include "iservice_registry.h" +namespace OHOS::DistributedKv { +int32_t KvStoreDataServiceMgr::ClearAppStorage(const std::string &bundleName, int32_t userId, int32_t appIndex, + int32_t tokenId) +{ + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + ZLOGE("KvStoreDataServiceMgr get samgr fail."); + return ERROR; + } + + auto remote = samgr->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); + sptr ability = iface_cast(remote); + if (ability == nullptr) { + ZLOGE("KvStoreDataServiceMgr initialize proxy failed."); + return ERROR; + } + return ability->ClearAppStorage(bundleName, userId, appIndex, tokenId); +} +} diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/BUILD.gn b/kv_store/frameworks/innerkitsimpl/kvdb/test/BUILD.gn index c5a7c29d..e067f62f 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/BUILD.gn +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/BUILD.gn @@ -12,6 +12,7 @@ # limitations under the License. import("//build/test.gni") import("//foundation/distributeddatamgr/data_share/datashare.gni") +import("//foundation/distributeddatamgr/kv_store/kv_store.gni") module_output_path = "kv_store/distributeddatafwk" @@ -20,6 +21,8 @@ config("module_private_config") { visibility = [ ":*" ] include_dirs = [ + "${kv_store_base_path}/frameworks/innerkitsimpl/distributeddatasvc/include", + "../../../../interfaces/innerkits/distributeddatamgr/include/", "//commonlibrary/c_utils/base/include", "${datashare_innerapi_path}/common/include", "${datashare_innerapi_path}/provider/include", @@ -50,7 +53,6 @@ ohos_source_set("kvdb_src_file") { "../../distributeddatafwk/src/data_query.cpp", "../../distributeddatafwk/src/distributed_kv_data_manager.cpp", "../../distributeddatafwk/src/ikvstore_client_death_observer.cpp", - "../../distributeddatafwk/src/ikvstore_data_service.cpp", "../../distributeddatafwk/src/ikvstore_observer.cpp", "../../distributeddatafwk/src/ikvstore_sync_callback.cpp", "../../distributeddatafwk/src/kv_utils.cpp", @@ -86,6 +88,7 @@ ohos_source_set("kvdb_src_file") { configs = [ ":module_private_config" ] deps = [ + "../../../../interfaces/innerkits/distributeddatamgr:distributeddata_mgr", "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", "//foundation/distributedhardware/device_manager/interfaces/inner_kits/native_cpp:devicemanagersdk", ] diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/backup_manager_test.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/backup_manager_test.cpp index 6d79dd6f..c900b605 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/backup_manager_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/backup_manager_test.cpp @@ -43,7 +43,6 @@ public: void BackupManagerTest::SetUpTestCase(void) { - OHOS::SaveStringToFile("/sys/fs/selinux/enforce", "0"); std::string baseDir = "/data/service/el1/public/database/BackupManagerTest"; mkdir(baseDir.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); mkdir((baseDir + "/key").c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); @@ -51,7 +50,6 @@ void BackupManagerTest::SetUpTestCase(void) void BackupManagerTest::TearDownTestCase(void) { - OHOS::SaveStringToFile("/sys/fs/selinux/enforce", "1"); std::string baseDir = "/data/service/el1/public/database/BackupManagerTest"; StoreManager::GetInstance().Delete({ "BackupManagerTest" }, { "SingleKVStore" }, baseDir); diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_test.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_test.cpp index 5a5703b3..43112888 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/single_store_impl_test.cpp @@ -70,14 +70,12 @@ public: void SingleStoreImplTest::SetUpTestCase(void) { - OHOS::SaveStringToFile("/sys/fs/selinux/enforce", "0"); std::string baseDir = "/data/service/el1/public/database/SingleStoreImplTest"; mkdir(baseDir.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); } void SingleStoreImplTest::TearDownTestCase(void) { - OHOS::SaveStringToFile("/sys/fs/selinux/enforce", "1"); std::string baseDir = "/data/service/el1/public/database/SingleStoreImplTest"; StoreManager::GetInstance().Delete({ "SingleStoreImplTest" }, { "SingleKVStore" }, baseDir); diff --git a/kv_store/frameworks/innerkitsimpl/kvdb/test/store_factory_test.cpp b/kv_store/frameworks/innerkitsimpl/kvdb/test/store_factory_test.cpp index dac65cc5..87731f07 100644 --- a/kv_store/frameworks/innerkitsimpl/kvdb/test/store_factory_test.cpp +++ b/kv_store/frameworks/innerkitsimpl/kvdb/test/store_factory_test.cpp @@ -77,14 +77,12 @@ void StoreFactoryTest::TearDownTestCase(void) void StoreFactoryTest::SetUp(void) { - OHOS::SaveStringToFile("/sys/fs/selinux/enforce", "0"); std::string baseDir = "/data/service/el1/public/database/rekey"; mkdir(baseDir.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)); } void StoreFactoryTest::TearDown(void) { - OHOS::SaveStringToFile("/sys/fs/selinux/enforce", "1"); DeleteKVStore(); (void)remove("/data/service/el1/public/database/rekey"); } @@ -356,4 +354,4 @@ HWTEST_F(StoreFactoryTest, RekeyNoPwdFile, TestSize.Level1) StoreManager::GetInstance().GetKVStore(appId, storeId, options, status); ASSERT_EQ(status, CRYPT_ERROR); } -} +} \ No newline at end of file diff --git a/kv_store/frameworks/jskitsimpl/distributeddata/include/js_const_properties.h b/kv_store/frameworks/jskitsimpl/distributeddata/include/js_const_properties.h index dcc861be..367261d9 100644 --- a/kv_store/frameworks/jskitsimpl/distributeddata/include/js_const_properties.h +++ b/kv_store/frameworks/jskitsimpl/distributeddata/include/js_const_properties.h @@ -16,9 +16,9 @@ #ifndef OHOS_JS_CONST_PROPERTIES_H #define OHOS_JS_CONST_PROPERTIES_H -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_common.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS::DistributedData { napi_status InitConstProperties(napi_env env, napi_value exports); diff --git a/kv_store/frameworks/jskitsimpl/distributeddata/include/js_util.h b/kv_store/frameworks/jskitsimpl/distributeddata/include/js_util.h index 1076e1af..d9ebeead 100644 --- a/kv_store/frameworks/jskitsimpl/distributeddata/include/js_util.h +++ b/kv_store/frameworks/jskitsimpl/distributeddata/include/js_util.h @@ -20,9 +20,9 @@ #include "data_query.h" #include "js_kv_manager.h" #include "change_notification.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "datashare_abs_predicates.h" #include "datashare_values_bucket.h" diff --git a/kv_store/frameworks/jskitsimpl/distributeddata/include/napi_queue.h b/kv_store/frameworks/jskitsimpl/distributeddata/include/napi_queue.h index c205511b..7022dcff 100644 --- a/kv_store/frameworks/jskitsimpl/distributeddata/include/napi_queue.h +++ b/kv_store/frameworks/jskitsimpl/distributeddata/include/napi_queue.h @@ -19,9 +19,9 @@ #include #include "log_print.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS::DistributedData { constexpr size_t ARGC_MAX = 6; diff --git a/kv_store/frameworks/jskitsimpl/distributeddata/include/uv_queue.h b/kv_store/frameworks/jskitsimpl/distributeddata/include/uv_queue.h index 78e622c5..b5b96ea7 100644 --- a/kv_store/frameworks/jskitsimpl/distributeddata/include/uv_queue.h +++ b/kv_store/frameworks/jskitsimpl/distributeddata/include/uv_queue.h @@ -15,9 +15,9 @@ #ifndef OHOS_UV_QUEUE_H #define OHOS_UV_QUEUE_H #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "uv.h" namespace OHOS::DistributedData { diff --git a/kv_store/frameworks/jskitsimpl/distributedkvstore/include/js_const_properties.h b/kv_store/frameworks/jskitsimpl/distributedkvstore/include/js_const_properties.h index 29465db6..e34d8563 100644 --- a/kv_store/frameworks/jskitsimpl/distributedkvstore/include/js_const_properties.h +++ b/kv_store/frameworks/jskitsimpl/distributedkvstore/include/js_const_properties.h @@ -16,9 +16,9 @@ #ifndef OHOS_JS_CONST_PROPERTIES_H #define OHOS_JS_CONST_PROPERTIES_H -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_common.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS::DistributedKVStore { napi_status InitConstProperties(napi_env env, napi_value exports); diff --git a/kv_store/frameworks/jskitsimpl/distributedkvstore/include/js_error_utils.h b/kv_store/frameworks/jskitsimpl/distributedkvstore/include/js_error_utils.h index 47062431..2b9788f2 100644 --- a/kv_store/frameworks/jskitsimpl/distributedkvstore/include/js_error_utils.h +++ b/kv_store/frameworks/jskitsimpl/distributedkvstore/include/js_error_utils.h @@ -19,7 +19,7 @@ #include #include "store_errno.h" #include "js_native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" +#include "napi/native_common.h" #include "log_print.h" namespace OHOS { diff --git a/kv_store/frameworks/jskitsimpl/distributedkvstore/include/js_util.h b/kv_store/frameworks/jskitsimpl/distributedkvstore/include/js_util.h index 567eb0fb..2d24da1a 100644 --- a/kv_store/frameworks/jskitsimpl/distributedkvstore/include/js_util.h +++ b/kv_store/frameworks/jskitsimpl/distributedkvstore/include/js_util.h @@ -20,9 +20,9 @@ #include "data_query.h" #include "js_kv_manager.h" #include "change_notification.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "datashare_abs_predicates.h" #include "datashare_values_bucket.h" #include "js_error_utils.h" diff --git a/kv_store/frameworks/jskitsimpl/distributedkvstore/include/napi_queue.h b/kv_store/frameworks/jskitsimpl/distributedkvstore/include/napi_queue.h index 2841fea1..ec7a4a43 100644 --- a/kv_store/frameworks/jskitsimpl/distributedkvstore/include/napi_queue.h +++ b/kv_store/frameworks/jskitsimpl/distributedkvstore/include/napi_queue.h @@ -19,9 +19,9 @@ #include #include "log_print.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS::DistributedKVStore { constexpr size_t ARGC_MAX = 6; diff --git a/kv_store/frameworks/jskitsimpl/distributedkvstore/include/uv_queue.h b/kv_store/frameworks/jskitsimpl/distributedkvstore/include/uv_queue.h index 92252696..f467a763 100644 --- a/kv_store/frameworks/jskitsimpl/distributedkvstore/include/uv_queue.h +++ b/kv_store/frameworks/jskitsimpl/distributedkvstore/include/uv_queue.h @@ -15,9 +15,9 @@ #ifndef OHOS_UV_QUEUE_H #define OHOS_UV_QUEUE_H #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "uv.h" namespace OHOS::DistributedKVStore { diff --git a/kv_store/frameworks/libs/distributeddb/BUILD.gn b/kv_store/frameworks/libs/distributeddb/BUILD.gn index ae33396b..537f4f5f 100644 --- a/kv_store/frameworks/libs/distributeddb/BUILD.gn +++ b/kv_store/frameworks/libs/distributeddb/BUILD.gn @@ -51,7 +51,6 @@ config("distrdb_config") { "OMIT_FLATBUFFER", "OMIT_MULTI_VER", "RELATIONAL_STORE", - "MANNUAL_SYNC_AND_CLEAN_CLOUD_DATA", "SQLITE_DISTRIBUTE_RELATIONAL", "USE_DFX_ABILITY", "SQLITE_ENABLE_DROPTABLE_CALLBACK", diff --git a/kv_store/frameworks/libs/distributeddb/common/include/cloud/cloud_db_types.h b/kv_store/frameworks/libs/distributeddb/common/include/cloud/cloud_db_types.h index a3e4a3cb..c4604f80 100644 --- a/kv_store/frameworks/libs/distributeddb/common/include/cloud/cloud_db_types.h +++ b/kv_store/frameworks/libs/distributeddb/common/include/cloud/cloud_db_types.h @@ -38,11 +38,6 @@ struct CloudSyncData { CloudSyncData(const std::string &_tableName) : tableName(_tableName) {}; }; -struct AssetField { - DistributedDB::Field field; - int64_t index = 0u; -}; - template struct index_of : std::integral_constant {}; diff --git a/kv_store/frameworks/libs/distributeddb/common/include/db_common.h b/kv_store/frameworks/libs/distributeddb/common/include/db_common.h index 2cdb848c..f471c0fa 100644 --- a/kv_store/frameworks/libs/distributeddb/common/include/db_common.h +++ b/kv_store/frameworks/libs/distributeddb/common/include/db_common.h @@ -76,6 +76,8 @@ public: static std::string TrimSpace(const std::string &input); + static void RTrim(std::string &oriString); + static bool HasConstraint(const std::string &sql, const std::string &keyWord, const std::string &prePattern, const std::string &nextPattern); @@ -83,6 +85,8 @@ public: static std::string ToLowerCase(const std::string &str); + static std::string ToUpperCase(const std::string &str); + static bool CaseInsensitiveCompare(std::string first, std::string second); static bool CheckIsAlnumAndUnderscore(const std::string &text); diff --git a/kv_store/frameworks/libs/distributeddb/common/include/db_constant.h b/kv_store/frameworks/libs/distributeddb/common/include/db_constant.h index aab366fd..40d72c5f 100644 --- a/kv_store/frameworks/libs/distributeddb/common/include/db_constant.h +++ b/kv_store/frameworks/libs/distributeddb/common/include/db_constant.h @@ -149,7 +149,8 @@ public: static const std::string LOG_TABLE_VERSION_1; static const std::string LOG_TABLE_VERSION_2; - const char *LOG_TABLE_VERSION_3 = "3.0"; + static constexpr const char *LOG_TABLE_VERSION_3 = "3.0"; + static constexpr const char *LOG_TABLE_VERSION_4 = "4.0"; static const std::string LOG_TABLE_VERSION_CURRENT; static const std::string LOG_TABLE_VERSION_KEY; diff --git a/kv_store/frameworks/libs/distributeddb/common/include/performance_analysis.h b/kv_store/frameworks/libs/distributeddb/common/include/performance_analysis.h index 286fe4ac..5463bcc1 100644 --- a/kv_store/frameworks/libs/distributeddb/common/include/performance_analysis.h +++ b/kv_store/frameworks/libs/distributeddb/common/include/performance_analysis.h @@ -17,6 +17,7 @@ #define PERFORMANCE_ANALYSIS_H #include +#include #include #include "db_types.h" @@ -120,6 +121,7 @@ private: std::ofstream outFile; int fileNumber_; std::string fileName_; + static std::once_flag initFlag_; }; } // namespace DistributedDB #endif diff --git a/kv_store/frameworks/libs/distributeddb/common/include/relational/table_info.h b/kv_store/frameworks/libs/distributeddb/common/include/relational/table_info.h index 7c469e00..31f07970 100644 --- a/kv_store/frameworks/libs/distributeddb/common/include/relational/table_info.h +++ b/kv_store/frameworks/libs/distributeddb/common/include/relational/table_info.h @@ -54,6 +54,10 @@ public: bool IsAssetType() const; bool IsAssetsType() const; + + CollateType GetCollateType() const; + void SetCollateType(CollateType collateType); + private: std::string fieldName_; std::string dataType_; // Type may be null @@ -62,6 +66,7 @@ private: bool hasDefaultValue_ = false; std::string defaultValue_; int64_t cid_ = -1; + CollateType collateType_ = CollateType::COLLATE_NONE; }; using FieldInfoMap = std::map; diff --git a/kv_store/frameworks/libs/distributeddb/common/src/db_common.cpp b/kv_store/frameworks/libs/distributeddb/common/src/db_common.cpp index c60311cb..40c1abae 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/db_common.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/db_common.cpp @@ -381,6 +381,14 @@ std::string DBCommon::TrimSpace(const std::string &input) return res; } +void DBCommon::RTrim(std::string &oriString) +{ + if (oriString.empty()) { + return; + } + oriString.erase(oriString.find_last_not_of(" ") + 1); +} + namespace { bool CharIn(char c, const std::string &pattern) { @@ -425,6 +433,13 @@ std::string DBCommon::ToLowerCase(const std::string &str) return res; } +std::string DBCommon::ToUpperCase(const std::string &str) +{ + std::string res(str.length(), ' '); + std::transform(str.begin(), str.end(), res.begin(), ::toupper); + return res; +} + bool DBCommon::CaseInsensitiveCompare(std::string first, std::string second) { std::transform(first.begin(), first.end(), first.begin(), ::tolower); diff --git a/kv_store/frameworks/libs/distributeddb/common/src/db_constant.cpp b/kv_store/frameworks/libs/distributeddb/common/src/db_constant.cpp index eb7a24d0..9ce5e351 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/db_constant.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/db_constant.cpp @@ -73,7 +73,7 @@ const std::string DBConstant::LOG_POSTFIX = "_log"; const std::string DBConstant::LOG_TABLE_VERSION_1 = "1.0"; const std::string DBConstant::LOG_TABLE_VERSION_2 = "2.0"; const char *LOG_TABLE_VERSION_3 = "3.0"; -const std::string DBConstant::LOG_TABLE_VERSION_CURRENT = "3.0"; +const std::string DBConstant::LOG_TABLE_VERSION_CURRENT = "4.0"; const std::string DBConstant::LOG_TABLE_VERSION_KEY = "log_table_version"; @@ -82,4 +82,4 @@ const std::string DBConstant::REMOTE_DEVICE_SCHEMA_KEY_PREFIX = "remote_device_s const std::string DBConstant::DEVICEID_PREFIX_KEY = "deviceId"; const std::string DBConstant::QUERY_SYNC_PREFIX_KEY = "querySync"; const std::string DBConstant::DELETE_SYNC_PREFIX_KEY = "deleteSync"; -} \ No newline at end of file +} diff --git a/kv_store/frameworks/libs/distributeddb/common/src/performance_analysis.cpp b/kv_store/frameworks/libs/distributeddb/common/src/performance_analysis.cpp index 75e11259..44739c6f 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/performance_analysis.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/performance_analysis.cpp @@ -26,11 +26,12 @@ namespace DistributedDB { const std::string PerformanceAnalysis::STATISTICAL_DATA_FILE_NAME_HEADER = "/data/log/statistic"; const std::string PerformanceAnalysis::CSV_FILE_EXTENSION = ".csv"; const std::string PerformanceAnalysis::DEFAULT_FILE_NAME = "default00"; +std::once_flag PerformanceAnalysis::initFlag_; PerformanceAnalysis *PerformanceAnalysis::GetInstance(int stepNum) { static PerformanceAnalysis inst(stepNum); - inst.Initialization(); + std::call_once(initFlag_, std::bind(&PerformanceAnalysis::Initialization, &inst)); return &inst; } diff --git a/kv_store/frameworks/libs/distributeddb/common/src/relational/table_info.cpp b/kv_store/frameworks/libs/distributeddb/common/src/relational/table_info.cpp index eec56911..639dcea7 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/relational/table_info.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/relational/table_info.cpp @@ -198,6 +198,16 @@ bool FieldInfo::IsAssetsType() const return strcasecmp(dataType_.c_str(), ASSETS) == 0; } +CollateType FieldInfo::GetCollateType() const +{ + return collateType_; +} + +void FieldInfo::SetCollateType(CollateType collateType) +{ + collateType_ = collateType; +} + const std::string &TableInfo::GetTableName() const { return tableName_; diff --git a/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.cpp b/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.cpp index 880edecb..01a7b8fe 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.cpp @@ -138,8 +138,7 @@ bool TaskPoolImpl::IdleExit(std::unique_lock &lock) if (!isGenericWorker && (curThreads_ > minThreads_)) { std::cv_status status = hasTasks_.wait_for(lock, std::chrono::seconds(IDLE_WAIT_PERIOD)); - if (status == std::cv_status::timeout && - genericTaskCount_ <= 0) { + if (status == std::cv_status::timeout && IsNoTaskExecute()) { --idleThreads_; return true; } @@ -292,4 +291,17 @@ void TaskPoolImpl::TryToSpawnThreads() } (void)(SpawnThreads(false)); } + +bool TaskPoolImpl::IsNoTaskExecute() const +{ + if (genericTaskCount_ > 0) { + return false; + } + for (const auto &item: queuedTasks_) { + if (item.second.CanGetTask()) { + return false; + } + } + return true; +} } // namespace DistributedDB diff --git a/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.h b/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.h index ed998892..4342be15 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.h +++ b/kv_store/frameworks/libs/distributeddb/common/src/task_pool_impl.h @@ -61,6 +61,7 @@ private: void TaskWorker(); void FinishExecuteTask(TaskQueue *taskQueue); void TryToSpawnThreads(); + bool IsNoTaskExecute() const; // Member Variables. static constexpr int IDLE_WAIT_PERIOD = 1; // wait 1 second before exiting. diff --git a/kv_store/frameworks/libs/distributeddb/common/src/task_queue.cpp b/kv_store/frameworks/libs/distributeddb/common/src/task_queue.cpp index 764ff4a2..72114e70 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/task_queue.cpp +++ b/kv_store/frameworks/libs/distributeddb/common/src/task_queue.cpp @@ -72,4 +72,14 @@ bool TaskQueue::IsEmptyAndUnlocked() const } return tasks_.empty(); } + +bool TaskQueue::CanGetTask() const +{ + if (lockable_) { + if (lockThread_ != std::thread::id()) { + return false; + } + } + return !tasks_.empty(); +} } // namespace DistributedDB diff --git a/kv_store/frameworks/libs/distributeddb/common/src/task_queue.h b/kv_store/frameworks/libs/distributeddb/common/src/task_queue.h index ea8337b7..7017f196 100644 --- a/kv_store/frameworks/libs/distributeddb/common/src/task_queue.h +++ b/kv_store/frameworks/libs/distributeddb/common/src/task_queue.h @@ -29,7 +29,7 @@ public: Task GetTaskAutoLock(); void ReleaseLock(); bool IsEmptyAndUnlocked() const; - + bool CanGetTask() const; private: bool lockable_; std::thread::id lockThread_; diff --git a/kv_store/frameworks/libs/distributeddb/interfaces/include/relational/relational_store_client.h b/kv_store/frameworks/libs/distributeddb/interfaces/include/relational/relational_store_client.h new file mode 100644 index 00000000..1a545905 --- /dev/null +++ b/kv_store/frameworks/libs/distributeddb/interfaces/include/relational/relational_store_client.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2023 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 RELATIONAL_STORE_CLIENT_H +#define RELATIONAL_STORE_CLIENT_H + +#include +#include +#include + +#include "sqlite3.h" + +#include "store_types.h" + +struct ClientChangedData { + std::string tableName; +}; + +using ClientObserver = std::function; + +DB_API DistributedDB::DBStatus RegisterClientObserver(sqlite3 *db, const ClientObserver &clientObserver); + +DB_API DistributedDB::DBStatus UnRegisterClientObserver(sqlite3 *db); + +#endif // RELATIONAL_STORE_CLIENT_H diff --git a/kv_store/frameworks/libs/distributeddb/interfaces/include/relational/relational_store_manager.h b/kv_store/frameworks/libs/distributeddb/interfaces/include/relational/relational_store_manager.h index 4e683a77..a7daf9b6 100644 --- a/kv_store/frameworks/libs/distributeddb/interfaces/include/relational/relational_store_manager.h +++ b/kv_store/frameworks/libs/distributeddb/interfaces/include/relational/relational_store_manager.h @@ -31,7 +31,8 @@ public: DB_API static std::string GetDistributedLogTableName(const std::string &tableName); // key:colName value:real value - DB_API static std::vector CalcPrimaryKeyHash(const std::map primaryKey); + DB_API static std::vector CalcPrimaryKeyHash(const std::map &primaryKey, + const std::map &collateTypeMap = {}); DB_API RelationalStoreManager(const std::string &appId, const std::string &userId, int32_t instanceId = 0); DB_API ~RelationalStoreManager() = default; @@ -60,4 +61,4 @@ private: int32_t instanceId_; }; } // namespace DistributedDB -#endif // RELATIONAL_STORE_MANAGER_H \ No newline at end of file +#endif // RELATIONAL_STORE_MANAGER_H diff --git a/kv_store/frameworks/libs/distributeddb/interfaces/include/store_types.h b/kv_store/frameworks/libs/distributeddb/interfaces/include/store_types.h index 0e7b9e29..a6ac4bcc 100644 --- a/kv_store/frameworks/libs/distributeddb/interfaces/include/store_types.h +++ b/kv_store/frameworks/libs/distributeddb/interfaces/include/store_types.h @@ -140,6 +140,13 @@ enum ProcessStatus { FINISHED = 2, }; +enum class CollateType : uint32_t { + COLLATE_NONE = 0, + COLLATE_NOCASE, + COLLATE_RTRIM, + COLLATE_BUTT +}; + struct Info { uint32_t batchIndex = 0; uint32_t total = 0; diff --git a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_delegate_impl.h b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_delegate_impl.h index bcd3de63..45c8906b 100644 --- a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_delegate_impl.h +++ b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_delegate_impl.h @@ -36,8 +36,6 @@ public: DBStatus RemoveDeviceDataInner(const std::string &device, ClearMode mode) override; - DBStatus DoClean(ClearMode mode); - DBStatus CreateDistributedTableInner(const std::string &tableName, TableSyncType type) override; DBStatus RemoveDeviceData(const std::string &device, const std::string &tableName) override; diff --git a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_manager.cpp b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_manager.cpp index ab61b004..ef3f600d 100644 --- a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_manager.cpp +++ b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_manager.cpp @@ -147,7 +147,25 @@ DB_API std::string RelationalStoreManager::GetDistributedLogTableName(const std: return DBCommon::GetLogTableName(tableName); } -DB_API std::vector RelationalStoreManager::CalcPrimaryKeyHash(const std::map primaryKey) +int static GetCollateTypeByName(const std::map &collateTypeMap, + const std::string &name, CollateType &collateType) +{ + auto it = collateTypeMap.find(name); + if (it == collateTypeMap.end()) { + LOGW("collate map doesn't contain primary key we need"); + collateType = CollateType::COLLATE_NONE; + return E_OK; + } + if (static_cast(it->second) >= static_cast(CollateType::COLLATE_BUTT)) { + LOGE("collate type is invalid"); + return -E_INVALID_ARGS; + } + collateType = it->second; + return E_OK; +} + +DB_API std::vector RelationalStoreManager::CalcPrimaryKeyHash(const std::map &primaryKey, + const std::map &collateTypeMap) { std::vector result; if (primaryKey.empty()) { @@ -155,20 +173,32 @@ DB_API std::vector RelationalStoreManager::CalcPrimaryKeyHash(const std return result; } int errCode = E_OK; + CollateType collateType = CollateType::COLLATE_NONE; if (primaryKey.size() == 1) { auto iter = primaryKey.begin(); Field field = {iter->first, static_cast(iter->second.index()), true, false}; - errCode = CloudStorageUtils::CalculateHashKeyForOneField(field, primaryKey, false, result); + if (GetCollateTypeByName(collateTypeMap, iter->first, collateType) != E_OK) { + return result; + } + errCode = CloudStorageUtils::CalculateHashKeyForOneField(field, primaryKey, false, collateType, result); if (errCode != E_OK) { // never happen LOGE("calc hash fail when there is one primary key errCode = %d", errCode); } } else { std::vector tempRes; - for (const auto &item : primaryKey) { + std::map pkOrderByUpperName; + for (const auto &item : primaryKey) { // we sort by upper case name in log table when calculate hash + pkOrderByUpperName[DBCommon::ToUpperCase(item.first)] = item.second; + } + + for (const auto &item : pkOrderByUpperName) { std::vector temp; - Field field = {item.first, static_cast(item.second.index()), true, false}; - errCode = CloudStorageUtils::CalculateHashKeyForOneField(field, primaryKey, false, temp); + Field field = {DBCommon::ToLowerCase(item.first), static_cast(item.second.index()), true, false}; + if (GetCollateTypeByName(collateTypeMap, DBCommon::ToLowerCase(item.first), collateType) != E_OK) { + return result; + } + errCode = CloudStorageUtils::CalculateHashKeyForOneField(field, primaryKey, false, collateType, temp); if (errCode != E_OK) { // never happen LOGE("calc hash fail when there is more than one primary key errCode = %d", errCode); @@ -195,4 +225,4 @@ std::string RelationalStoreManager::GetRelationalStoreIdentifier(const std::stri return RuntimeConfig::GetStoreIdentifier(userId, appId, storeId, syncDualTupleMode); } } // namespace DistributedDB -#endif \ No newline at end of file +#endif diff --git a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_sqlite_ext.cpp b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_sqlite_ext.cpp index d338faf3..5bf899b6 100644 --- a/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_sqlite_ext.cpp +++ b/kv_store/frameworks/libs/distributeddb/interfaces/src/relational/relational_store_sqlite_ext.cpp @@ -19,6 +19,8 @@ #include #include +#include "relational_store_client.h" + // using the "sqlite3sym.h" in OHOS #ifndef USE_SQLITE_SYMBOLS #include "sqlite3.h" @@ -193,6 +195,21 @@ struct TransactFunc { void(*xDestroy)(void*) = nullptr; }; +std::mutex g_clientObserverMutex; +std::map g_clientObserverMap; + +void StringToVector(const std::string &src, std::vector &dst) +{ + dst.resize(src.size()); + dst.assign(src.begin(), src.end()); +} + +void VectorToString(const std::vector &src, std::string &dst) +{ + dst.clear(); + dst.assign(src.begin(), src.end()); +} + int RegisterFunction(sqlite3 *db, const std::string &funcName, int nArg, void *uData, TransactFunc &func) { if (db == nullptr) { @@ -223,22 +240,64 @@ int CalcValueHash(const std::vector &value, std::vector &hashV return E_OK; } -void CalcHashKey(sqlite3_context *ctx, int argc, sqlite3_value **argv) +void StringToUpper(std::string &str) { - // 1 means that the function only needs one parameter, namely key - if (ctx == nullptr || argc != 1 || argv == nullptr) { + std::transform(str.cbegin(), str.cend(), str.begin(), [](unsigned char c) { + return std::toupper(c); + }); +} + +void RTrim(std::string &str) +{ + if (str.empty()) { return; } - auto keyBlob = static_cast(sqlite3_value_blob(argv[0])); - if (keyBlob == nullptr) { - sqlite3_result_error(ctx, "Parameters is invalid.", -1); + str.erase(str.find_last_not_of(" ") + 1); +} + +void CalcHashKey(sqlite3_context *ctx, int argc, sqlite3_value **argv) +{ + // 1 means that the function only needs one parameter, namely key + if (ctx == nullptr || argc != 2 || argv == nullptr) { // 2 is params count return; } - int blobLen = sqlite3_value_bytes(argv[0]); - std::vector value(keyBlob, keyBlob + blobLen); + + int errCode; std::vector hashValue; - int errCode = CalcValueHash(value, hashValue); - if (errCode != E_OK) { + DistributedDB::CollateType collateType = static_cast(sqlite3_value_int(argv[1])); + if (collateType == DistributedDB::CollateType::COLLATE_NOCASE) { + auto colChar = reinterpret_cast(sqlite3_value_text(argv[0])); + if (colChar == nullptr) { + return; + } + std::string colStr(colChar); + StringToUpper(colStr); + std::vector value; + StringToVector(colStr, value); + errCode = CalcValueHash(value, hashValue); + } else if (collateType == DistributedDB::CollateType::COLLATE_RTRIM) { + auto colChar = reinterpret_cast(sqlite3_value_text(argv[0])); + if (colChar == nullptr) { + return; + } + std::string colStr(colChar); + RTrim(colStr); + std::vector value; + StringToVector(colStr, value); + errCode = CalcValueHash(value, hashValue); + } else { + auto keyBlob = static_cast(sqlite3_value_blob(argv[0])); + if (keyBlob == nullptr) { + sqlite3_result_error(ctx, "Parameters is invalid.", -1); + return; + } + + int blobLen = sqlite3_value_bytes(argv[0]); + std::vector value(keyBlob, keyBlob + blobLen); + errCode = CalcValueHash(value, hashValue); + } + + if (errCode != DistributedDB::DBStatus::OK) { sqlite3_result_error(ctx, "Get hash value error.", -1); return; } @@ -250,7 +309,7 @@ int RegisterCalcHash(sqlite3 *db) { TransactFunc func; func.xFunc = &CalcHashKey; - return RegisterFunction(db, "calc_hash", 1, nullptr, func); + return RegisterFunction(db, "calc_hash", 2, nullptr, func); // 2 is params count } void GetSysTime(sqlite3_context *ctx, int argc, sqlite3_value **argv) @@ -270,7 +329,7 @@ void GetRawSysTime(sqlite3_context *ctx, int argc, sqlite3_value **argv) uint64_t curTime = 0; int errCode = TimeHelper::GetSysCurrentRawTime(curTime); - if (errCode != E_OK) { + if (errCode != DistributedDB::DBStatus::OK) { sqlite3_result_error(ctx, "get raw sys time failed.", errCode); return; } @@ -286,6 +345,66 @@ void GetLastTime(sqlite3_context *ctx, int argc, sqlite3_value **argv) sqlite3_result_int64(ctx, (sqlite3_int64)TimeHelper::GetTime(0)); } +int GetHashString(const std::string &str, std::string &dst) +{ + std::vector strVec; + StringToVector(str, strVec); + std::vector hashVec; + int errCode = CalcValueHash(strVec, hashVec); + if (errCode != E_OK) { + return errCode; + } + VectorToString(hashVec, dst); + return E_OK; +} + +static bool GetDbFileName(sqlite3 *db, std::string &fileName) +{ + if (db == nullptr) { + return false; + } + + auto dbFilePath = sqlite3_db_filename(db, nullptr); + if (dbFilePath == nullptr) { + return false; + } + fileName = std::string(dbFilePath); + return true; +} + +void CloudDataChangedObserver(sqlite3_context *ctx, int argc, sqlite3_value **argv) +{ + if (ctx == nullptr || argc != 3 || argv == nullptr) { // 3 is param counts + return; + } + sqlite3 *db = static_cast(sqlite3_user_data(ctx)); + std::string fileName; + if (!GetDbFileName(db, fileName)) { + return; + } + + std::string hashFileName; + int errCode = GetHashString(fileName, hashFileName); + if (errCode != DistributedDB::DBStatus::OK) { + return; + } + std::lock_guard lock(g_clientObserverMutex); + auto it = g_clientObserverMap.find(hashFileName); + if (it != g_clientObserverMap.end()) { + auto tableNameChar = reinterpret_cast(sqlite3_value_text(argv[0])); + if (tableNameChar == nullptr) { + return; + } + + if (it->second != nullptr) { + std::string tableName = std::string(tableNameChar); + ClientChangedData clientChangedData { tableName }; + it->second(clientChangedData); + } + } + sqlite3_result_int64(ctx, (sqlite3_int64)1); +} + int RegisterGetSysTime(sqlite3 *db) { TransactFunc func; @@ -307,6 +426,13 @@ int RegisterGetLastTime(sqlite3 *db) return RegisterFunction(db, "get_last_time", 0, nullptr, func); } +int RegisterCloudDataChangeObserver(sqlite3 *db) +{ + TransactFunc func; + func.xFunc = &CloudDataChangedObserver; + return RegisterFunction(db, "client_observer", 3, db, func); // 3 is param counts const_cast(dbFilePath) +} + int ResetStatement(sqlite3_stmt *&stmt) { if (stmt == nullptr || sqlite3_finalize(stmt) != SQLITE_OK) { @@ -439,7 +565,7 @@ int GetTableSyncType(sqlite3 *db, const std::string &tableName, std::string &tab int errCode = sqlite3_prepare_v2(db, selectSql, -1, &statement, nullptr); if (errCode != SQLITE_OK) { (void)sqlite3_finalize(statement); - return -E_ERROR; + return DistributedDB::DBStatus::DB_ERROR; } std::string keyStr = SYNC_TABLE_TYPE + tableName; @@ -451,7 +577,7 @@ int GetTableSyncType(sqlite3 *db, const std::string &tableName, std::string &tab if (sqlite3_step(statement) == SQLITE_ROW) { std::vector value; - if (GetColumnBlobValue(statement, 0, value) == E_OK) { + if (GetColumnBlobValue(statement, 0, value) == DistributedDB::DBStatus::OK) { tableType.assign(value.begin(), value.end()); (void)sqlite3_finalize(statement); return E_OK; @@ -515,7 +641,7 @@ void ClearTheLogAfterDropTable(sqlite3 *db, const char *tableName, const char *s if (isLogTblExists) { std::string tableType = DEVICE_TYPE; - if (GetTableSyncType(db, tableStr, tableType) != E_OK) { + if (GetTableSyncType(db, tableStr, tableType) != DistributedDB::DBStatus::OK) { return; } if (tableType == DEVICE_TYPE) { @@ -539,6 +665,7 @@ void PostHandle(sqlite3 *db) RegisterGetSysTime(db); RegisterGetLastTime(db); RegisterGetRawSysTime(db); + RegisterCloudDataChangeObserver(db); (void)sqlite3_set_droptable_handle(db, &ClearTheLogAfterDropTable); (void)sqlite3_busy_timeout(db, BUSY_TIMEOUT); std::string recursiveTrigger = "PRAGMA recursive_triggers = ON;"; @@ -576,6 +703,43 @@ SQLITE_API int sqlite3_open_v2_relational(const char *filename, sqlite3 **ppDb, return err; } +DB_API DistributedDB::DBStatus RegisterClientObserver(sqlite3 *db, const ClientObserver &clientObserver) +{ + std::string fileName; + if (clientObserver == nullptr || !GetDbFileName(db, fileName)) { + return DistributedDB::INVALID_ARGS; + } + + std::string hashFileName; + int errCode = GetHashString(fileName, hashFileName); + if (errCode != DistributedDB::DBStatus::OK) { + return DistributedDB::DB_ERROR; + } + std::lock_guard lock(g_clientObserverMutex); + g_clientObserverMap[hashFileName] = clientObserver; + return DistributedDB::OK; +} + +DB_API DistributedDB::DBStatus UnRegisterClientObserver(sqlite3 *db) +{ + std::string fileName; + if (!GetDbFileName(db, fileName)) { + return DistributedDB::INVALID_ARGS; + } + + std::string hashFileName; + int errCode = GetHashString(fileName, hashFileName); + if (errCode != DistributedDB::DBStatus::OK) { + return DistributedDB::DB_ERROR; + } + std::lock_guard lock(g_clientObserverMutex); + auto it = g_clientObserverMap.find(hashFileName); + if (it != g_clientObserverMap.end()) { + g_clientObserverMap.erase(it); + } + return DistributedDB::OK; +} + // hw export the symbols #ifdef SQLITE_DISTRIBUTE_RELATIONAL #if defined(__GNUC__) @@ -606,4 +770,4 @@ static const sqlite3_api_routines_relational sqlite3HwApis = { }; EXPORT_SYMBOLS const sqlite3_api_routines_relational *sqlite3_export_relational_symbols = &sqlite3HwApis; -#endif \ No newline at end of file +#endif diff --git a/kv_store/frameworks/libs/distributeddb/storage/include/cloud/cloud_meta_data.h b/kv_store/frameworks/libs/distributeddb/storage/include/cloud/cloud_meta_data.h index 48ae1837..f714b75a 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/include/cloud/cloud_meta_data.h +++ b/kv_store/frameworks/libs/distributeddb/storage/include/cloud/cloud_meta_data.h @@ -38,9 +38,11 @@ public: int SetLocalWaterMark(const TableName &tableName, Timestamp localMark); int SetCloudWaterMark(const TableName &tableName, std::string &cloudMark); + int CleanWaterMark(const TableName &tableName); + private: typedef struct CloudMetaValue { - Timestamp localMark; + Timestamp localMark = 0u; std::string cloudMark; } CloudMetaValue; diff --git a/kv_store/frameworks/libs/distributeddb/storage/include/cloud/cloud_storage_utils.h b/kv_store/frameworks/libs/distributeddb/storage/include/cloud/cloud_storage_utils.h index bc8cf3c4..fc42a284 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/include/cloud/cloud_storage_utils.h +++ b/kv_store/frameworks/libs/distributeddb/storage/include/cloud/cloud_storage_utils.h @@ -34,15 +34,21 @@ public: return (errCode == E_OK || (field.nullable && errCode == -E_NOT_FOUND)); } - static int Int64ToVector(const VBucket &vBucket, const Field &field, std::vector &value); - static int BoolToVector(const VBucket &vBucket, const Field &field, std::vector &value); - static int DoubleToVector(const VBucket &vBucket, const Field &field, std::vector &value); - static int TextToVector(const VBucket &vBucket, const Field &field, std::vector &value); - static int BlobToVector(const VBucket &vBucket, const Field &field, std::vector &value); + static int Int64ToVector(const VBucket &vBucket, const Field &field, CollateType collateType, + std::vector &value); + static int BoolToVector(const VBucket &vBucket, const Field &field, CollateType collateType, + std::vector &value); + static int DoubleToVector(const VBucket &vBucket, const Field &field, CollateType collateType, + std::vector &value); + static int TextToVector(const VBucket &vBucket, const Field &field, CollateType collateType, + std::vector &value); + static int BlobToVector(const VBucket &vBucket, const Field &field, CollateType collateType, + std::vector &value); static std::set GetCloudPrimaryKey(const TableSchema &tableSchema); static std::vector GetCloudPrimaryKeyField(const TableSchema &tableSchema); - static std::map GetCloudPrimaryKeyFieldMap(const TableSchema &tableSchema); + static std::map GetCloudPrimaryKeyFieldMap(const TableSchema &tableSchema, + bool sortByUpper = false); static bool IsContainsPrimaryKey(const TableSchema &tableSchema); static std::vector GetCloudAsset(const TableSchema &tableSchema); static int GetAssetFieldsFromSchema(const TableSchema &tableSchema, VBucket &vBucket, @@ -108,7 +114,7 @@ public: } static int CalculateHashKeyForOneField(const Field &field, const VBucket &vBucket, bool allowEmpty, - std::vector &hashValue); + CollateType collateType, std::vector &hashValue); }; } #endif // CLOUD_STORAGE_UTILS_H diff --git a/kv_store/frameworks/libs/distributeddb/storage/include/storage_proxy.h b/kv_store/frameworks/libs/distributeddb/storage/include/storage_proxy.h index 4027fee8..618a5e82 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/include/storage_proxy.h +++ b/kv_store/frameworks/libs/distributeddb/storage/include/storage_proxy.h @@ -88,6 +88,8 @@ public: std::string GetIdentify() const; + int CleanWaterMark(const TableName &tableName); + protected: void Init(); diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_meta_data.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_meta_data.cpp index decfb300..4e8ea714 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_meta_data.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_meta_data.cpp @@ -164,4 +164,17 @@ int CloudMetaData::DeserializeMark(Value &blobMark, CloudMetaValue &cloudMetaVal } return E_OK; } + +int CloudMetaData::CleanWaterMark(const TableName &tableName) +{ + std::lock_guard lock(cloudMetaMutex_); + std::string cloudWaterMark; + int ret = WriteMarkToMeta(tableName, 0, cloudWaterMark); + if (ret != E_OK) { + return ret; + } + cloudMetaVals_[tableName] = {}; + LOGD("[Meta] clean cloud water mark"); + return E_OK; +} } // namespace DistributedDB \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_storage_utils.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_storage_utils.cpp index 7f030927..d13b1e3b 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_storage_utils.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_storage_utils.cpp @@ -193,8 +193,10 @@ int CloudStorageUtils::BindAsset(int index, const VBucket &vBucket, const Field return errCode; } -int CloudStorageUtils::Int64ToVector(const VBucket &vBucket, const Field &field, std::vector &value) +int CloudStorageUtils::Int64ToVector(const VBucket &vBucket, const Field &field, CollateType collateType, + std::vector &value) { + (void)collateType; int64_t val = 0; if (CloudStorageUtils::GetValueFromVBucket(field.colName, vBucket, val) != E_OK) { return -E_CLOUD_ERROR; @@ -203,8 +205,10 @@ int CloudStorageUtils::Int64ToVector(const VBucket &vBucket, const Field &field, return E_OK; } -int CloudStorageUtils::BoolToVector(const VBucket &vBucket, const Field &field, std::vector &value) +int CloudStorageUtils::BoolToVector(const VBucket &vBucket, const Field &field, CollateType collateType, + std::vector &value) { + (void)collateType; bool val = false; if (CloudStorageUtils::GetValueFromVBucket(field.colName, vBucket, val) != E_OK) { return -E_CLOUD_ERROR; @@ -213,8 +217,10 @@ int CloudStorageUtils::BoolToVector(const VBucket &vBucket, const Field &field, return E_OK; } -int CloudStorageUtils::DoubleToVector(const VBucket &vBucket, const Field &field, std::vector &value) +int CloudStorageUtils::DoubleToVector(const VBucket &vBucket, const Field &field, CollateType collateType, + std::vector &value) { + (void)collateType; double val = 0.0; if (CloudStorageUtils::GetValueFromVBucket(field.colName, vBucket, val) != E_OK) { return -E_CLOUD_ERROR; @@ -225,18 +231,29 @@ int CloudStorageUtils::DoubleToVector(const VBucket &vBucket, const Field &field return E_OK; } -int CloudStorageUtils::TextToVector(const VBucket &vBucket, const Field &field, std::vector &value) +int CloudStorageUtils::TextToVector(const VBucket &vBucket, const Field &field, CollateType collateType, + std::vector &value) { std::string val; if (CloudStorageUtils::GetValueFromVBucket(field.colName, vBucket, val) != E_OK) { return -E_CLOUD_ERROR; } + if (collateType == CollateType::COLLATE_NOCASE) { + for (auto &c : val) { + c = static_cast(std::toupper(c)); + } + } else if (collateType == CollateType::COLLATE_RTRIM) { + DBCommon::RTrim(val); + } + DBCommon::StringToVector(val, value); return E_OK; } -int CloudStorageUtils::BlobToVector(const VBucket &vBucket, const Field &field, std::vector &value) +int CloudStorageUtils::BlobToVector(const VBucket &vBucket, const Field &field, CollateType collateType, + std::vector &value) { + (void)collateType; if (field.type == TYPE_INDEX) { return CloudStorageUtils::GetValueFromVBucket(field.colName, vBucket, value); } else if (field.type == TYPE_INDEX) { @@ -296,12 +313,17 @@ std::vector CloudStorageUtils::GetCloudPrimaryKeyField(const TableSchema return pkVec; } -std::map CloudStorageUtils::GetCloudPrimaryKeyFieldMap(const TableSchema &tableSchema) +std::map CloudStorageUtils::GetCloudPrimaryKeyFieldMap(const TableSchema &tableSchema, + bool sortByUpper) { std::map pkMap; for (const auto &field : tableSchema.fields) { if (field.primary) { - pkMap[field.colName] = field; + if (sortByUpper) { + pkMap[DBCommon::ToUpperCase(field.colName)] = field; + } else { + pkMap[field.colName] = field; + } } } return pkMap; @@ -561,12 +583,13 @@ bool CloudStorageUtils::IsAssets(const Type &type) } int CloudStorageUtils::CalculateHashKeyForOneField(const Field &field, const VBucket &vBucket, bool allowEmpty, - std::vector &hashValue) + CollateType collateType, std::vector &hashValue) { if (allowEmpty && vBucket.find(field.colName) == vBucket.end()) { return E_OK; // if vBucket from cloud doesn't contain primary key and allowEmpty, no need to calculate hash } - static std::map &)>> toVecFunc = { + static std::map &)>> toVecFunc = { { TYPE_INDEX, &CloudStorageUtils::Int64ToVector }, { TYPE_INDEX, &CloudStorageUtils::BoolToVector }, { TYPE_INDEX, &CloudStorageUtils::DoubleToVector }, @@ -581,7 +604,7 @@ int CloudStorageUtils::CalculateHashKeyForOneField(const Field &field, const VBu return -E_CLOUD_ERROR; } std::vector value; - int errCode = it->second(vBucket, field, value); + int errCode = it->second(vBucket, field, collateType, value); if (errCode != E_OK) { LOGE("convert cloud field fail, %d", errCode); return errCode; diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/cloud/schema_mgr.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/cloud/schema_mgr.cpp index 1197b1ab..4f871dd7 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/cloud/schema_mgr.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/cloud/schema_mgr.cpp @@ -135,7 +135,7 @@ bool SchemaMgr::ComparePrimaryField(std::map &localPrimaryKeys, // whether the corresponding field in local schema is primary key bool isLocalFieldPrimary = false; for (const auto &kvPair : localPrimaryKeys) { - if (kvPair.second == cloudField.colName) { + if (DBCommon::CaseInsensitiveCompare(kvPair.second, cloudField.colName)) { isLocalFieldPrimary = true; localPrimaryKeys.erase(kvPair.first); break; @@ -146,7 +146,25 @@ bool SchemaMgr::ComparePrimaryField(std::map &localPrimaryKeys, void SchemaMgr::SetCloudDbSchema(const DataBaseSchema &schema) { - cloudSchema_ = std::make_shared(schema); + DataBaseSchema cloudSchema; + for (const auto &table : schema.tables) { + TableSchema tableSchema; + std::string name(table.name.length(), ' '); + std::transform(table.name.begin(), table.name.end(), name.begin(), tolower); + tableSchema.name = name; + for (const auto &field : table.fields) { + Field tableField; + std::string colName(field.colName.length(), ' '); + std::transform(field.colName.begin(), field.colName.end(), colName.begin(), tolower); + tableField.colName = colName; + tableField.type = field.type; + tableField.primary = field.primary; + tableField.nullable = field.nullable; + tableSchema.fields.emplace_back(tableField); + } + cloudSchema.tables.emplace_back(tableSchema); + } + cloudSchema_ = std::make_shared(cloudSchema); } std::shared_ptr SchemaMgr::GetCloudDbSchema() @@ -160,7 +178,7 @@ int SchemaMgr::GetCloudTableSchema(const TableName &tableName, TableSchema &retS return -E_SCHEMA_MISMATCH; } for (const TableSchema &tableSchema : cloudSchema_->tables) { - if (tableSchema.name == tableName) { + if (DBCommon::CaseInsensitiveCompare(tableSchema.name, tableName)) { retSchema = tableSchema; return E_OK; } diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/relational_sync_able_storage.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/relational_sync_able_storage.cpp index 99cdcd47..4bb00398 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/relational_sync_able_storage.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/relational_sync_able_storage.cpp @@ -694,10 +694,11 @@ void RelationalSyncAbleStorage::TriggerObserverAction(const std::string &deviceN int taskErrCode = RuntimeContext::GetInstance()->ScheduleTask([this, deviceName, changedData, isChangedData] () mutable { std::lock_guard lock(dataChangeDeviceMutex_); - if (!dataChangeCallbackMap_.empty()) { - auto it = dataChangeCallbackMap_.rbegin(); // call the last valid observer - if (it->second != nullptr) { - it->second(deviceName, std::move(changedData), isChangedData); + LOGD("begin to trigger observer, size = %zu(include null observer)", dataChangeCallbackMap_.size()); + for (const auto &item : dataChangeCallbackMap_) { + if (item.second != nullptr) { + ChangedData observerChangeData = changedData; + item.second(deviceName, std::move(observerChangeData), isChangedData); } } DecObjRef(this); @@ -1076,6 +1077,8 @@ int RelationalSyncAbleStorage::GetInfoByPrimaryKeyOrGid(const std::string &table LOGE("Get cloud schema failed when query log for cloud sync, %d", errCode); return errCode; } + RelationalSchemaObject localSchema = GetSchemaInfo(); + transactionHandle_->SetLocalSchema(localSchema); return transactionHandle_->GetInfoByPrimaryKeyOrGid(tableSchema, vBucket, dataInfoWithLog, assetInfo); } @@ -1092,6 +1095,8 @@ int RelationalSyncAbleStorage::PutCloudSyncData(const std::string &tableName, Do LOGE("Get cloud schema failed when save cloud data, %d", errCode); return errCode; } + RelationalSchemaObject localSchema = GetSchemaInfo(); + transactionHandle_->SetLocalSchema(localSchema); return transactionHandle_->PutCloudSyncData(tableName, tableSchema, downloadData); } diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/cloud_sync_log_table_manager.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/cloud_sync_log_table_manager.cpp index 10085da3..fa6eec4e 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/cloud_sync_log_table_manager.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/cloud_sync_log_table_manager.cpp @@ -14,6 +14,7 @@ */ #include "cloud_sync_log_table_manager.h" +#include "db_common.h" namespace DistributedDB { std::string CloudSyncLogTableManager::CalcPrimaryKeyHash(const std::string &references, const TableInfo &table, @@ -21,20 +22,35 @@ std::string CloudSyncLogTableManager::CalcPrimaryKeyHash(const std::string &refe { (void)identity; std::string sql; + FieldInfoMap fieldInfos = table.GetFields(); if (table.GetPrimaryKey().size() == 1) { - sql = "calc_hash(" + references + "'" + table.GetPrimaryKey().at(0) + "')"; + std::string pkName = table.GetPrimaryKey().at(0); + if (pkName == "rowid") { + std::string collateStr = std::to_string(static_cast(CollateType::COLLATE_NONE)); + sql = "calc_hash(" + references + "'" + table.GetPrimaryKey().at(0) + "', " + collateStr + ")"; + } else { + if (fieldInfos.find(pkName) == fieldInfos.end()) { + return sql; + } + std::string collateStr = std::to_string(static_cast(fieldInfos.at(pkName).GetCollateType())); + sql = "calc_hash(" + references + "'" + table.GetPrimaryKey().at(0) + "', " + collateStr + ")"; + } } else { - std::set primaryKeySet; // we need sort primary key by name + std::set primaryKeySet; // we need sort primary key by upper name for (const auto &it : table.GetPrimaryKey()) { - primaryKeySet.emplace(it.second); + primaryKeySet.emplace(DBCommon::ToUpperCase(it.second)); } sql = "calc_hash("; for (const auto &it : primaryKeySet) { - sql += "calc_hash(" + references + "'" + it + "')||"; + if (fieldInfos.find(it) == fieldInfos.end()) { + return sql; + } + std::string collateStr = std::to_string(static_cast(fieldInfos.at(it).GetCollateType())); + sql += "calc_hash(" + references + "'" + it + "', " + collateStr + ")||"; } sql.pop_back(); sql.pop_back(); - sql += ")"; + sql += ", 0)"; } return sql; } @@ -60,9 +76,10 @@ std::string CloudSyncLogTableManager::GetPrimaryKeySql(const TableInfo &table) std::string CloudSyncLogTableManager::GetInsertTrigger(const TableInfo &table, const std::string &identity) { std::string logTblName = GetLogTableName(table); + std::string tableName = table.GetTableName(); std::string insertTrigger = "CREATE TRIGGER IF NOT EXISTS "; - insertTrigger += "naturalbase_rdb_" + table.GetTableName() + "_ON_INSERT AFTER INSERT \n"; - insertTrigger += "ON '" + table.GetTableName() + "'\n"; + insertTrigger += "naturalbase_rdb_" + tableName + "_ON_INSERT AFTER INSERT \n"; + insertTrigger += "ON '" + tableName + "'\n"; insertTrigger += "WHEN (SELECT count(*) from " + DBConstant::RELATIONAL_PREFIX + "metadata "; insertTrigger += "WHERE key = 'log_trigger_switch' AND value = 'true')\n"; insertTrigger += "BEGIN\n"; @@ -74,6 +91,7 @@ std::string CloudSyncLogTableManager::GetInsertTrigger(const TableInfo &table, c insertTrigger += logTblName + " where hash_key = " + CalcPrimaryKeyHash("NEW.", table, identity); insertTrigger += ") THEN (select cloud_gid from " + logTblName + " where hash_key = "; insertTrigger += CalcPrimaryKeyHash("NEW.", table, identity) + ") ELSE '' END);\n"; + insertTrigger += "select client_observer('" + tableName + "', NEW.rowid, 0);\n"; insertTrigger += "END;"; return insertTrigger; } @@ -82,15 +100,17 @@ std::string CloudSyncLogTableManager::GetUpdateTrigger(const TableInfo &table, c { (void)identity; std::string logTblName = GetLogTableName(table); + std::string tableName = table.GetTableName(); std::string updateTrigger = "CREATE TRIGGER IF NOT EXISTS "; - updateTrigger += "naturalbase_rdb_" + table.GetTableName() + "_ON_UPDATE AFTER UPDATE \n"; - updateTrigger += "ON '" + table.GetTableName() + "'\n"; + updateTrigger += "naturalbase_rdb_" + tableName + "_ON_UPDATE AFTER UPDATE \n"; + updateTrigger += "ON '" + tableName + "'\n"; updateTrigger += "WHEN (SELECT count(*) from " + DBConstant::RELATIONAL_PREFIX + "metadata "; updateTrigger += "WHERE key = 'log_trigger_switch' AND value = 'true')\n"; updateTrigger += "BEGIN\n"; // if user change the primary key, we can still use gid to identify which one is updated updateTrigger += "\t UPDATE " + logTblName; updateTrigger += " SET timestamp=get_raw_sys_time(), device='', flag=0x02"; updateTrigger += " WHERE data_key = OLD.rowid;\n"; + updateTrigger += "select client_observer('" + tableName + "', OLD.rowid, 1);\n"; updateTrigger += "END;"; return updateTrigger; } @@ -98,15 +118,18 @@ std::string CloudSyncLogTableManager::GetUpdateTrigger(const TableInfo &table, c std::string CloudSyncLogTableManager::GetDeleteTrigger(const TableInfo &table, const std::string &identity) { (void)identity; + std::string tableName = table.GetTableName(); std::string deleteTrigger = "CREATE TRIGGER IF NOT EXISTS "; - deleteTrigger += "naturalbase_rdb_" + table.GetTableName() + "_ON_DELETE BEFORE DELETE \n"; - deleteTrigger += "ON '" + table.GetTableName() + "'\n"; + deleteTrigger += "naturalbase_rdb_" + tableName + "_ON_DELETE BEFORE DELETE \n"; + deleteTrigger += "ON '" + tableName + "'\n"; deleteTrigger += "WHEN (SELECT count(*) from " + DBConstant::RELATIONAL_PREFIX + "metadata "; deleteTrigger += "WHERE key = 'log_trigger_switch' AND VALUE = 'true')\n"; deleteTrigger += "BEGIN\n"; deleteTrigger += "\t UPDATE " + GetLogTableName(table); deleteTrigger += " SET data_key=-1,flag=0x03,timestamp=get_raw_sys_time()"; deleteTrigger += " WHERE data_key = OLD.rowid;"; + // -1 is rowid when data is deleted, 2 means change type is delete(ClientChangeType) + deleteTrigger += "select client_observer('" + tableName + "', -1, 2);\n"; deleteTrigger += "END;"; return deleteTrigger; } diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/collaboration_log_table_manager.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/collaboration_log_table_manager.cpp index 6a2be816..26468e70 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/collaboration_log_table_manager.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/collaboration_log_table_manager.cpp @@ -27,18 +27,18 @@ std::string CollaborationLogTableManager::CalcPrimaryKeyHash(const std::string & { std::string sql; if (IsCollaborationWithoutKey(table)) { - sql = "calc_hash('" + identity + "'||calc_hash(" + references + "rowid))"; + sql = "calc_hash('" + identity + "'||calc_hash(" + references + "rowid, 0), 0)"; } else { if (table.GetIdentifyKey().size() == 1) { - sql = "calc_hash(" + references + "'" + table.GetIdentifyKey().at(0) + "')"; + sql = "calc_hash(" + references + "'" + table.GetIdentifyKey().at(0) + "', 0)"; } else { sql = "calc_hash("; for (const auto &it : table.GetIdentifyKey()) { - sql += "calc_hash(" + references + "'" + it + "')||"; + sql += "calc_hash(" + references + "'" + it + "', 0)||"; } sql.pop_back(); sql.pop_back(); - sql += ")"; + sql += ", 0)"; } } return sql; diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_database_upgrader.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_database_upgrader.cpp index 24c9facb..87c7f2e3 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_database_upgrader.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_relational_database_upgrader.cpp @@ -111,7 +111,11 @@ int SqliteRelationalDatabaseUpgrader::UpgradeTrigger(const std::string &logTable DistributedTableMode mode = schemaObject.GetTableMode(); for (const auto &[tableName, tableInfo] : schemaObject.GetTables()) { std::string dropTriggerSql = "DROP TRIGGER IF EXISTS " + DBConstant::SYSTEM_TABLE_PREFIX + tableName + - "_ON_UPDATE"; + "_ON_UPDATE;"; + dropTriggerSql += "DROP TRIGGER IF EXISTS " + DBConstant::SYSTEM_TABLE_PREFIX + tableName + + "_ON_INSERT;"; + dropTriggerSql += "DROP TRIGGER IF EXISTS " + DBConstant::SYSTEM_TABLE_PREFIX + tableName + + "_ON_DELETE;"; errCode = SQLiteUtils::ExecuteRawSQL(db_, dropTriggerSql); if (errCode != E_OK) { LOGE("[Relational][Upgrade] drop trigger failed.", errCode); @@ -165,4 +169,4 @@ int SqliteRelationalDatabaseUpgrader::UpgradeLogTable(const std::string &logTabl } return E_OK; } -} // namespace DistributedDB \ No newline at end of file +} // namespace DistributedDB diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp index 341f258e..e48cad43 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/relational/sqlite_single_relational_storage_engine.cpp @@ -73,6 +73,12 @@ int SQLiteSingleRelationalStorageEngine::RegisterFunction(sqlite3 *db) const errCode = SQLiteUtils::RegisterGetRawSysTime(db); if (errCode != E_OK) { LOGE("[engine] register get raw sys time failed!"); + return errCode; + } + + errCode = SQLiteUtils::RegisterCloudDataChangeObserver(db); + if (errCode != E_OK) { + LOGE("[engine] register cloud observer failed!"); } return errCode; diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/split_device_log_table_manager.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/split_device_log_table_manager.cpp index cba29fb6..e3176bd2 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/split_device_log_table_manager.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/split_device_log_table_manager.cpp @@ -22,15 +22,15 @@ std::string SplitDeviceLogTableManager::CalcPrimaryKeyHash(const std::string &re (void)identity; std::string sql; if (table.GetPrimaryKey().size() == 1) { - sql = "calc_hash(" + references + "'" + table.GetPrimaryKey().at(0) + "')"; + sql = "calc_hash(" + references + "'" + table.GetPrimaryKey().at(0) + "', 0)"; } else { sql = "calc_hash("; for (const auto &it : table.GetPrimaryKey()) { - sql += "calc_hash(" + references + "'" + it.second + "')||"; + sql += "calc_hash(" + references + "'" + it.second + "', 0)||"; } sql.pop_back(); sql.pop_back(); - sql += ")"; + sql += ", 0)"; } return sql; } diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.cpp index fe7ee9f5..9e7ef8f0 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_natural_store.cpp @@ -275,7 +275,7 @@ int SQLiteSingleVerNaturalStore::GetSecurityOption(SecurityOption &option) const if (isMemDb) { LOGI("[GetSecurityOption] MemDb, no need to get security option"); option = SecurityOption(); - return E_OK; + return -E_NOT_SUPPORT; } option.securityLabel = GetDbProperties().GetSecLabel(); diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.cpp index 3ae06554..facf9120 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_executor.cpp @@ -1664,6 +1664,11 @@ int SQLiteSingleVerRelationalStorageExecutor::PutVBucketByType(VBucket &vBucket, return E_OK; } +void SQLiteSingleVerRelationalStorageExecutor::SetLocalSchema(const RelationalSchemaObject &localSchema) +{ + localSchema_ = localSchema; +} + int SQLiteSingleVerRelationalStorageExecutor::GetInfoByPrimaryKeyOrGid(const TableSchema &tableSchema, const VBucket &vBucket, DataInfoWithLog &dataInfoWithLog, VBucket &assetInfo) { @@ -1787,7 +1792,14 @@ int SQLiteSingleVerRelationalStorageExecutor::GetPrimaryKeyHashValue(const VBuck const TableSchema &tableSchema, std::vector &hashValue, bool allowEmpty) { int errCode = E_OK; - std::map pkMap = CloudStorageUtils::GetCloudPrimaryKeyFieldMap(tableSchema); + TableInfo localTable = localSchema_.GetTable(tableSchema.name); + // table name in cloud schema is in lower case + if (DBCommon::ToLowerCase(localTable.GetTableName()) != tableSchema.name) { + LOGE("localSchema doesn't contain table from cloud"); + return -E_INTERNAL_ERROR; + } + + std::map pkMap = CloudStorageUtils::GetCloudPrimaryKeyFieldMap(tableSchema, true); if (pkMap.size() == 0) { int64_t rowid = SQLiteUtils::GetLastRowId(dbHandle_); std::vector value; @@ -1795,12 +1807,26 @@ int SQLiteSingleVerRelationalStorageExecutor::GetPrimaryKeyHashValue(const VBuck errCode = DBCommon::CalcValueHash(value, hashValue); } else if (pkMap.size() == 1) { std::vector pkVec = CloudStorageUtils::GetCloudPrimaryKeyField(tableSchema); - errCode = CloudStorageUtils::CalculateHashKeyForOneField(pkVec.at(0), vBucket, allowEmpty, hashValue); + FieldInfoMap fieldInfos = localTable.GetFields(); + if (fieldInfos.find(pkMap.begin()->first) == fieldInfos.end()) { + LOGE("localSchema doesn't contain primary key."); + return -E_INTERNAL_ERROR; + } + CollateType collateType = fieldInfos.at(pkMap.begin()->first).GetCollateType(); + errCode = CloudStorageUtils::CalculateHashKeyForOneField( + pkVec.at(0), vBucket, allowEmpty, collateType, hashValue); } else { std::vector tempRes; for (const auto &item: pkMap) { + FieldInfoMap fieldInfos = localTable.GetFields(); + if (fieldInfos.find(item.first) == fieldInfos.end()) { + LOGE("localSchema doesn't contain primary key in multi pks."); + return -E_INTERNAL_ERROR; + } std::vector temp; - errCode = CloudStorageUtils::CalculateHashKeyForOneField(item.second, vBucket, allowEmpty, temp); + CollateType collateType = fieldInfos.at(item.first).GetCollateType(); + errCode = CloudStorageUtils::CalculateHashKeyForOneField( + item.second, vBucket, allowEmpty, collateType, temp); if (errCode != E_OK) { LOGE("calc hash fail when there is more than one primary key. errCode = %d", errCode); return errCode; @@ -1975,9 +2001,8 @@ int SQLiteSingleVerRelationalStorageExecutor::DoCleanLogs(const std::vector(1)); +} + int SQLiteUtils::RegisterGetSysTime(sqlite3 *db) { TransactFunc func; @@ -1404,6 +1425,13 @@ int SQLiteUtils::RegisterGetRawSysTime(sqlite3 *db) return SQLiteUtils::RegisterFunction(db, "get_raw_sys_time", 0, nullptr, func); } +int SQLiteUtils::RegisterCloudDataChangeObserver(sqlite3 *db) +{ + TransactFunc func; + func.xFunc = &CloudDataChangedObserver; + return RegisterFunction(db, "client_observer", 3, db, func); // 3 is param counts +} + int SQLiteUtils::CreateSameStuTable(sqlite3 *db, const TableInfo &baseTbl, const std::string &newTableName) { std::string sql = "CREATE TABLE IF NOT EXISTS '" + newTableName + "' ("; @@ -1936,13 +1964,8 @@ void SQLiteUtils::ExtractReturn(sqlite3_context *ctx, FieldType type, const Fiel return; } -void SQLiteUtils::CalcHashKey(sqlite3_context *ctx, int argc, sqlite3_value **argv) +static void CalcHashFunc(sqlite3_context *ctx, sqlite3_value **argv) { - // 1 means that the function only needs one parameter, namely key - if (ctx == nullptr || argc != 1 || argv == nullptr) { - LOGE("Parameter does not meet restrictions."); - return; - } auto keyBlob = static_cast(sqlite3_value_blob(argv[0])); if (keyBlob == nullptr) { sqlite3_result_error(ctx, "Parameters is invalid.", USING_STR_LEN); @@ -1959,9 +1982,28 @@ void SQLiteUtils::CalcHashKey(sqlite3_context *ctx, int argc, sqlite3_value **ar return; } sqlite3_result_blob(ctx, hashValue.data(), hashValue.size(), SQLITE_TRANSIENT); - return; } +void SQLiteUtils::CalcHashKey(sqlite3_context *ctx, int argc, sqlite3_value **argv) +{ + // 1 means that the function only needs one parameter, namely key + if (ctx == nullptr || argc != 1 || argv == nullptr) { + LOGE("Parameter does not meet restrictions."); + return; + } + CalcHashFunc(ctx, argv); +} + +void SQLiteUtils::CalcHash(sqlite3_context *ctx, int argc, sqlite3_value **argv) +{ + if (ctx == nullptr || argc != 2 || argv == nullptr) { // 2 is params count + LOGE("Parameter does not meet restrictions."); + return; + } + CalcHashFunc(ctx, argv); +} + + int SQLiteUtils::GetDbSize(const std::string &dir, const std::string &dbName, uint64_t &size) { std::string dataDir = dir + "/" + dbName + DBConstant::SQLITE_DB_EXTENSION; @@ -2298,4 +2340,4 @@ END: SQLiteUtils::ResetStatement(stmt, true, errCode); return errCode; } -} // namespace DistributedDB \ No newline at end of file +} // namespace DistributedDB diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_utils.h b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_utils.h index 3d8bb3dc..f268a465 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_utils.h +++ b/kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_utils.h @@ -166,6 +166,8 @@ public: static int RegisterGetRawSysTime(sqlite3 *db); + static int RegisterCloudDataChangeObserver(sqlite3 *db); + static int CreateRelationalLogTable(sqlite3 *db, const std::string &oriTableName); static int AddRelationalLogTableTrigger(sqlite3 *db, const std::string &identity, const TableInfo &table); @@ -221,10 +223,12 @@ private: static void ExtractReturn(sqlite3_context *ctx, FieldType type, const FieldValue &value); static void CalcHashKey(sqlite3_context *ctx, int argc, sqlite3_value **argv); + static void CalcHash(sqlite3_context *ctx, int argc, sqlite3_value **argv); static void GetSysTime(sqlite3_context *ctx, int argc, sqlite3_value **argv); static void GetLastTime(sqlite3_context *ctx, int argc, sqlite3_value **argv); static void GetRawSysTime(sqlite3_context *ctx, int argc, sqlite3_value **argv); + static void CloudDataChangedObserver(sqlite3_context *ctx, int argc, sqlite3_value **argv); static int SetDataBaseProperty(sqlite3 *db, const OpenDbProperties &properties, bool setWal, const std::vector &sqls); diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/storage_engine.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/storage_engine.cpp index 833be3c1..ecd52dad 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/storage_engine.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/storage_engine.cpp @@ -220,6 +220,7 @@ void StorageEngine::Recycle(StorageExecutor *&handle) if (iter != writeUsingList_.end()) { writeUsingList_.remove(handle); if (writeIdleList_.size() >= 1) { + LOGD("[Recycle] delete handle"); delete handle; handle = nullptr; return; @@ -390,6 +391,7 @@ void StorageEngine::CloseExecutor() std::lock_guard lock(writeMutex_); for (auto &item : writeIdleList_) { if (item != nullptr) { + LOGD("[CloseExecutor] delete item"); delete item; item = nullptr; } diff --git a/kv_store/frameworks/libs/distributeddb/storage/src/storage_proxy.cpp b/kv_store/frameworks/libs/distributeddb/storage/src/storage_proxy.cpp index 0f61210d..55f8f506 100644 --- a/kv_store/frameworks/libs/distributeddb/storage/src/storage_proxy.cpp +++ b/kv_store/frameworks/libs/distributeddb/storage/src/storage_proxy.cpp @@ -365,4 +365,14 @@ Timestamp StorageProxy::EraseNanoTime(DistributedDB::Timestamp localTime) { return localTime / CloudDbConstant::TEN_THOUSAND * CloudDbConstant::TEN_THOUSAND; } + +int StorageProxy::CleanWaterMark(const DistributedDB::TableName &tableName) +{ + std::shared_lock readLock(storeMutex_); + if (cloudMetaData_ == nullptr) { + LOGW("[StorageProxy] meta is nullptr return default"); + return -E_INVALID_DB; + } + return cloudMetaData_->CleanWaterMark(tableName); +} } diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_pull_strategy.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_pull_strategy.cpp index bbbce725..6e3b8f4c 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_pull_strategy.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_pull_strategy.cpp @@ -16,17 +16,15 @@ namespace DistributedDB { -OpType CloudForcePullStrategy::TagSyncDataStatus(bool existInLocal, LogInfo &localInfo, LogInfo &cloudInfo, - std::set &deletePrimaryKeySet) +OpType CloudForcePullStrategy::TagSyncDataStatus(bool existInLocal, LogInfo &localInfo, LogInfo &cloudInfo) { if (existInLocal) { if (!IsDelete(localInfo) && IsDelete(cloudInfo)) { - (void)deletePrimaryKeySet.insert(localInfo.hashKey); return OpType::DELETE; } else if (IsDelete(cloudInfo)) { return OpType::UPDATE_TIMESTAMP; } - if (IsDelete(localInfo) || deletePrimaryKeySet.find(localInfo.hashKey) != deletePrimaryKeySet.end()) { + if (IsDelete(localInfo)) { return OpType::INSERT; } return OpType::UPDATE; diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_pull_strategy.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_pull_strategy.h index 50cc9676..79db2efd 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_pull_strategy.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_pull_strategy.h @@ -19,8 +19,7 @@ namespace DistributedDB { class CloudForcePullStrategy : public CloudSyncStrategy { public: - OpType TagSyncDataStatus(bool existInLocal, LogInfo &localInfo, LogInfo &cloudInfo, - std::set &deletePrimaryKeySet) override; + OpType TagSyncDataStatus(bool existInLocal, LogInfo &localInfo, LogInfo &cloudInfo) override; bool JudgeUpdateCursor() override; diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_push_strategy.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_push_strategy.cpp index 82e57928..ed2f8e4e 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_push_strategy.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_push_strategy.cpp @@ -16,10 +16,8 @@ namespace DistributedDB { const std::string cloud_device_name = "cloud"; -OpType CloudForcePushStrategy::TagSyncDataStatus(bool existInLocal, LogInfo &localInfo, LogInfo &cloudInfo, - std::set &deletePrimaryKeySet) +OpType CloudForcePushStrategy::TagSyncDataStatus(bool existInLocal, LogInfo &localInfo, LogInfo &cloudInfo) { - (void)deletePrimaryKeySet; bool isCloudDelete = IsDelete(cloudInfo); if (!existInLocal) { return OpType::NOT_HANDLE; diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_push_strategy.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_push_strategy.h index dfcd5c32..b7616e67 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_push_strategy.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_push_strategy.h @@ -19,8 +19,7 @@ namespace DistributedDB { class CloudForcePushStrategy : public CloudSyncStrategy { public: - OpType TagSyncDataStatus(bool existInLocal, LogInfo &localInfo, LogInfo &cloudInfo, - std::set &deletePrimaryKeySet) override; + OpType TagSyncDataStatus(bool existInLocal, LogInfo &localInfo, LogInfo &cloudInfo) override; bool JudgeUpdateCursor() override; diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_merge_strategy.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_merge_strategy.cpp index 0d401313..00d6fccd 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_merge_strategy.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_merge_strategy.cpp @@ -16,8 +16,7 @@ namespace DistributedDB { -OpType CloudMergeStrategy::TagSyncDataStatus(bool existInLocal, LogInfo &localInfo, LogInfo &cloudInfo, - std::set &deletePrimaryKeySet) +OpType CloudMergeStrategy::TagSyncDataStatus(bool existInLocal, LogInfo &localInfo, LogInfo &cloudInfo) { bool isCloudDelete = IsDelete(cloudInfo); bool isLocalDelete = IsDelete(localInfo); @@ -41,11 +40,10 @@ OpType CloudMergeStrategy::TagSyncDataStatus(bool existInLocal, LogInfo &localIn if (isLocalDelete) { return OpType::UPDATE_TIMESTAMP; } else { - (void)deletePrimaryKeySet.insert(localInfo.hashKey); return OpType::DELETE; } } else { - if (isLocalDelete || deletePrimaryKeySet.find(localInfo.hashKey) != deletePrimaryKeySet.end()) { + if (isLocalDelete) { type = OpType::INSERT; } else { type = OpType::UPDATE; diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_merge_strategy.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_merge_strategy.h index 7724c173..2f07eb5b 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_merge_strategy.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_merge_strategy.h @@ -23,8 +23,7 @@ public: CloudMergeStrategy() = default; ~CloudMergeStrategy() override = default; - OpType TagSyncDataStatus(bool existInLocal, LogInfo &localInfo, LogInfo &cloudInfo, - std::set &deletePrimaryKeySet) override; + OpType TagSyncDataStatus(bool existInLocal, LogInfo &localInfo, LogInfo &cloudInfo) override; bool JudgeUpdateCursor() override; diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_strategy.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_strategy.h index 0c6d5492..2d0fd48b 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_strategy.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_strategy.h @@ -27,13 +27,11 @@ public: CloudSyncStrategy() = default; virtual ~CloudSyncStrategy() = default; - virtual OpType TagSyncDataStatus(bool existInLocal, LogInfo &localInfo, LogInfo &cloudInfo, - std::set &deletePrimaryKeySet) + virtual OpType TagSyncDataStatus(bool existInLocal, LogInfo &localInfo, LogInfo &cloudInfo) { (void)existInLocal; (void)localInfo; (void)cloudInfo; - (void)deletePrimaryKeySet; return OpType::NOT_HANDLE; } diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_utils.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_utils.h index b8583a11..a601cc58 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_utils.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_utils.h @@ -20,6 +20,14 @@ #include "icloud_sync_storage_interface.h" namespace DistributedDB { + +constexpr int GID_INDEX = 0; +constexpr int PREFIX_INDEX = 1; +constexpr int STRATEGY_INDEX = 2; +constexpr int ASSETS_INDEX = 3; +constexpr int HASH_KEY_INDEX = 4; +constexpr int PRIMARY_KEY_INDEX = 5; + int GetCloudPkVals(const VBucket &datum, const std::vector &pkColNames, int64_t dataKey, std::vector &cloudPkVals); diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.cpp index 1a7fda6e..6372294c 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.cpp @@ -301,8 +301,7 @@ void CloudSyncer::DoFinished(TaskId taskId, int errCode, const InnerProcessInfo currentContext_.notifier = nullptr; currentContext_.strategy = nullptr; currentContext_.tableName.clear(); - currentContext_.assetDownloadList.completeDownloadList.clear(); - currentContext_.assetDownloadList.downloadList.clear(); + currentContext_.assetDownloadList.clear(); currentContext_.assetFields.clear(); currentContext_.assetsInfo.clear(); currentContext_.cloudWaterMarks.clear(); @@ -426,7 +425,7 @@ static LogInfo GetCloudLogInfo(VBucket &datum) /** * UpdateChangedData will be used for Insert case, which we can only get rowid after we saved data in db. */ -int CloudSyncer::UpdateChangedData(SyncParam ¶m, AssetDownloadList &assetsDownloadList) +int CloudSyncer::UpdateChangedData(SyncParam ¶m, DownloadList &assetsDownloadList) { if (param.withoutRowIdData.insertData.empty() && param.withoutRowIdData.updateData.empty()) { return E_OK; @@ -447,7 +446,7 @@ int CloudSyncer::UpdateChangedData(SyncParam ¶m, AssetDownloadList &assetsDo size_t downloadIndex = std::get<0>(tuple); VBucket &datum = param.downloadData.data[downloadIndex]; size_t insertIdx = std::get<1>(tuple); - std::vector &pkVal = std::get<5>(assetsDownloadList.downloadList[insertIdx]); // 5 means primary key list + std::vector &pkVal = std::get<5>(assetsDownloadList[insertIdx]); // 5 means primary key list pkVal[0] = datum[CloudDbConstant::ROW_ID_FIELD_NAME]; } for (const auto &tuple : param.withoutRowIdData.updateData) { @@ -617,7 +616,7 @@ int CloudSyncer::HandleDownloadResult(const std::string &tableName, DownloadComm return errCode; } -int CloudSyncer::CloudDbDownloadAssets(InnerProcessInfo &info, const DownloadList &downloadList, bool willHandleResult, +int CloudSyncer::CloudDbDownloadAssets(InnerProcessInfo &info, const DownloadList &downloadList, const std::set &dupHashKeySet, ChangedData &changedAssets) { int downloadStatus = E_OK; @@ -636,13 +635,19 @@ int CloudSyncer::CloudDbDownloadAssets(InnerProcessInfo &info, const DownloadLis info.downLoadInfo.successCount -= (downloadList.size() - i); return -E_NOT_SET; } + if (errorCode != E_OK) { + info.downLoadInfo.failCount += 1; + info.downLoadInfo.successCount -= 1; + } if (dupHashKeySet.find(downloadItem.hashKey) == dupHashKeySet.end()) { changedAssets.primaryData[OpTypeToChangeType(downloadItem.strategy)].push_back( downloadItem.primaryKeyValList); } else if (downloadItem.strategy == OpType::INSERT) { changedAssets.primaryData[ChangeType::OP_UPDATE].push_back(downloadItem.primaryKeyValList); } - if (!willHandleResult) { + + // If the assets are DELETE, needn't fill back cloud assets. + if (downloadItem.strategy == OpType::DELETE) { continue; } CloudStorageUtils::MergeDownloadAsset(downloadAssets, downloadItem.assets); @@ -656,11 +661,9 @@ int CloudSyncer::CloudDbDownloadAssets(InnerProcessInfo &info, const DownloadLis } } } - if (!commitList.empty()) { - int ret = CommitDownloadResult(info, commitList); - if (ret != E_OK) { - return ret; - } + int ret = CommitDownloadResult(info, commitList); + if (ret != E_OK) { + return ret; } LOGD("Download status is %d", downloadStatus); return downloadStatus; @@ -668,13 +671,12 @@ int CloudSyncer::CloudDbDownloadAssets(InnerProcessInfo &info, const DownloadLis void CloudSyncer::GetDownloadItem(const DownloadList &downloadList, size_t i, DownloadItem &downloadItem) { - downloadItem.gid = std::get<0>(downloadList[i]); // 0 means gid is the first element in assetsInfo - downloadItem.prefix = std::get<1>(downloadList[i]); // 1 means primaryKey is the second element in assetsInfo - downloadItem.strategy = std::get<2>(downloadList[i]); // 2 means strategy is the third element in assetsInfo - // 3 means assets info [colName, assets] is the forth element in downloadList[i] - downloadItem.assets = std::get<3>(downloadList[i]); - downloadItem.hashKey = std::get<4>(downloadList[i]); // 4 means hash key - downloadItem.primaryKeyValList = std::get<5>(downloadList[i]); // 5 means primary key value list + downloadItem.gid = std::get(downloadList[i]); + downloadItem.prefix = std::get(downloadList[i]); + downloadItem.strategy = std::get(downloadList[i]); + downloadItem.assets = std::get(downloadList[i]); + downloadItem.hashKey = std::get(downloadList[i]); + downloadItem.primaryKeyValList = std::get(downloadList[i]); } int CloudSyncer::DownloadAssets(InnerProcessInfo &info, const std::vector &pKColNames, @@ -691,25 +693,19 @@ int CloudSyncer::DownloadAssets(InnerProcessInfo &info, const std::vector autoLock(contextLock_); - downloadList = currentContext_.assetDownloadList.downloadList; - completeDeletedList = currentContext_.assetDownloadList.completeDownloadList; + changeList = currentContext_.assetDownloadList; } // Download data (include deleting) will handle return Code in this situation - int ret = CloudDbDownloadAssets(info, downloadList, true, dupHashKeySet, changedAssets); + int ret = CloudDbDownloadAssets(info, changeList, dupHashKeySet, changedAssets); if (ret != E_OK) { LOGE("[CloudSyncer] Can not download assets or can not handle download result %d", ret); return ret; } - // Download data (include deleting), won't handle return Code in this situation - ret = CloudDbDownloadAssets(info, completeDeletedList, false, dupHashKeySet, changedAssets); - if (ret != E_OK) { - LOGE("[CloudSyncer] Can not download assets or can not handle download result for deleted record %d", ret); - } return ret; } @@ -809,32 +805,49 @@ int CloudSyncer::HandleTagAssets(const Key &hashKey, size_t idx, SyncParam ¶ LOGE("[CloudSyncer] TagAssetsInSingleRecord report ERROR"); return ret; } - if (isDelStrategy) { - param.assetsDownloadList.completeDownloadList.push_back( - std::make_tuple(dataInfo.cloudLogInfo.cloudGid, prefix, strategy, assetsMap, hashKey, pkVals)); - } else { - if (!param.isSinglePrimaryKey && strategy == OpType::INSERT) { - param.withoutRowIdData.assetInsertData.push_back(std::make_tuple(idx, - param.assetsDownloadList.downloadList.size())); - } - param.assetsDownloadList.downloadList.push_back( - std::make_tuple(dataInfo.cloudLogInfo.cloudGid, prefix, strategy, assetsMap, hashKey, pkVals)); + + if (!param.isSinglePrimaryKey && strategy == OpType::INSERT) { + param.withoutRowIdData.assetInsertData.push_back(std::make_tuple(idx, param.assetsDownloadList.size())); } + param.assetsDownloadList.push_back( + std::make_tuple(dataInfo.cloudLogInfo.cloudGid, prefix, strategy, assetsMap, hashKey, pkVals)); return ret; } -int CloudSyncer::SaveDatum(SyncParam ¶m, size_t idx, std::vector> &deletedList) +void CloudSyncer::ModifyFieldNameToLower(VBucket &data) +{ + for (auto it = data.begin(); it != data.end();) { + if (it->first == CloudDbConstant::GID_FIELD || it->first == CloudDbConstant::CREATE_FIELD || + it->first == CloudDbConstant::MODIFY_FIELD || it->first == CloudDbConstant::DELETE_FIELD || + it->first == CloudDbConstant::CURSOR_FIELD) { + it++; + continue; + } + std::string lowerField(it->first.length(), ' '); + std::transform(it->first.begin(), it->first.end(), lowerField.begin(), tolower); + if (lowerField != it->first) { + data[lowerField] = std::move(data[it->first]); + data.erase(it++); + } else { + it++; + } + } +} + +int CloudSyncer::SaveDatum(SyncParam ¶m, size_t idx, std::vector> &deletedList, + std::map &localLogInfoCache) { int ret = PreHandleData(param.downloadData.data[idx], param.pkColNames); if (ret != E_OK) { LOGE("[CloudSyncer] Invalid download data:%d", ret); return ret; } + ModifyFieldNameToLower(param.downloadData.data[idx]); ModifyCloudDataTime(param.downloadData.data[idx]); DataInfo dataInfo; VBucket localAssetInfo; bool isExist = true; - ret = storageProxy_->GetInfoByPrimaryKeyOrGid(param.tableName, param.downloadData.data[idx], dataInfo.localInfo, + ret = GetLocalInfo(param.tableName, param.downloadData.data[idx], dataInfo.localInfo, localLogInfoCache, localAssetInfo); if (ret == -E_NOT_FOUND) { isExist = false; @@ -850,6 +863,8 @@ int CloudSyncer::SaveDatum(SyncParam ¶m, size_t idx, std::vector> deletedList; + // use for record local delete status + std::map localLogInfoCache; for (size_t i = 0; i < param.downloadData.data.size(); i++) { - ret = SaveDatum(param, i, deletedList); + ret = SaveDatum(param, i, deletedList, localLogInfoCache); if (ret != E_OK) { param.info.downLoadInfo.failCount += param.downloadData.data.size(); LOGE("[CloudSyncer] Cannot save datum due to error code %d", ret); @@ -1930,11 +1947,10 @@ int CloudSyncer::CleanCloudData(ClearMode mode, const std::vector & const RelationalSchemaObject &localSchema) { std::lock_guard lock(syncMutex_); - std::string emptyString; int index = 1; for (const auto &tableName: tableNameList) { LOGD("[CloudSyncer] Start clean cloud water mark. table index: %d.", index); - int ret = storageProxy_->SetCloudWaterMark(tableName, emptyString); + int ret = storageProxy_->CleanWaterMark(tableName); if (ret != E_OK) { LOGE("[CloudSyncer] failed to put cloud water mark after clean cloud data, %d.", ret); return ret; @@ -1993,6 +2009,9 @@ void CloudSyncer::UpdateCloudWaterMark(const SyncParam ¶m) int CloudSyncer::CommitDownloadResult(InnerProcessInfo &info, DownloadCommitList &commitList) { + if (commitList.empty()) { + return E_OK; + } uint32_t successCount = 0; int ret = HandleDownloadResult(info.tableName, commitList, successCount); info.downLoadInfo.failCount += (commitList.size() - successCount); @@ -2025,8 +2044,64 @@ int CloudSyncer::TagStatusByStrategy(bool isExist, SyncParam ¶m, DataInfo &d return -E_INTERNAL_ERROR; } strategyOpResult = currentContext_.strategy->TagSyncDataStatus(isExist, dataInfo.localInfo.logInfo, - dataInfo.cloudLogInfo, param.deletePrimaryKeySet); + dataInfo.cloudLogInfo); + } + if (strategyOpResult == OpType::DELETE) { + param.deletePrimaryKeySet.insert(dataInfo.localInfo.logInfo.hashKey); } return E_OK; } + +int CloudSyncer::GetLocalInfo(const std::string &tableName, const VBucket &cloudData, DataInfoWithLog &logInfo, + std::map &localLogInfoCache, VBucket &localAssetInfo) +{ + int errCode = storageProxy_->GetInfoByPrimaryKeyOrGid(tableName, cloudData, logInfo, localAssetInfo); + if (errCode != E_OK) { + return errCode; + } + std::string hashKey(logInfo.logInfo.hashKey.begin(), logInfo.logInfo.hashKey.end()); + if (localLogInfoCache.find(hashKey) != localLogInfoCache.end()) { + LOGD("[CloudSyncer] exist same record in one batch, override from cache record!"); + logInfo.logInfo.flag = localLogInfoCache[hashKey].flag; + logInfo.logInfo.wTimestamp = localLogInfoCache[hashKey].wTimestamp; + logInfo.logInfo.timestamp = localLogInfoCache[hashKey].timestamp; + logInfo.logInfo.cloudGid = localLogInfoCache[hashKey].cloudGid; + logInfo.logInfo.device = localLogInfoCache[hashKey].device; + // delete record should remove local asset info + if ((localLogInfoCache[hashKey].flag & 0x01) == 1) { + localAssetInfo.clear(); + } + } + return errCode; +} + +void CloudSyncer::UpdateLocalCache(OpType opType, const LogInfo &cloudInfo, const LogInfo &localInfo, + std::map &localLogInfoCache) +{ + // only cloud delete data need records + if ((cloudInfo.flag & 0x01) != 1) { + return; + } + LogInfo updateLogInfo; + std::string hashKey(localInfo.hashKey.begin(), localInfo.hashKey.end()); + switch (opType) { + case OpType::DELETE: { + updateLogInfo.flag |= 0x01; + updateLogInfo.timestamp = cloudInfo.timestamp; + updateLogInfo.wTimestamp = cloudInfo.wTimestamp; + updateLogInfo.device = "cloud"; + localLogInfoCache[hashKey] = updateLogInfo; + break; + } + case OpType::CLEAR_GID: + case OpType::UPDATE_TIMESTAMP: { + updateLogInfo = localInfo; + updateLogInfo.cloudGid.clear(); + localLogInfoCache[hashKey] = updateLogInfo; + break; + } + default: + break; + } +} } // namespace DistributedDB diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h index 7df10a57..49855801 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h @@ -67,12 +67,6 @@ protected: DataInfoWithLog localInfo; LogInfo cloudLogInfo; }; - struct AssetDownloadList { - // assets in following list will fill STATUS and timestamp after calling downloading - DownloadList downloadList = {}; - // assets in following list won't fill STATUS and timestamp after calling downloading - DownloadList completeDownloadList = {}; - }; struct WithoutRowIdData { std::vector insertData = {}; std::vector> updateData = {}; @@ -82,7 +76,7 @@ protected: DownloadData downloadData; ChangedData changedData; InnerProcessInfo info; - AssetDownloadList assetsDownloadList; + DownloadList assetsDownloadList; std::string cloudWaterMark; std::vector pkColNames; std::set deletePrimaryKeySet; @@ -99,7 +93,7 @@ protected: std::shared_ptr strategy; std::map> assetFields; // should be cleared after each Download - AssetDownloadList assetDownloadList; + DownloadList assetDownloadList; // store GID and assets, using in upload procedure std::map>> assetsInfo; std::map cloudWaterMarks; @@ -200,7 +194,8 @@ protected: void SetTaskFailed(TaskId taskId, int errCode); - int SaveDatum(SyncParam ¶m, size_t idx, std::vector> &deletedList); + int SaveDatum(SyncParam ¶m, size_t idx, std::vector> &deletedList, + std::map &localLogInfoCache); int SaveData(SyncParam ¶m); @@ -243,7 +238,7 @@ protected: int DownloadAssets(InnerProcessInfo &info, const std::vector &pKColNames, const std::set &dupHashKeySet, ChangedData &changedAssets); - int CloudDbDownloadAssets(InnerProcessInfo &info, const DownloadList &downloadList, bool willHandleResult, + int CloudDbDownloadAssets(InnerProcessInfo &info, const DownloadList &downloadList, const std::set &dupHashKeySet, ChangedData &changedAssets); void GetDownloadItem(const DownloadList &downloadList, size_t i, DownloadItem &downloadItem); @@ -256,7 +251,7 @@ protected: bool IsDataContainDuplicateAsset(const std::vector &assetFields, VBucket &data); - int UpdateChangedData(SyncParam ¶m, AssetDownloadList &assetsDownloadList); + int UpdateChangedData(SyncParam ¶m, DownloadList &assetsDownloadList); void WaitAllSyncCallbackTaskFinish(); @@ -270,6 +265,14 @@ protected: void ClearWithoutData(SyncParam ¶m); + void ModifyFieldNameToLower(VBucket &data); + + int GetLocalInfo(const std::string &tableName, const VBucket &cloudData, DataInfoWithLog &logInfo, + std::map &localLogInfoCache, VBucket &localAssetInfo); + + void UpdateLocalCache(OpType opType, const LogInfo &cloudInfo, + const LogInfo &localInfo, std::map &localLogInfoCache); + std::mutex queueLock_; TaskId currentTaskId_; std::list taskQueue_; diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync.cpp index 0e5371ff..99ac2226 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync.cpp @@ -1324,7 +1324,7 @@ int SingleVerDataSync::RunPermissionCheck(SingleVerSyncTaskContext *context, con uint32_t version = std::min(context->GetRemoteSoftwareVersion(), SOFTWARE_VERSION_CURRENT); if (version > SOFTWARE_VERSION_RELEASE_2_0 && (mode != SyncModeType::PULL) && !context->GetReceivcPermitCheck()) { - bool permitReceive = SingleVerDataSyncUtils::CheckPermitReceiveData(context, communicateHandle_); + bool permitReceive = SingleVerDataSyncUtils::CheckPermitReceiveData(context, communicateHandle_, storage_); if (permitReceive) { context->SetReceivcPermitCheck(true); } else { @@ -1856,7 +1856,7 @@ int SingleVerDataSync::ControlCmdStartCheck(SingleVerSyncTaskContext *context) if ((context->GetMode() != SyncModeType::SUBSCRIBE_QUERY) || context->GetReceivcPermitCheck()) { return E_OK; } - bool permitReceive = SingleVerDataSyncUtils::CheckPermitReceiveData(context, communicateHandle_); + bool permitReceive = SingleVerDataSyncUtils::CheckPermitReceiveData(context, communicateHandle_, storage_); if (permitReceive) { context->SetReceivcPermitCheck(true); } else { diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync_utils.cpp b/kv_store/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync_utils.cpp index 09578114..051a75d7 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync_utils.cpp +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync_utils.cpp @@ -203,8 +203,19 @@ int SingleVerDataSyncUtils::RunPermissionCheck(SingleVerSyncTaskContext *context } bool SingleVerDataSyncUtils::CheckPermitReceiveData(const SingleVerSyncTaskContext *context, - const ICommunicator *communicator) + const ICommunicator *communicator, const SyncGenericInterface *storage) { + if (storage == nullptr) { + LOGE("[DataSync] storage is nullptr when check receive data"); + return false; + } + // check memory db here because remote maybe low version + // it will send option with not set rather than not support when remote is memory db + bool memory = storage->GetDbProperties().GetBoolProp(KvDBProperties::MEMORY_MODE, false); + if (memory) { + LOGE("[DataSync] skip check receive data because local is memory db"); + return true; + } SecurityOption remoteSecOption = context->GetRemoteSeccurityOption(); std::string localDeviceId; if (communicator == nullptr || remoteSecOption.securityLabel == NOT_SURPPORT_SEC_CLASSIFICATION) { diff --git a/kv_store/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync_utils.h b/kv_store/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync_utils.h index 0f1de464..d93df8f1 100644 --- a/kv_store/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync_utils.h +++ b/kv_store/frameworks/libs/distributeddb/syncer/src/single_ver_data_sync_utils.h @@ -48,7 +48,8 @@ public: static int RunPermissionCheck(SingleVerSyncTaskContext *context, const SyncGenericInterface* storage, const std::string &label, int mode); - static bool CheckPermitReceiveData(const SingleVerSyncTaskContext *context, const ICommunicator *communicator); + static bool CheckPermitReceiveData(const SingleVerSyncTaskContext *context, const ICommunicator *communicator, + const SyncGenericInterface *storage); static void SetPacketId(DataRequestPacket *packet, SingleVerSyncTaskContext *context, uint32_t version); diff --git a/kv_store/frameworks/libs/distributeddb/test/BUILD.gn b/kv_store/frameworks/libs/distributeddb/test/BUILD.gn index 9fda240c..b4c59371 100644 --- a/kv_store/frameworks/libs/distributeddb/test/BUILD.gn +++ b/kv_store/frameworks/libs/distributeddb/test/BUILD.gn @@ -64,7 +64,6 @@ config("module_private_config") { "OMIT_FLATBUFFER", "OMIT_MULTI_VER", "RELATIONAL_STORE", - "MANNUAL_SYNC_AND_CLEAN_CLOUD_DATA", "SQLITE_DISTRIBUTE_RELATIONAL", "USE_DFX_ABILITY", "TRACE_SQLITE_EXECUTE", diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_common_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_common_test.cpp index 5b86ecc5..6329f7a5 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_common_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_common_test.cpp @@ -38,7 +38,6 @@ namespace { KvStoreNbDelegate *g_kvNbDelegatePtr = nullptr; auto g_kvNbDelegateCallback = bind(&DistributedDBToolsUnitTest::KvStoreNbDelegateCallback, std::placeholders::_1, std::placeholders::_2, std::ref(g_kvDelegateStatus), std::ref(g_kvNbDelegatePtr)); -} class DistributedDBCommonTest : public testing::Test { public: @@ -548,4 +547,29 @@ HWTEST_F(DistributedDBCommonTest, StringCaseTest002, TestSize.Level0) EXPECT_TRUE(DBCommon::CaseInsensitiveCompare("OPQRSTUVWXYZ", "opqrstuvwxyz")); EXPECT_FALSE(DBCommon::CaseInsensitiveCompare("sqlite", "sqlite3")); EXPECT_FALSE(DBCommon::CaseInsensitiveCompare("gitee", "git")); +} + +HWTEST_F(DistributedDBCommonTest, PerformanceAnalysisTest001, TestSize.Level1) +{ + int threadCount = 1000; + int count1 = 0; + int count2 = 0; + for (int i = 0; i < threadCount; i++) { + std::thread t1([&count1] { + PerformanceAnalysis::GetInstance(20); // 20 is stepNum + count1++; + }); + + std::thread t2([&count2] { + PerformanceAnalysis::GetInstance(20); // 20 is stepNum + count2++; + }); + + t1.join(); + t2.join(); + } + EXPECT_EQ(count1, count2); + EXPECT_EQ(count1, threadCount); +} + } \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.cpp index 23edb85e..e30771fe 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.cpp @@ -27,12 +27,10 @@ #include #include -#include "cloud_db_constant.h" #include "cloud_db_types.h" #include "db_common.h" #include "db_constant.h" #include "generic_single_ver_kv_entry.h" -#include "time_helper.h" #include "platform_specific.h" #include "runtime_config.h" #include "single_ver_data_packet.h" @@ -747,7 +745,12 @@ unsigned long RelationalStoreObserverUnitTest::GetCallCount() const return callCount_; } -void RelationalStoreObserverUnitTest::OnChange(const StoreChangedData& data) +unsigned long RelationalStoreObserverUnitTest::GetCloudCallCount() const +{ + return cloudCallCount_; +} + +void RelationalStoreObserverUnitTest::OnChange(const StoreChangedData &data) { callCount_++; changeDevice_ = data.GetDataChangeDevice(); @@ -759,7 +762,9 @@ void RelationalStoreObserverUnitTest::OnChange(const StoreChangedData& data) void RelationalStoreObserverUnitTest::OnChange( DistributedDB::Origin origin, const std::string &originalId, DistributedDB::ChangedData &&data) { + cloudCallCount_++; savedChangedData_[data.tableName] = data; + LOGD("cloud sync Onchangedata, tableName = %s", data.tableName.c_str()); } void RelationalStoreObserverUnitTest::SetExpectedResult(const DistributedDB::ChangedData &changedData) @@ -805,6 +810,14 @@ static bool IsPrimaryDataEq( uint64_t type, DistributedDB::ChangedData &input, DistributedDB::ChangedData &expected) { for (size_t m = 0; m < input.primaryData[type].size(); m++) { + if (m >= expected.primaryData[type].size()) { + LOGE("Actual primary data's size is more than the expected!"); + return false; + } + if (input.primaryData[type][m].size() != expected.primaryData[type][m].size()) { + LOGE("Primary data fields' size is not equal!"); + return false; + } for (size_t k = 0; k < input.primaryData[type][m].size(); k++) { if (!IsPrimaryKeyEq(input.primaryData[type][m][k], expected.primaryData[type][m][k])) { return false; @@ -867,6 +880,12 @@ void RelationalStoreObserverUnitTest::ResetToZero() storeProperty_ = {}; } +void RelationalStoreObserverUnitTest::ResetCloudSyncToZero() +{ + cloudCallCount_ = 0; + savedChangedData_.clear(); +} + const std::string RelationalStoreObserverUnitTest::GetDataChangeDevice() const { return changeDevice_; @@ -1191,27 +1210,4 @@ END: SQLiteUtils::ResetStatement(stmt, true, errCode); return SQLiteUtils::MapSQLiteErrno(errCode); } - -void RelationalTestUtils::GenerateAssetData(const DistributedDB::Asset &sourceAsset, - std::vector &record, std::vector &extend) -{ - VBucket data; - std::vector photo(1, 'v'); - data.insert_or_assign("name", "Local" + std::to_string(0)); - data.insert_or_assign("height", 166.0); // 166.0 is random double value - data.insert_or_assign("married", false); - data.insert_or_assign("age", 13L); - data.insert_or_assign("photo", photo); - Asset asset = sourceAsset; - asset.name = asset.name + std::to_string(0); - data.insert_or_assign("assert", asset); - record.push_back(data); - VBucket log; - Timestamp now = TimeHelper::GetSysCurrentTime(); - log.insert_or_assign(CloudDbConstant::CREATE_FIELD, (int64_t)now / CloudDbConstant::TEN_THOUSAND); - log.insert_or_assign(CloudDbConstant::MODIFY_FIELD, (int64_t)now / CloudDbConstant::TEN_THOUSAND); - log.insert_or_assign(CloudDbConstant::DELETE_FIELD, false); - log.insert_or_assign("#_gid", std::to_string(2)); // 2 is gid - extend.push_back(log); -} } // namespace DistributedDBUnitTest diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.h b/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.h index f2f7cd97..9614c7ce 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.h +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/common/distributeddb_tools_unit_test.h @@ -282,13 +282,16 @@ public: // reset the callCount_ to zero. void ResetToZero(); + void ResetCloudSyncToZero(); // get callback results. unsigned long GetCallCount() const; + unsigned long GetCloudCallCount() const; const std::string GetDataChangeDevice() const; DistributedDB::StoreProperty GetStoreProperty() const; private: unsigned long callCount_; + unsigned long cloudCallCount_ = 0; std::string changeDevice_; DistributedDB::StoreProperty storeProperty_; std::unordered_map expectedChangedData_; @@ -325,8 +328,6 @@ public: static int CheckTableRecords(sqlite3 *db, const std::string &table); static int GetMetaData(sqlite3 *db, const DistributedDB::Key &key, DistributedDB::Value &value); static int SetMetaData(sqlite3 *db, const DistributedDB::Key &key, const DistributedDB::Value &value); - static void GenerateAssetData(const DistributedDB::Asset &sourceAsset, std::vector &record, - std::vector &extend); }; } // namespace DistributedDBUnitTest diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_ext_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_ext_test.cpp index c1da893f..2882e401 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_ext_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_ext_test.cpp @@ -19,6 +19,7 @@ #include "db_common.h" #include "distributeddb_data_generate_unit_test.h" #include "distributeddb_tools_unit_test.h" +#include "relational_store_client.h" #include "relational_store_manager.h" using namespace testing::ext; @@ -45,6 +46,22 @@ public: static void TearDownTestCase(void); void SetUp() override; void TearDown() override; + void ClientObserverFunc(ClientChangedData &clientChangedData) + { + LOGD("client observer fired, table: %s", clientChangedData.tableName.c_str()); + triggerTableName_ = clientChangedData.tableName; + triggeredCount_++; + } + + void ClientObserverFunc2(ClientChangedData &clientChangedData) + { + LOGD("client observer2 fired, table: %s", clientChangedData.tableName.c_str()); + triggeredCount2_++; + } + + std::string triggerTableName_; + int triggeredCount_ = 0; + int triggeredCount2_ = 0; }; void DistributedDBCloudInterfacesRelationalExtTest::SetUpTestCase(void) @@ -104,7 +121,7 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, GetRawSysTimeTest001, Te EXPECT_EQ(sqlite3_close_v2(db), E_OK); } -void PrepareData(const std::string &tableName, bool primaryKeyIsRowId) +void PrepareData(const std::string &tableName, bool primaryKeyIsRowId, bool userDefineRowid = true) { /** * @tc.steps:step1. create db, create table. @@ -117,7 +134,11 @@ void PrepareData(const std::string &tableName, bool primaryKeyIsRowId) if (primaryKeyIsRowId) { sql = "create table " + tableName + "(rowid INTEGER primary key, id int, name TEXT);"; } else { - sql = "create table " + tableName + "(rowid int, id int, name TEXT, PRIMARY KEY(id, name));"; + if (userDefineRowid) { + sql = "create table " + tableName + "(rowid int, id int, name TEXT, PRIMARY KEY(id, name));"; + } else { + sql = "create table " + tableName + "(id int, name TEXT, PRIMARY KEY(id));"; + } } EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), E_OK); @@ -406,4 +427,204 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, DeleteTriggerTest001, Te EXPECT_EQ(resultCount, 1); EXPECT_EQ(sqlite3_close_v2(db), E_OK); } + +/** + * @tc.name: TriggerObserverTest001 + * @tc.desc: Test invalid args for RegisterClientObserver and UnRegisterClientObserver + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhangshijie + */ +HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, TriggerObserverTest001, TestSize.Level0) +{ + /** + * @tc.steps:step1. call RegisterClientObserver and UnRegisterClientObserver with db = nullptr. + * @tc.expected: step1. return INVALID_ARGS. + */ + ClientObserver clientObserver = std::bind(&DistributedDBCloudInterfacesRelationalExtTest::ClientObserverFunc, + this, std::placeholders::_1); + EXPECT_EQ(RegisterClientObserver(nullptr, clientObserver), INVALID_ARGS); + EXPECT_EQ(UnRegisterClientObserver(nullptr), INVALID_ARGS); + + /** + * @tc.steps:step2. call RegisterClientObserver with nullptr clientObserver. + * @tc.expected: step2. return INVALID_ARGS. + */ + sqlite3 *db = RelationalTestUtils::CreateDataBase(g_dbDir + STORE_ID + DB_SUFFIX); + EXPECT_NE(db, nullptr); + EXPECT_EQ(RegisterClientObserver(db, nullptr), INVALID_ARGS); + + /** + * @tc.steps:step3. call RegisterClientObserver and UnRegisterClientObserver with closed db handle. + * @tc.expected: step3. return INVALID_ARGS. + */ + EXPECT_EQ(sqlite3_close_v2(db), E_OK); + EXPECT_EQ(RegisterClientObserver(db, clientObserver), INVALID_ARGS); + EXPECT_EQ(UnRegisterClientObserver(db), INVALID_ARGS); +} + +/** + * @tc.name: TriggerObserverTest002 + * @tc.desc: Test trigger client observer in sqlite + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhangshijie + */ +HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, TriggerObserverTest002, TestSize.Level0) +{ + /** + * @tc.steps:step1. prepare data. + * @tc.expected: step1. return ok. + */ + const std::string tableName = "sync_data"; + PrepareData(tableName, false, false); + + /** + * @tc.steps:step2. register client observer. + * @tc.expected: step2. return ok. + */ + sqlite3 *db = RelationalTestUtils::CreateDataBase(g_dbDir + STORE_ID + DB_SUFFIX); + EXPECT_NE(db, nullptr); + ClientObserver clientObserver = std::bind(&DistributedDBCloudInterfacesRelationalExtTest::ClientObserverFunc, + this, std::placeholders::_1); + EXPECT_EQ(RegisterClientObserver(db, clientObserver), OK); + + /** + * @tc.steps:step3. insert data into sync_data, check observer. + * @tc.expected: step3. check observer ok. + */ + std::string sql = "insert into " + tableName + " VALUES(1, 'zhangsan'), (2, 'lisi'), (3, 'wangwu');"; + EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), E_OK); + EXPECT_EQ(triggerTableName_, tableName); + EXPECT_EQ(triggeredCount_, 3); // 3 is observer triggered counts + + /** + * @tc.steps:step4. update data, check observer. + * @tc.expected: step4. check observer ok. + */ + sql = "update " + tableName + " set name = 'lisi1' where id = 2;"; + EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), E_OK); + EXPECT_EQ(triggerTableName_, tableName); + EXPECT_EQ(triggeredCount_, 4); // 4 is observer triggered counts + + /** + * @tc.steps:step4. delete data, check observer. + * @tc.expected: step4. check observer ok. + */ + sql = "delete from " + tableName + " where id = 3;"; + EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), E_OK); + EXPECT_EQ(triggerTableName_, tableName); + EXPECT_EQ(triggeredCount_, 5); // 5 is observer triggered counts + + /** + * @tc.steps:step5. register another observer, update data, check observer. + * @tc.expected: step5. check observer ok. + */ + triggeredCount_ = 0; + ClientObserver clientObserver2 = std::bind(&DistributedDBCloudInterfacesRelationalExtTest::ClientObserverFunc2, + this, std::placeholders::_1); + EXPECT_EQ(RegisterClientObserver(db, clientObserver2), OK); + sql = "update " + tableName + " set name = 'lisi2' where id = 2;"; + EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), E_OK); + EXPECT_EQ(triggeredCount_, 0); + EXPECT_EQ(triggeredCount2_, 1); + + /** + * @tc.steps:step6. UnRegisterClientObserver, update data, check observer. + * @tc.expected: step6. check observer ok. + */ + triggeredCount2_ = 0; + EXPECT_EQ(UnRegisterClientObserver(db), OK); + sql = "update " + tableName + " set name = 'lisi3' where id = 2;"; + EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), E_OK); + EXPECT_EQ(triggeredCount2_, 0); // observer2 will not be triggered + EXPECT_EQ(sqlite3_close_v2(db), E_OK); +} + +/** + * @tc.name: TriggerObserverTest003 + * @tc.desc: Test RegisterClientObserver and UnRegisterClientObserver concurrently + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhangshijie + */ +HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, TriggerObserverTest003, TestSize.Level1) +{ + for (int i = 0; i < 1000; i++) { // 1000 is loop times + std::thread t1 ([this]() { + sqlite3 *db = RelationalTestUtils::CreateDataBase(g_dbDir + STORE_ID + DB_SUFFIX); + EXPECT_NE(db, nullptr); + ClientObserver clientObserver = std::bind( + &DistributedDBCloudInterfacesRelationalExtTest::ClientObserverFunc, this, std::placeholders::_1); + EXPECT_EQ(RegisterClientObserver(db, clientObserver), OK); + EXPECT_EQ(UnRegisterClientObserver(db), OK); + EXPECT_EQ(sqlite3_close_v2(db), E_OK); + }); + + std::thread t2 ([this]() { + sqlite3 *db = RelationalTestUtils::CreateDataBase(g_dbDir + STORE_ID + DB_SUFFIX); + EXPECT_NE(db, nullptr); + ClientObserver clientObserver = std::bind( + &DistributedDBCloudInterfacesRelationalExtTest::ClientObserverFunc2, this, std::placeholders::_1); + EXPECT_EQ(RegisterClientObserver(db, clientObserver), OK); + EXPECT_EQ(UnRegisterClientObserver(db), OK); + EXPECT_EQ(sqlite3_close_v2(db), E_OK); + }); + + t1.join(); + t2.join(); + } +} + +/** + * @tc.name: TriggerObserverTest004 + * @tc.desc: Test batch insert/update/delete data then trigger client observer + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhangshijie + */ +HWTEST_F(DistributedDBCloudInterfacesRelationalExtTest, TriggerObserverTest004, TestSize.Level1) +{ + /** + * @tc.steps:step1. prepare data. + * @tc.expected: step1. return ok. + */ + const std::string tableName = "sync_data"; + PrepareData(tableName, false, false); + + /** + * @tc.steps:step2. register client observer. + * @tc.expected: step2. return ok. + */ + sqlite3 *db = RelationalTestUtils::CreateDataBase(g_dbDir + STORE_ID + DB_SUFFIX); + EXPECT_NE(db, nullptr); + ClientObserver clientObserver = std::bind(&DistributedDBCloudInterfacesRelationalExtTest::ClientObserverFunc, + this, std::placeholders::_1); + EXPECT_EQ(RegisterClientObserver(db, clientObserver), OK); + + /** + * @tc.steps:step3. insert data into sync_data, check observer. + * @tc.expected: step3. check observer ok. + */ + std::string sql; + int dataCounts = 1000; + for (int i = 1; i <= dataCounts; i++) { + sql = "insert into " + tableName + " VALUES(" + std::to_string(i) + ", 'zhangsan" + std::to_string(i) + "');"; + EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), E_OK); + } + + EXPECT_EQ(triggerTableName_, tableName); + EXPECT_EQ(triggeredCount_, dataCounts); + + /** + * @tc.steps:step4. insert or replace, check observer. + * @tc.expected: step5. check observer ok. + */ + triggeredCount_ = 0; + sql = "insert or replace into " + tableName + " VALUES(1000, 'lisi');"; + EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), E_OK); + EXPECT_EQ(triggeredCount_, 2); // 2 is trigger times, first delete then insert + EXPECT_EQ(UnRegisterClientObserver(db), OK); + EXPECT_EQ(sqlite3_close_v2(db), E_OK); +} } \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_remove_device_data_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_remove_device_data_test.cpp index ed3807f2..be280104 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_remove_device_data_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_cloud_interfaces_relational_remove_device_data_test.cpp @@ -701,6 +701,5 @@ HWTEST_F(DistributedDBCloudInterfacesRelationalRemoveDeviceDataTest, CleanCloudD ASSERT_EQ(g_delegate->RemoveDeviceData(device, FLAG_AND_DATA), DBStatus::OK); CloseDb(); } - } #endif // RELATIONAL_STORE \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_log_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_log_test.cpp index 7ccaf5da..c64cfb6c 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_log_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_log_test.cpp @@ -80,5 +80,5 @@ HWTEST_F(DistributedDBInterfacesLogTest, DeviceLogTest001, TestSize.Level1) string key4 = "hashKey"; SplitDeviceLogTableManager manager; string value = manager.CalcPrimaryKeyHash(key1, tableInfo, key4); - EXPECT_EQ(value, "calc_hash(calc_hash(NEW.'key2')||calc_hash(NEW.'key3'))"); -} \ No newline at end of file + EXPECT_EQ(value, "calc_hash(calc_hash(NEW.'key2', 0)||calc_hash(NEW.'key3', 0), 0)"); +} diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp index 57f46909..4d9e69ad 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/distributeddb_interfaces_relational_sync_test.cpp @@ -549,10 +549,10 @@ HWTEST_F(DistributedDBInterfacesRelationalSyncTest, UpgradeTriggerTest001, TestS "ON 'student_1'\n" "BEGIN\n" "\t UPDATE naturalbase_rdb_aux_student_1_log SET data_key=-1,timestamp=get_sys_time(0), device=''," - " flag=0x03 WHERE hash_key=calc_hash(OLD.'id') AND flag&0x02=0x02;\n" + " flag=0x03 WHERE hash_key=calc_hash(OLD.'id', 0) AND flag&0x02=0x02;\n" "\t INSERT OR REPLACE INTO naturalbase_rdb_aux_student_1_log VALUES (NEW.rowid, '', '', get_sys_time(0), " - "get_last_time(), CASE WHEN (calc_hash(NEW.'id') != calc_hash(NEW.'id')) " \ - "THEN 0x02 ELSE 0x22 END, calc_hash(NEW.'id'), '');\n" + "get_last_time(), CASE WHEN (calc_hash(NEW.'id', 0) != calc_hash(NEW.'id', 0)) " \ + "THEN 0x02 ELSE 0x22 END, calc_hash(NEW.'id', 0), '');\n" "END"; EXPECT_TRUE(resultTrigger == expectTrigger); } diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_interfaces_relational_sync_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_interfaces_relational_sync_test.cpp index fb6a9064..6c497bbd 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_interfaces_relational_sync_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_interfaces_relational_sync_test.cpp @@ -260,7 +260,7 @@ namespace { data.insert_or_assign("height", 166.0); // 166.0 is random double value data.insert_or_assign("married", false); data.insert_or_assign("photo", photo); - data.insert_or_assign("age", 13L); + data.insert_or_assign("AGE", 13L); Asset asset = g_cloudAsset; asset.name = asset.name + std::to_string(i); assetIsNull ? data.insert_or_assign("assert", Nil()) : data.insert_or_assign("assert", asset); diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_meta_data_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_meta_data_test.cpp index ea784f6f..72ef9ddf 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_meta_data_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_meta_data_test.cpp @@ -36,7 +36,8 @@ namespace { const string STORE_ID = "Relational_Store_ID"; const string TABLE_NAME = "cloudData"; string TEST_DIR; - string STORE_PATH = "./g_store.db"; + string g_storePath; + string g_dbDir; DistributedDB::RelationalStoreManager g_mgr(APP_ID, USER_ID); RelationalStoreDelegate *g_delegate = nullptr; IRelationalStore *g_store = nullptr; @@ -45,7 +46,7 @@ namespace { void CreateDB() { sqlite3 *db = nullptr; - int errCode = sqlite3_open(STORE_PATH.c_str(), &db); + int errCode = sqlite3_open(g_storePath.c_str(), &db); if (errCode != SQLITE_OK) { LOGE("open db failed:%d", errCode); sqlite3_close(db); @@ -73,7 +74,7 @@ namespace { const RelationalSyncAbleStorage *GetRelationalStore() { RelationalDBProperties properties; - InitStoreProp(STORE_PATH, APP_ID, USER_ID, properties); + InitStoreProp(g_storePath, APP_ID, USER_ID, properties); int errCode = E_OK; g_store = RelationalStoreInstance::GetDataBase(properties, errCode); if (g_store == nullptr) { @@ -90,18 +91,18 @@ namespace { void SetAndGetWaterMark(TableName tableName, Timestamp mark) { - Timestamp retMark; - EXPECT_EQ(g_storageProxy->PutLocalWaterMark(tableName, mark), E_OK); - EXPECT_EQ(g_storageProxy->GetLocalWaterMark(tableName, retMark), E_OK); - EXPECT_EQ(retMark, mark); + Timestamp retMark; + EXPECT_EQ(g_storageProxy->PutLocalWaterMark(tableName, mark), E_OK); + EXPECT_EQ(g_storageProxy->GetLocalWaterMark(tableName, retMark), E_OK); + EXPECT_EQ(retMark, mark); } void SetAndGetWaterMark(TableName tableName, std::string mark) { - std::string retMark; - EXPECT_EQ(g_storageProxy->SetCloudWaterMark(tableName, mark), E_OK); - EXPECT_EQ(g_storageProxy->GetCloudWaterMark(tableName, retMark), E_OK); - EXPECT_EQ(retMark, mark); + std::string retMark; + EXPECT_EQ(g_storageProxy->SetCloudWaterMark(tableName, mark), E_OK); + EXPECT_EQ(g_storageProxy->GetCloudWaterMark(tableName, retMark), E_OK); + EXPECT_EQ(retMark, mark); } class DistributedDBCloudMetaDataTest : public testing::Test { @@ -114,6 +115,11 @@ namespace { void DistributedDBCloudMetaDataTest::SetUpTestCase(void) { + DistributedDBToolsUnitTest::TestDirInit(TEST_DIR); + LOGD("test dir is %s", TEST_DIR.c_str()); + g_dbDir = TEST_DIR + "/"; + g_storePath = g_dbDir + STORE_ID + ".db"; + DistributedDBToolsUnitTest::RemoveTestDbFiles(TEST_DIR); } void DistributedDBCloudMetaDataTest::TearDownTestCase(void) @@ -125,7 +131,7 @@ namespace { DistributedDBToolsUnitTest::PrintTestCaseInfo(); LOGD("Test dir is %s", TEST_DIR.c_str()); CreateDB(); - ASSERT_EQ(g_mgr.OpenStore(STORE_PATH, STORE_ID, RelationalStoreDelegate::Option {}, g_delegate), DBStatus::OK); + ASSERT_EQ(g_mgr.OpenStore(g_storePath, STORE_ID, RelationalStoreDelegate::Option {}, g_delegate), DBStatus::OK); ASSERT_NE(g_delegate, nullptr); g_storageProxy = GetStorageProxy((ICloudSyncStorageInterface *) GetRelationalStore()); } @@ -194,4 +200,4 @@ namespace { EXPECT_EQ(retLocalMark, 0u); } -} \ No newline at end of file +} diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_save_cloud_data_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_save_cloud_data_test.cpp index bd99eaa7..92c8a438 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_save_cloud_data_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_save_cloud_data_test.cpp @@ -271,6 +271,7 @@ namespace { EXPECT_EQ(dataInfoWithLog.logInfo.timestamp, eraseTime); EXPECT_EQ(dataInfoWithLog.logInfo.wTimestamp, eraseWTime); } + EXPECT_EQ(storageProxy->Commit(), E_OK); } /** @@ -432,6 +433,7 @@ namespace { DataInfoWithLog dataInfoWithLog; VBucket assetInfo; EXPECT_EQ(storageProxy->GetInfoByPrimaryKeyOrGid(g_tableName, vBucket, dataInfoWithLog, assetInfo), E_OK); + EXPECT_EQ(storageProxy->Commit(), E_OK); } /** diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_cloud_syncable_storage_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_cloud_syncable_storage_test.cpp index af4f51dc..cfd5ae1c 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_cloud_syncable_storage_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_cloud_syncable_storage_test.cpp @@ -1268,9 +1268,10 @@ HWTEST_F(DistributedDBRelationalCloudSyncableStorageTest, CalPrimaryKeyHash001, ASSERT_EQ(g_delegate->CreateDistributedTable(tableName, CLOUD_COOPERATION), DBStatus::OK); std::string name = "Local0"; std::map primaryKey = {{"name", name}}; + std::map collateType = {{"name", CollateType::COLLATE_NONE}}; string sql = "INSERT OR REPLACE INTO user2(name, age) VALUES ('Local" + std::to_string(0) + "', '18');"; EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), SQLITE_OK); - std::vector result = RelationalStoreManager::CalcPrimaryKeyHash(primaryKey); + std::vector result = RelationalStoreManager::CalcPrimaryKeyHash(primaryKey, collateType); EXPECT_NE(result.size(), 0u); std::string logTableName = RelationalStoreManager::GetDistributedLogTableName(tableName); /** @@ -1322,10 +1323,11 @@ HWTEST_F(DistributedDBRelationalCloudSyncableStorageTest, CalPrimaryKeyHash002, ASSERT_EQ(g_delegate->CreateDistributedTable(tableName, CLOUD_COOPERATION), DBStatus::OK); int64_t id = 1; std::map primaryKey = {{"id", id}}; + std::map collateType = {{"id", CollateType::COLLATE_NONE}}; std::string sql = "INSERT OR REPLACE INTO " + tableName + " (id, name) VALUES ('" + '1' + "', 'Local" + std::to_string(0) + "');"; EXPECT_EQ(RelationalTestUtils::ExecSql(db, sql), SQLITE_OK); - std::vector result = RelationalStoreManager::CalcPrimaryKeyHash(primaryKey); + std::vector result = RelationalStoreManager::CalcPrimaryKeyHash(primaryKey, collateType); EXPECT_NE(result.size(), 0u); std::string logTableName = RelationalStoreManager::GetDistributedLogTableName(tableName); /** @@ -1354,4 +1356,4 @@ HWTEST_F(DistributedDBRelationalCloudSyncableStorageTest, CalPrimaryKeyHash002, sqlite3_close(db); } } -#endif // RELATIONAL_STORE \ No newline at end of file +#endif // RELATIONAL_STORE diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_store_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_store_test.cpp index a172472e..b369cd2a 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_store_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_storage_sqlite_single_ver_natural_store_test.cpp @@ -1134,11 +1134,11 @@ HWTEST_F(DistributedDBStorageSQLiteSingleVerNaturalStoreTest, MigrationAndReleas DistributedDB::MockSqliteSingleVerNaturalStore *store = new(std::nothrow) MockSqliteSingleVerNaturalStore; ASSERT_NE(store, nullptr); + store->IncRefCount(); std::thread dataMigrationThread([&store]() { store->CallAsyncDataMigration(); }); std::thread releaseThread([&store]() { - store->IncRefCount(); store->CallReleaseResources(); }); diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_asset_compare_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_asset_compare_test.cpp index 3076c1b4..7213c386 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_asset_compare_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_asset_compare_test.cpp @@ -39,7 +39,8 @@ namespace { constexpr auto FIELD_CARS = "cars"; const string STORE_ID = "Relational_Store_ID"; const string TABLE_NAME = "cloudData"; - string STORE_PATH = "./g_store.db"; + string g_storePath; + string g_dbDir; string TEST_DIR; DistributedDB::RelationalStoreManager g_mgr(APP_ID, USER_ID); RelationalStoreDelegate *g_delegate = nullptr; @@ -135,7 +136,7 @@ namespace { void CreateDB() { sqlite3 *db = nullptr; - int errCode = sqlite3_open(STORE_PATH.c_str(), &db); + int errCode = sqlite3_open(g_storePath.c_str(), &db); if (errCode != SQLITE_OK) { LOGE("open db failed:%d", errCode); sqlite3_close(db); @@ -162,7 +163,7 @@ namespace { const RelationalSyncAbleStorage *GetRelationalStore() { RelationalDBProperties properties; - InitStoreProp(STORE_PATH, APP_ID, USER_ID, properties); + InitStoreProp(g_storePath, APP_ID, USER_ID, properties); int errCode = E_OK; g_store = RelationalStoreInstance::GetDataBase(properties, errCode); if (g_store == nullptr) { @@ -182,6 +183,11 @@ namespace { void DistributedDBCloudAssetCompareTest::SetUpTestCase(void) { + DistributedDBToolsUnitTest::TestDirInit(TEST_DIR); + LOGD("test dir is %s", TEST_DIR.c_str()); + g_dbDir = TEST_DIR + "/"; + g_storePath = g_dbDir + STORE_ID + ".db"; + DistributedDBToolsUnitTest::RemoveTestDbFiles(TEST_DIR); } void DistributedDBCloudAssetCompareTest::TearDownTestCase(void) @@ -193,7 +199,7 @@ namespace { DistributedDBToolsUnitTest::PrintTestCaseInfo(); LOGD("Test dir is %s", TEST_DIR.c_str()); CreateDB(); - ASSERT_EQ(g_mgr.OpenStore(STORE_PATH, STORE_ID, RelationalStoreDelegate::Option {}, g_delegate), DBStatus::OK); + ASSERT_EQ(g_mgr.OpenStore(g_storePath, STORE_ID, RelationalStoreDelegate::Option {}, g_delegate), DBStatus::OK); ASSERT_NE(g_delegate, nullptr); g_storageProxy = std::make_shared((ICloudSyncStorageInterface *) GetRelationalStore()); ASSERT_NE(g_storageProxy, nullptr); @@ -828,4 +834,4 @@ namespace { ASSERT_TRUE(g_cloudSyncer->TestIsDataContainDuplicateAsset(assetFields, DATA_SAME_NAME_ASSETS)); ASSERT_TRUE(g_cloudSyncer->TestIsDataContainDuplicateAsset(assetFields, DATA_BASELINE) == false); } -} \ No newline at end of file +} diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_strategy_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_strategy_test.cpp index 11500180..72aa4f03 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_strategy_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_strategy_test.cpp @@ -100,66 +100,65 @@ HWTEST_F(DistributedDBCloudStrategyTest, TagOpTyeTest001, TestSize.Level0) ASSERT_NE(strategy, nullptr); LogInfo localInfo; LogInfo cloudInfo; - std::set deletePrimaryKeySet; /** * @tc.steps: step2. local not exist cloud record * @tc.expected: step2. insert cloud record to local */ - EXPECT_EQ(strategy->TagSyncDataStatus(false, localInfo, cloudInfo, deletePrimaryKeySet), OpType::INSERT); + EXPECT_EQ(strategy->TagSyncDataStatus(false, localInfo, cloudInfo), OpType::INSERT); /** * @tc.steps: step3. local record is newer and local not exist gid * @tc.expected: step3. only update gid */ localInfo.timestamp = 1u; - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::ONLY_UPDATE_GID); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::ONLY_UPDATE_GID); /** * @tc.steps: step4. local record is newer and local exist gid * @tc.expected: step4. no need handle this record */ localInfo.cloudGid = "gid"; - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::NOT_HANDLE); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::NOT_HANDLE); /** * @tc.steps: step5. cloud record is newer * @tc.expected: step5. update cloud record */ cloudInfo.timestamp = 2u; // mark 2 means cloud is new - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::UPDATE); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::UPDATE); /** * @tc.steps: step6. cloud record is newer and it is delete * @tc.expected: step6. delete cloud record */ cloudInfo.flag = 0x01; // it means delete - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::DELETE); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::DELETE); /** * @tc.steps: step7. cloud is new and local is delete * @tc.expected: step7 insert cloud record */ cloudInfo.flag = 0; // it means no delete localInfo.flag = 0x01; // it means delete - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::INSERT); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::INSERT); /** * @tc.steps: step8. cloud is new and local both delete * @tc.expected: step8 not handle cloud record */ cloudInfo.flag = 0x01; // it means delete - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::UPDATE_TIMESTAMP); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::UPDATE_TIMESTAMP); /** * @tc.steps: step9. cloud is delete and local not exist * @tc.expected: step9 not handle cloud record */ - EXPECT_EQ(strategy->TagSyncDataStatus(false, localInfo, cloudInfo, deletePrimaryKeySet), OpType::NOT_HANDLE); + EXPECT_EQ(strategy->TagSyncDataStatus(false, localInfo, cloudInfo), OpType::NOT_HANDLE); /** * @tc.steps: step10. cloud is old and delete, local has gid * @tc.expected: step10 clear gid */ localInfo.timestamp = 3u; // mark 3 means local is new - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::CLEAR_GID); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::CLEAR_GID); /** * @tc.steps: step10. cloud is old and delete, local has not gid * @tc.expected: step10 not handle cloud record */ localInfo.cloudGid = ""; - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::NOT_HANDLE); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::NOT_HANDLE); } /** @@ -178,39 +177,38 @@ HWTEST_F(DistributedDBCloudStrategyTest, TagOpTyeTest002, TestSize.Level0) ASSERT_NE(strategy, nullptr); LogInfo localInfo; LogInfo cloudInfo; - std::set deletePrimaryKeySet; /** * @tc.steps: step2. local not exist cloud record * @tc.expected: step2. not handle */ - EXPECT_EQ(strategy->TagSyncDataStatus(false, localInfo, cloudInfo, deletePrimaryKeySet), OpType::NOT_HANDLE); + EXPECT_EQ(strategy->TagSyncDataStatus(false, localInfo, cloudInfo), OpType::NOT_HANDLE); /** * @tc.steps: step3. local has cloud record but don't have gid * @tc.expected: step3. only update gid */ - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::ONLY_UPDATE_GID); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::ONLY_UPDATE_GID); /** * @tc.steps: step4. local has cloud record and have gid * @tc.expected: step4. not handle */ localInfo.cloudGid = "gid"; - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::NOT_HANDLE); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::NOT_HANDLE); localInfo.cloudGid = ""; /** * @tc.steps: step5. local has cloud record(without gid) but cloud flag is delete * @tc.expected: step5. ONLY UPDATE GID */ cloudInfo.flag = 0x01; // it means delete - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::NOT_HANDLE); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::NOT_HANDLE); /** * @tc.steps: step6. local has cloud record(with gid) but cloud flag is delete * @tc.expected: step6. CLEAR_GID */ localInfo.cloudGid = "gid"; - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::CLEAR_GID); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::CLEAR_GID); } /** @@ -229,14 +227,12 @@ HWTEST_F(DistributedDBCloudStrategyTest, TagOpTyeTest003, TestSize.Level0) ASSERT_NE(strategy, nullptr); LogInfo localInfo; LogInfo cloudInfo; - std::set deletePrimaryKeySet; /** * @tc.steps: step2. local not exist cloud record(without gid) and its not deleted in cloud * @tc.expected: step2. insert */ - EXPECT_EQ(strategy->TagSyncDataStatus(false, localInfo, cloudInfo, deletePrimaryKeySet), OpType::INSERT); - deletePrimaryKeySet.clear(); + EXPECT_EQ(strategy->TagSyncDataStatus(false, localInfo, cloudInfo), OpType::INSERT); /** * @tc.steps: step3. local not exist cloud record and it's deleted in cloud (without gid) @@ -244,37 +240,31 @@ HWTEST_F(DistributedDBCloudStrategyTest, TagOpTyeTest003, TestSize.Level0) */ localInfo.cloudGid = ""; cloudInfo.flag = 0x01; // it means delete - EXPECT_EQ(strategy->TagSyncDataStatus(false, localInfo, cloudInfo, deletePrimaryKeySet), OpType::NOT_HANDLE); - deletePrimaryKeySet.clear(); + EXPECT_EQ(strategy->TagSyncDataStatus(false, localInfo, cloudInfo), OpType::NOT_HANDLE); /** * @tc.steps: step4. local not exist cloud record and it's deleted in cloud (with gid) * @tc.expected: step4. delete */ localInfo.cloudGid = "gid"; - EXPECT_EQ(strategy->TagSyncDataStatus(false, localInfo, cloudInfo, deletePrimaryKeySet), OpType::DELETE); - deletePrimaryKeySet.clear(); + EXPECT_EQ(strategy->TagSyncDataStatus(false, localInfo, cloudInfo), OpType::DELETE); /** * @tc.steps: step5. local exist cloud record and its deleted in cloud * @tc.expected: step5. delete */ - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::DELETE); - deletePrimaryKeySet.clear(); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::DELETE); localInfo.cloudGid = ""; - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::DELETE); - deletePrimaryKeySet.clear(); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::DELETE); /** * @tc.steps: step6. local exist cloud record and its not deleted in cloud(WITH OR WITHOUT gid) * @tc.expected: step6. UPDATE */ cloudInfo.flag = 0x00; - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::UPDATE); - deletePrimaryKeySet.clear(); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::UPDATE); localInfo.cloudGid = "gid"; - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::UPDATE); - deletePrimaryKeySet.clear(); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::UPDATE); } /** @@ -293,16 +283,15 @@ HWTEST_F(DistributedDBCloudStrategyTest, TagOpTyeTest004, TestSize.Level0) ASSERT_NE(strategy, nullptr); LogInfo localInfo; LogInfo cloudInfo; - std::set deletePrimaryKeySet; cloudInfo.flag = 0x01; localInfo.flag = 0x01; localInfo.cloudGid = ""; - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::UPDATE_TIMESTAMP); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::UPDATE_TIMESTAMP); cloudInfo.flag = 0x00; localInfo.flag = 0x01; - EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo, deletePrimaryKeySet), OpType::INSERT); + EXPECT_EQ(strategy->TagSyncDataStatus(true, localInfo, cloudInfo), OpType::INSERT); } /** diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_db.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_db.cpp index 959e32c6..e74d0d48 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_db.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_db.cpp @@ -180,6 +180,7 @@ DBStatus VirtualCloudDb::DeleteByGid(const std::string &tableName, VBucket &exte tableData.extend[g_modifiedField] = (int64_t)TimeHelper::GetSysCurrentTime() / CloudDbConstant::TEN_THOUSAND; tableData.extend[g_deleteField] = true; + tableData.extend[g_cursorField] = std::to_string(currentCursor_++); LOGD("[VirtualCloudDb] DeleteByGid, gid %s", std::get(extend[g_gidField]).c_str()); tableData.record.clear(); break; @@ -353,4 +354,19 @@ void VirtualCloudDb::SetActionStatus(DBStatus status) { actionStatus_ = status; } + +DBStatus VirtualCloudDb::GetDataStatus(const std::string &gid, bool &deleteStatus) +{ + for (const auto &[tableName, tableDataList]: cloudData_) { + for (auto &tableData : tableDataList) { + if (std::get(tableData.extend.at(g_gidField)) == gid) { + deleteStatus = std::get(tableData.extend.at(g_deleteField)); + LOGI("tableName %s gid %s deleteStatus is %d", tableName.c_str(), gid.c_str(), deleteStatus); + return OK; + } + } + } + LOGE("not found gid %s ", gid.c_str()); + return NOT_FOUND; +} } \ No newline at end of file diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_db.h b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_db.h index dc7a324f..afaad573 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_db.h +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_db.h @@ -64,6 +64,8 @@ public: uint32_t GetQueryTimes(const std::string &tableName); void SetActionStatus(DBStatus status); + + DBStatus GetDataStatus(const std::string &gid, bool &deleteStatus); private: struct CloudData { VBucket record; diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_relational_multi_user_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_relational_multi_user_test.cpp index 14fc7348..bea2e527 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_relational_multi_user_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_relational_multi_user_test.cpp @@ -702,7 +702,6 @@ HWTEST_F(DistributedDBRelationalMultiUserTest, RdbMultiUser003, TestSize.Level3) RuntimeConfig::SetAutoLaunchRequestCallback(nullptr, DBType::DB_RELATION); RuntimeConfig::ReleaseAutoLaunch(USER_ID_2, APP_ID, STORE_ID, DBType::DB_RELATION); - EXPECT_EQ(g_currentStatus, AutoLaunchStatus::WRITE_CLOSED); RuntimeConfig::ReleaseAutoLaunch(USER_ID_2, APP_ID, STORE_ID, DBType::DB_RELATION); g_currentStatus = 0; CloseStore(); diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_relational_ver_p2p_sync_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_relational_ver_p2p_sync_test.cpp index 6298d9de..884911bf 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_relational_ver_p2p_sync_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_relational_ver_p2p_sync_test.cpp @@ -464,20 +464,26 @@ namespace { InsertValueToDB(dataMap); } - void PrepareVirtualEnvironment(std::map &dataMap, const std::string &tableName, - std::vector &fieldInfoList, const std::vector remoteDeviceVec, - bool createDistributedTable = true) + void InsertDataToDeviceB(std::map &dataMap, const std::string &tableName, + std::vector &fieldInfoList, Timestamp ts) { - PrepareBasicTable(tableName, fieldInfoList, remoteDeviceVec, createDistributedTable); GenerateValue(dataMap, fieldInfoList); VirtualRowData virtualRowData; for (const auto &item : dataMap) { virtualRowData.objectData.PutDataValue(item.first, item.second); } - virtualRowData.logInfo.timestamp = 1; + virtualRowData.logInfo.timestamp = ts; g_deviceB->PutData(tableName, {virtualRowData}); } + void PrepareVirtualEnvironment(std::map &dataMap, const std::string &tableName, + std::vector &fieldInfoList, const std::vector remoteDeviceVec, + bool createDistributedTable = true) + { + PrepareBasicTable(tableName, fieldInfoList, remoteDeviceVec, createDistributedTable); + InsertDataToDeviceB(dataMap, tableName, fieldInfoList, 1); + } + void PrepareVirtualEnvironment(std::map &dataMap, const std::vector remoteDeviceVec, bool createDistributedTable = true) { @@ -773,6 +779,20 @@ namespace { } } + static void ReleaseForObserver007(RelationalStoreDelegate *rdb1, RelationalStoreObserverUnitTest *observer1, + RelationalStoreObserverUnitTest *observer) + { + ASSERT_EQ(g_mgr.CloseStore(rdb1), OK); + rdb1 = nullptr; + delete observer1; + observer1 = nullptr; + std::this_thread::sleep_for(std::chrono::seconds(2)); // sleep 2 second to wait sync finish + RuntimeConfig::ReleaseAutoLaunch(USER_ID, APP_ID, STORE_ID_1, DBType::DB_RELATION); + RuntimeContext::GetInstance()->StopTaskPool(); + delete observer; + observer = nullptr; + } + class DistributedDBRelationalVerP2PSyncTest : public testing::Test { public: static void SetUpTestCase(); @@ -1681,7 +1701,7 @@ HWTEST_F(DistributedDBRelationalVerP2PSyncTest, Observer003, TestSize.Level0) * @tc.steps: step3. device A check observer * @tc.expected: step2. data change device is deviceB */ - EXPECT_EQ(g_observer->GetCallCount(), 1u); + EXPECT_EQ(g_observer->GetCallCount(), 2u); // 2 is observer triggered times EXPECT_EQ(g_observer->GetDataChangeDevice(), DEVICE_B); CheckIdentify(g_observer); mgr = std::make_shared(APP_ID, USER_ID); @@ -1889,16 +1909,123 @@ HWTEST_F(DistributedDBRelationalVerP2PSyncTest, Observer007, TestSize.Level3) * @tc.steps: step6. close store and delete observer1 * @tc.expected: step6. success. */ + ReleaseForObserver007(rdb1, observer1, observer); +} + +void RegisterNewObserver(RelationalStoreDelegate *rdb1, RelationalStoreObserverUnitTest *observer1, + RelationalStoreObserverUnitTest *autoLaunchObserver) +{ + /** + * @tc.steps: step1. register another observer + */ + auto observer2 = new (std::nothrow) RelationalStoreObserverUnitTest(); + ASSERT_NE(observer2, nullptr); + EXPECT_EQ(rdb1->RegisterObserver(observer2), OK); + observer1->ResetToZero(); + std::map dataMap; + InsertDataToDeviceB(dataMap, g_tableName, g_fieldInfoList, 2); // 2 is watermark + Query query = Query::Select(g_tableName); + EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true), E_OK); + EXPECT_EQ(observer1->GetCallCount(), 0u); + EXPECT_EQ(autoLaunchObserver->GetCallCount(), 2u); // 2 is auto_launch observer triggered times + EXPECT_EQ(observer2->GetCallCount(), 1u); + + EXPECT_EQ(rdb1->UnRegisterObserver(), OK); + observer2->ResetToZero(); + InsertDataToDeviceB(dataMap, g_tableName, g_fieldInfoList, 3); // 3 is watermark + EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true), E_OK); + EXPECT_EQ(observer1->GetCallCount(), 0u); + EXPECT_EQ(autoLaunchObserver->GetCallCount(), 3u); // 3 is auto_launch observer triggered times + EXPECT_EQ(observer2->GetCallCount(), 0u); + + RuntimeConfig::ReleaseAutoLaunch(USER_ID, APP_ID, STORE_ID_1, DBType::DB_RELATION); + delete autoLaunchObserver; + delete observer1; + delete observer2; ASSERT_EQ(g_mgr.CloseStore(rdb1), OK); rdb1 = nullptr; - delete observer1; - observer1 = nullptr; - std::this_thread::sleep_for(std::chrono::seconds(2)); // sleep 2 second to wait sync finish - std::this_thread::sleep_for(std::chrono::seconds(5)); // sleep 5 second to wait sync finish - RuntimeConfig::ReleaseAutoLaunch(USER_ID, APP_ID, STORE_ID_1, DBType::DB_RELATION); - RuntimeContext::GetInstance()->StopTaskPool(); } +/** +* @tc.name: relation observer 008 +* @tc.desc: Test multi rdb observer +* @tc.type: FUNC +* @tc.require: +* @tc.author: zhangshijie +*/ +HWTEST_F(DistributedDBRelationalVerP2PSyncTest, Observer008, TestSize.Level3) +{ + /** + * @tc.steps: step1. open rdb store, create distribute table and insert data + */ + g_observer->ResetToZero(); + std::map dataMap; + PrepareVirtualEnvironment(dataMap, {g_deviceB}); + + /** + * @tc.steps: step2. set auto launch callBack + */ + RelationalStoreObserverUnitTest *autoObserver = new (std::nothrow) RelationalStoreObserverUnitTest(); + const AutoLaunchRequestCallback callback = [autoObserver](const std::string &identifier, AutoLaunchParam ¶m) { + if (g_id != identifier) { + return false; + } + param.path = g_dbDir; + param.appId = APP_ID; + param.userId = USER_ID; + param.storeId = STORE_ID_1; + param.option.storeObserver = autoObserver; +#ifndef OMIT_ENCRYPT + param.option.isEncryptedDb = true; + param.option.cipher = CipherType::DEFAULT; + param.option.passwd = g_correctPasswd; + param.option.iterateTimes = DEFAULT_ITER; +#endif + return true; + }; + g_mgr.SetAutoLaunchRequestCallback(callback); + /** + * @tc.steps: step3. close store ensure communicator has closed + */ + g_mgr.CloseStore(g_rdbDelegatePtr); + g_rdbDelegatePtr = nullptr; + + /** + * @tc.steps: step4. RunCommunicatorLackCallback to autolaunch store + * @tc.expected: step4. success. + */ + LabelType labelType(g_id.begin(), g_id.end()); + g_communicatorAggregator->RunCommunicatorLackCallback(labelType); + std::this_thread::sleep_for(std::chrono::seconds(1)); + + auto observer1 = new (std::nothrow) RelationalStoreObserverUnitTest(); + ASSERT_NE(observer1, nullptr); + RelationalStoreDelegate::Option option; + option.observer = observer1; +#ifndef OMIT_ENCRYPT + option.isEncryptedDb = true; + option.iterateTimes = DEFAULT_ITER; + option.passwd = g_isAfterRekey ? g_rekeyPasswd : g_correctPasswd; + option.cipher = CipherType::DEFAULT; +#endif + RelationalStoreDelegate *rdb1 = nullptr; + g_mgr.OpenStore(g_dbDir, STORE_ID_1, option, rdb1); + ASSERT_TRUE(rdb1 != nullptr); + /** + * @tc.steps: step5. Call sync expect sync successful and device A check observer + */ + Query query = Query::Select(g_tableName); + EXPECT_EQ(g_deviceB->GenericVirtualDevice::Sync(SYNC_MODE_PUSH_ONLY, query, true), E_OK); + + /** + * @tc.steps: step6. Call sync expect sync successful and device A check observer + */ + EXPECT_EQ(autoObserver->GetCallCount(), 1u); + EXPECT_EQ(observer1->GetCallCount(), 1u); + EXPECT_EQ(autoObserver->GetDataChangeDevice(), DEVICE_B); + CheckIdentify(autoObserver); + RegisterNewObserver(rdb1, observer1, autoObserver); +} /** * @tc.name: remote query 001 diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_sync_check_test.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_sync_check_test.cpp index bc8f21cd..32a60427 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_sync_check_test.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/distributeddb_single_ver_p2p_sync_check_test.cpp @@ -302,6 +302,52 @@ HWTEST_F(DistributedDBSingleVerP2PSyncCheckTest, SecOptionCheck003, TestSize.Lev g_communicatorAggregator->RegOnDispatch(nullptr); } +/** + * @tc.name: sec option check Sync 004 + * @tc.desc: memory db not check device security + * @tc.type: FUNC + * @tc.require: + * @tc.author: zhangqiquan + */ +HWTEST_F(DistributedDBSingleVerP2PSyncCheckTest, SecOptionCheck004, TestSize.Level1) +{ + ASSERT_EQ(g_mgr.CloseKvStore(g_kvDelegatePtr), OK); + g_kvDelegatePtr = nullptr; + KvStoreNbDelegate::Option option; + option.secOption.securityLabel = SecurityLabel::NOT_SET; + option.isMemoryDb = true; + g_mgr.GetKvStore(STORE_ID, option, g_kvDelegateCallback); + ASSERT_TRUE(g_kvDelegateStatus == OK); + ASSERT_TRUE(g_kvDelegatePtr != nullptr); + + auto adapter = std::make_shared(); + RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(adapter); + adapter->ForkCheckDeviceSecurityAbility([](const std::string &, const SecurityOption &) { + return false; + }); + adapter->ForkGetSecurityOption([](const std::string &, SecurityOption &securityOption) { + securityOption.securityLabel = NOT_SET; + return OK; + }); + g_syncInterfaceB->ForkGetSecurityOption([](SecurityOption &) { + return -E_NOT_SUPPORT; + }); + + std::vector devices; + devices.push_back(g_deviceB->GetDeviceId()); + std::map result; + DBStatus status = g_tool.SyncTest(g_kvDelegatePtr, devices, SYNC_MODE_PUSH_PULL, result); + EXPECT_EQ(status, OK); + for (const auto &pair : result) { + LOGD("dev %s, status %d", pair.first.c_str(), pair.second); + EXPECT_TRUE(pair.second == OK); + } + + adapter->ForkCheckDeviceSecurityAbility(nullptr); + adapter->ForkGetSecurityOption(nullptr); + g_syncInterfaceB->ForkGetSecurityOption(nullptr); +} + #ifndef LOW_LEVEL_MEM_DEV /** * @tc.name: BigDataSync001 diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_single_ver_sync_db_Interface.cpp b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_single_ver_sync_db_Interface.cpp index c00ed104..10b51199 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_single_ver_sync_db_Interface.cpp +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_single_ver_sync_db_Interface.cpp @@ -362,6 +362,9 @@ const KvDBProperties &VirtualSingleVerSyncDBInterface::GetDbProperties() const int VirtualSingleVerSyncDBInterface::GetSecurityOption(SecurityOption &option) const { + if (getSecurityOptionCallBack_) { + return getSecurityOptionCallBack_(option); + } option = secOption_; return E_OK; } @@ -590,4 +593,9 @@ void VirtualSingleVerSyncDBInterface::SetSaveDataCallback(const std::function autoLock(saveDataMutex_); saveDataCallback_ = callback; } + +void VirtualSingleVerSyncDBInterface::ForkGetSecurityOption(std::function callBack) +{ + getSecurityOptionCallBack_ = callBack; +} } // namespace DistributedDB diff --git a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_single_ver_sync_db_Interface.h b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_single_ver_sync_db_Interface.h index 25b6e7bf..efa21e97 100644 --- a/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_single_ver_sync_db_Interface.h +++ b/kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/virtual_single_ver_sync_db_Interface.h @@ -143,6 +143,8 @@ public: void ResetDataControl(); void SetSaveDataCallback(const std::function &callback); + + void ForkGetSecurityOption(std::function callBack); private: int GetSyncData(Timestamp begin, Timestamp end, const DataSizeSpecInfo &dataSizeInfo, std::vector &dataItems, ContinueToken &continueStmtToken) const; @@ -181,6 +183,8 @@ private: std::mutex saveDataMutex_; std::function saveDataCallback_; + + std::function getSecurityOptionCallBack_; }; } // namespace DistributedDB diff --git a/kv_store/interfaces/innerkits/distributeddata/BUILD.gn b/kv_store/interfaces/innerkits/distributeddata/BUILD.gn index 9d75c7cc..d1b75214 100644 --- a/kv_store/interfaces/innerkits/distributeddata/BUILD.gn +++ b/kv_store/interfaces/innerkits/distributeddata/BUILD.gn @@ -27,6 +27,7 @@ config("distributeddatafwk_config") { include_dirs = [ "include", + "../../../frameworks/innerkitsimpl/distributeddatamgr/include", "../../../frameworks/innerkitsimpl/distributeddatafwk/include", "../../../frameworks/innerkitsimpl/distributeddatafwk/src", "../../../frameworks/common", @@ -53,7 +54,6 @@ old_source_config = [ "../../../frameworks/innerkitsimpl/distributeddatafwk/src/data_query.cpp", "../../../frameworks/innerkitsimpl/distributeddatafwk/src/distributed_kv_data_manager.cpp", "../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_client_death_observer.cpp", - "../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_data_service.cpp", "../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_observer.cpp", "../../../frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_sync_callback.cpp", "../../../frameworks/innerkitsimpl/distributeddatafwk/src/kv_utils.cpp", @@ -86,7 +86,10 @@ kvdb_source_config = [ "../../../frameworks/innerkitsimpl/kvdb/src/task_executor_adapter.cpp", ] -deps_config = [ "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb" ] +deps_config = [ + "../../../frameworks/libs/distributeddb:distributeddb", + "../distributeddatamgr:distributeddata_mgr", +] external_deps_config = [ "c_utils:utils", diff --git a/kv_store/interfaces/innerkits/distributeddatamgr/BUILD.gn b/kv_store/interfaces/innerkits/distributeddatamgr/BUILD.gn new file mode 100644 index 00000000..43db94ed --- /dev/null +++ b/kv_store/interfaces/innerkits/distributeddatamgr/BUILD.gn @@ -0,0 +1,50 @@ +# Copyright (c) 2023 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. +import("//build/ohos.gni") +import("//foundation/distributeddatamgr/kv_store/kv_store.gni") + +group("build_module") { + deps = [ ":distributeddata_mgr" ] +} + +config("data_mgr_public_config") { + visibility = [ ":*" ] + + cflags = [ "-Wno-multichar" ] + + include_dirs = [ + "include", + "../distributeddata/include", + "../../../frameworks/common", + "../../../frameworks/innerkitsimpl/distributeddatasvc/include", + ] +} + +ohos_shared_library("distributeddata_mgr") { + sources = [ + "../../../frameworks/innerkitsimpl/distributeddatasvc/src/datamgr_service_proxy.cpp", + "../../../frameworks/innerkitsimpl/distributeddatasvc/src/distributed_data_mgr.cpp", + "../../../frameworks/innerkitsimpl/distributeddatasvc/src/kvstore_data_service_mgr.cpp", + ] + + external_deps = [ + "c_utils:utils", + "hilog:libhilog", + "ipc:ipc_core", + "samgr:samgr_proxy", + ] + public_configs = [ ":data_mgr_public_config" ] + innerapi_tags = [ "platformsdk" ] + subsystem_name = "distributeddatamgr" + part_name = "kv_store" +} diff --git a/kv_store/interfaces/innerkits/distributeddatamgr/include/distributed_data_mgr.h b/kv_store/interfaces/innerkits/distributeddatamgr/include/distributed_data_mgr.h new file mode 100644 index 00000000..7339748e --- /dev/null +++ b/kv_store/interfaces/innerkits/distributeddatamgr/include/distributed_data_mgr.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2023 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 DISTRIBUTED_DATA_MGR_H +#define DISTRIBUTED_DATA_MGR_H +#include +#include +#include "visibility.h" +namespace OHOS::DistributedKv { +class DistributedDataMgr { +public: + /** + * @brief Constructor. + */ + API_EXPORT DistributedDataMgr(); + + /** + * @brief Destructor. + */ + API_EXPORT ~DistributedDataMgr(); + /** + * @brief Clear the data of given bundleName, userID and appIndex in datamgr_service. + * @param bundleName The bundle name. + * @param userId The user ID. + * @param appIndex The app index in sandbox. + * @param tokenId The token id to clear. + */ + API_EXPORT int32_t ClearAppStorage(const std::string &bundleName, int32_t userId, int32_t appIndex, + int32_t tokenId); +}; +} // namespace OHOS +#endif //DISTRIBUTED_DATA_MGR_H diff --git a/kv_store/kvstoremock/interfaces/mock/napi_base_context.h b/kv_store/kvstoremock/interfaces/mock/napi_base_context.h index eaa309b7..8ce54d61 100644 --- a/kv_store/kvstoremock/interfaces/mock/napi_base_context.h +++ b/kv_store/kvstoremock/interfaces/mock/napi_base_context.h @@ -18,7 +18,7 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" +#include "napi/native_api.h" namespace OHOS { namespace AppExecFwk { diff --git a/mock/innerkits/napi/ace_napi/include/napi/native_api.h b/mock/innerkits/napi/ace_napi/include/napi/native_api.h index f4e3eb46..47ed9536 100644 --- a/mock/innerkits/napi/ace_napi/include/napi/native_api.h +++ b/mock/innerkits/napi/ace_napi/include/napi/native_api.h @@ -40,6 +40,13 @@ #define NAPI_INNER_EXTERN __attribute__((__deprecated__)) #endif #endif +NAPI_EXTERN napi_status +napi_get_all_property_names(napi_env env, + napi_value object, + napi_key_collection_mode key_mode, + napi_key_filter key_filter, + napi_key_conversion key_conversion, + napi_value* result); NAPI_INNER_EXTERN napi_status napi_set_instance_data(napi_env env, void* data, diff --git a/mock/src/mock_js_napi.cpp b/mock/src/mock_js_napi.cpp index 6c5ce146..ad5467e9 100644 --- a/mock/src/mock_js_napi.cpp +++ b/mock/src/mock_js_napi.cpp @@ -12,9 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include extern "C" { napi_status napi_get_named_property(napi_env env, napi_value object, const char *utf8name, napi_value *result) @@ -366,4 +366,13 @@ int uv_cancel(uv_req_t* req) { return napi_ok; } +NAPI_EXTERN napi_status napi_get_all_property_names(napi_env env, + napi_value object, + napi_key_collection_mode key_mode, + napi_key_filter key_filter, + napi_key_conversion key_conversion, + napi_value* result) +{ + return napi_ok; +} } \ No newline at end of file diff --git a/preferences/frameworks/js/napi/common/include/js_ability.h b/preferences/frameworks/js/napi/common/include/js_ability.h index 938a0d94..fb114b55 100644 --- a/preferences/frameworks/js/napi/common/include/js_ability.h +++ b/preferences/frameworks/js/napi/common/include/js_ability.h @@ -19,9 +19,9 @@ #include #include "ability.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_base_context.h" namespace OHOS { diff --git a/preferences/frameworks/js/napi/common/include/js_utils.h b/preferences/frameworks/js/napi/common/include/js_utils.h index c5a3e9e9..1b15d858 100644 --- a/preferences/frameworks/js/napi/common/include/js_utils.h +++ b/preferences/frameworks/js/napi/common/include/js_utils.h @@ -23,9 +23,9 @@ #include #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace PreferencesJsKit { diff --git a/preferences/frameworks/js/napi/common/include/napi_async_call.h b/preferences/frameworks/js/napi/common/include/napi_async_call.h index ab71f14b..4c5d5f97 100644 --- a/preferences/frameworks/js/napi/common/include/napi_async_call.h +++ b/preferences/frameworks/js/napi/common/include/napi_async_call.h @@ -20,9 +20,9 @@ #include "log_print.h" #include "js_utils.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_preferences_error.h" namespace OHOS { @@ -31,10 +31,10 @@ namespace PreferencesJsKit { using InputAction = std::function; using OutputAction = std::function; using ExecuteAction = std::function; -extern bool async; -extern bool sync; -#define ASYNC &async -#define SYNC &sync +extern bool g_async; +extern bool g_sync; +#define ASYNC &g_async +#define SYNC &g_sync class BaseContext { public: diff --git a/preferences/frameworks/js/napi/common/include/napi_preferences_observer.h b/preferences/frameworks/js/napi/common/include/napi_preferences_observer.h index d1f2eb98..fb28af3c 100644 --- a/preferences/frameworks/js/napi/common/include/napi_preferences_observer.h +++ b/preferences/frameworks/js/napi/common/include/napi_preferences_observer.h @@ -16,7 +16,7 @@ #ifndef DISTRIBUTEDDATAMGR_PREFERENCES_NAPI_PREFERENCES_OBSERVER_H #define DISTRIBUTEDDATAMGR_PREFERENCES_NAPI_PREFERENCES_OBSERVER_H -#include "innerkits/napi/ace_napi/include/napi/native_api.h" +#include "napi/native_api.h" #include "preferences_observer.h" #include "js_observer.h" diff --git a/preferences/frameworks/js/napi/common/include/uv_queue.h b/preferences/frameworks/js/napi/common/include/uv_queue.h index 3a63b4d1..14c7fbdf 100644 --- a/preferences/frameworks/js/napi/common/include/uv_queue.h +++ b/preferences/frameworks/js/napi/common/include/uv_queue.h @@ -15,9 +15,9 @@ #ifndef OHOS_UV_QUEUE_H #define OHOS_UV_QUEUE_H #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "uv.h" namespace OHOS::PreferencesJsKit { diff --git a/preferences/frameworks/js/napi/common/mock/cross_platform/include/js_ability.h b/preferences/frameworks/js/napi/common/mock/cross_platform/include/js_ability.h index 908df88c..d6b864cd 100644 --- a/preferences/frameworks/js/napi/common/mock/cross_platform/include/js_ability.h +++ b/preferences/frameworks/js/napi/common/mock/cross_platform/include/js_ability.h @@ -19,9 +19,9 @@ #include #include "context.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_base_context.h" namespace OHOS { diff --git a/preferences/frameworks/js/napi/common/mock/include/js_ability.h b/preferences/frameworks/js/napi/common/mock/include/js_ability.h index eedc5e76..14b37a47 100644 --- a/preferences/frameworks/js/napi/common/mock/include/js_ability.h +++ b/preferences/frameworks/js/napi/common/mock/include/js_ability.h @@ -18,9 +18,9 @@ #include #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace PreferencesJsKit { diff --git a/preferences/frameworks/js/napi/common/src/napi_async_call.cpp b/preferences/frameworks/js/napi/common/src/napi_async_call.cpp index a9ab59f5..1e717cf4 100644 --- a/preferences/frameworks/js/napi/common/src/napi_async_call.cpp +++ b/preferences/frameworks/js/napi/common/src/napi_async_call.cpp @@ -18,8 +18,8 @@ namespace OHOS { namespace PreferencesJsKit { -bool async = true; // do not reset the value, used in DECLARE_NAPI_FUNCTION_WITH_DATA only -bool sync = !async; // do not reset the value, used in DECLARE_NAPI_FUNCTION_WITH_DATA only +bool g_async = true; // do not reset the value, used in DECLARE_NAPI_FUNCTION_WITH_DATA only +bool g_sync = !g_async; // do not reset the value, used in DECLARE_NAPI_FUNCTION_WITH_DATA only void BaseContext::SetAction( napi_env env, napi_callback_info info, InputAction input, ExecuteAction exec, OutputAction output) { diff --git a/preferences/frameworks/js/napi/preferences/include/napi_preferences.h b/preferences/frameworks/js/napi/preferences/include/napi_preferences.h index b7719c9c..326a5303 100644 --- a/preferences/frameworks/js/napi/preferences/include/napi_preferences.h +++ b/preferences/frameworks/js/napi/preferences/include/napi_preferences.h @@ -22,9 +22,9 @@ #include "js_observer.h" #include "js_utils.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_preferences_observer.h" #include "preferences.h" #include "preferences_helper.h" diff --git a/preferences/frameworks/js/napi/preferences/include/napi_preferences_helper.h b/preferences/frameworks/js/napi/preferences/include/napi_preferences_helper.h index 9925e1f3..15686d2b 100644 --- a/preferences/frameworks/js/napi/preferences/include/napi_preferences_helper.h +++ b/preferences/frameworks/js/napi/preferences/include/napi_preferences_helper.h @@ -15,9 +15,9 @@ #ifndef PREFERENCES_JSKIT_NAPI_PREFERENCE_HELPER_H #define PREFERENCES_JSKIT_NAPI_PREFERENCE_HELPER_H -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace PreferencesJsKit { diff --git a/preferences/frameworks/js/napi/preferences/src/entry_point.cpp b/preferences/frameworks/js/napi/preferences/src/entry_point.cpp index ad8b6601..7d61e3c4 100644 --- a/preferences/frameworks/js/napi/preferences/src/entry_point.cpp +++ b/preferences/frameworks/js/napi/preferences/src/entry_point.cpp @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" #include "napi_preferences.h" #include "napi_preferences_helper.h" diff --git a/preferences/frameworks/js/napi/storage/include/napi_storage.h b/preferences/frameworks/js/napi/storage/include/napi_storage.h index 37b780a0..14c0010c 100644 --- a/preferences/frameworks/js/napi/storage/include/napi_storage.h +++ b/preferences/frameworks/js/napi/storage/include/napi_storage.h @@ -21,9 +21,9 @@ #include #include "js_observer.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_preferences_observer.h" #include "preferences.h" #include "preferences_helper.h" @@ -62,7 +62,6 @@ private: std::shared_ptr value_; napi_env env_; - napi_ref wrapper_; std::mutex listMutex_ {}; std::shared_ptr uvQueue_; std::list> dataObserver_; diff --git a/preferences/frameworks/js/napi/storage/include/napi_storage_helper.h b/preferences/frameworks/js/napi/storage/include/napi_storage_helper.h index 2a60c69d..34957ee0 100644 --- a/preferences/frameworks/js/napi/storage/include/napi_storage_helper.h +++ b/preferences/frameworks/js/napi/storage/include/napi_storage_helper.h @@ -15,9 +15,9 @@ #ifndef PREFERENCES_JSKIT_NAPI_STORAGE_HELPER_H #define PREFERENCES_JSKIT_NAPI_STORAGE_HELPER_H -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace StorageJsKit { diff --git a/preferences/frameworks/js/napi/storage/src/entry_point_storage.cpp b/preferences/frameworks/js/napi/storage/src/entry_point_storage.cpp index 6d99039a..aa784427 100644 --- a/preferences/frameworks/js/napi/storage/src/entry_point_storage.cpp +++ b/preferences/frameworks/js/napi/storage/src/entry_point_storage.cpp @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" #include "napi_storage.h" #include "napi_storage_helper.h" diff --git a/preferences/frameworks/js/napi/storage/src/napi_storage.cpp b/preferences/frameworks/js/napi/storage/src/napi_storage.cpp index abc9205b..aefcebbf 100644 --- a/preferences/frameworks/js/napi/storage/src/napi_storage.cpp +++ b/preferences/frameworks/js/napi/storage/src/napi_storage.cpp @@ -52,13 +52,12 @@ struct StorageAysncContext : public BaseContext { static __thread napi_ref constructor_; StorageProxy::StorageProxy(std::shared_ptr &value) - : value_(value), env_(nullptr), wrapper_(nullptr), uvQueue_(nullptr) + : value_(value), env_(nullptr), uvQueue_(nullptr) { } StorageProxy::~StorageProxy() { - napi_delete_reference(env_, wrapper_); for (auto &observer : dataObserver_) { value_->UnRegisterObserver(observer); } @@ -157,9 +156,7 @@ napi_value StorageProxy::New(napi_env env, napi_callback_info info) obj->env_ = env; obj->value_ = std::move(preference); obj->uvQueue_ = std::make_shared(env); - NAPI_CALL(env, napi_wrap(env, thiz, obj, StorageProxy::Destructor, - nullptr, // finalize_hint - &obj->wrapper_)); + NAPI_CALL(env, napi_wrap(env, thiz, obj, StorageProxy::Destructor, nullptr, nullptr)); return thiz; } diff --git a/preferences/frameworks/js/napi/system_storage/include/napi_system_storage.h b/preferences/frameworks/js/napi/system_storage/include/napi_system_storage.h index e6883f79..6543d0d9 100644 --- a/preferences/frameworks/js/napi/system_storage/include/napi_system_storage.h +++ b/preferences/frameworks/js/napi/system_storage/include/napi_system_storage.h @@ -15,9 +15,9 @@ #ifndef PREFERENCES_JSKIT_NAPI_SYSTEM_STORAGE_H #define PREFERENCES_JSKIT_NAPI_SYSTEM_STORAGE_H -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace PreferencesJsKit { diff --git a/preferences/frameworks/js/napi/system_storage/src/entry_point_system_storage.cpp b/preferences/frameworks/js/napi/system_storage/src/entry_point_system_storage.cpp index af91bce2..79263993 100644 --- a/preferences/frameworks/js/napi/system_storage/src/entry_point_system_storage.cpp +++ b/preferences/frameworks/js/napi/system_storage/src/entry_point_system_storage.cpp @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" #include "napi_system_storage.h" EXTERN_C_START diff --git a/preferences/frameworks/native/include/preferences_xml_utils.h b/preferences/frameworks/native/include/preferences_xml_utils.h index 2b46677f..8c4bdef1 100644 --- a/preferences/frameworks/native/include/preferences_xml_utils.h +++ b/preferences/frameworks/native/include/preferences_xml_utils.h @@ -18,7 +18,6 @@ #include #include - namespace OHOS { namespace NativePreferences { class Element { diff --git a/preferences/test/native/fuzztest/preferences_fuzzer/BUILD.gn b/preferences/test/native/fuzztest/preferences_fuzzer/BUILD.gn index 3388a4b2..f771febc 100644 --- a/preferences/test/native/fuzztest/preferences_fuzzer/BUILD.gn +++ b/preferences/test/native/fuzztest/preferences_fuzzer/BUILD.gn @@ -25,7 +25,7 @@ config("module_private_config") { ##############################fuzztest########################################## ohos_fuzztest("PreferencesFuzzTest") { - module_out_path = "preferences/impl" + module_out_path = "preferences/preference" fuzz_config_file = "//foundation/distributeddatamgr/preferences/test/native/fuzztest/preferences_fuzzer" diff --git a/preferences/test/native/unittest/preferences_file_test.cpp b/preferences/test/native/unittest/preferences_file_test.cpp index 2c3a9f00..8addb083 100644 --- a/preferences/test/native/unittest/preferences_file_test.cpp +++ b/preferences/test/native/unittest/preferences_file_test.cpp @@ -22,7 +22,7 @@ #include "preferences.h" #include "preferences_errno.h" #include "preferences_helper.h" -#include "include/preferences_xml_utils.h" +#include "preferences_xml_utils.h" using namespace testing::ext; using namespace OHOS::NativePreferences; diff --git a/preferences/test/native/unittest/preferences_xml_utils_test.cpp b/preferences/test/native/unittest/preferences_xml_utils_test.cpp index fa0ef6d7..5ca90a1a 100644 --- a/preferences/test/native/unittest/preferences_xml_utils_test.cpp +++ b/preferences/test/native/unittest/preferences_xml_utils_test.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "include/preferences_xml_utils.h" +#include "preferences_xml_utils.h" #include @@ -23,7 +23,7 @@ #include "preferences.h" #include "preferences_errno.h" #include "preferences_helper.h" -#include "include/preferences_impl.h" +#include "preferences_impl.h" using namespace testing::ext; using namespace OHOS::NativePreferences; diff --git a/relational_store/frameworks/js/napi/cloud_data/include/js_const_properties.h b/relational_store/frameworks/js/napi/cloud_data/include/js_const_properties.h index 9a100577..6245a158 100644 --- a/relational_store/frameworks/js/napi/cloud_data/include/js_const_properties.h +++ b/relational_store/frameworks/js/napi/cloud_data/include/js_const_properties.h @@ -15,9 +15,9 @@ #ifndef LDBPROJ_JS_CONST_PROPERTIES_H #define LDBPROJ_JS_CONST_PROPERTIES_H -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS::CloudData { napi_status InitConstProperties(napi_env env, napi_value exports); diff --git a/relational_store/frameworks/js/napi/cloud_data/include/js_error_utils.h b/relational_store/frameworks/js/napi/cloud_data/include/js_error_utils.h index b5395ad5..93d9d5d0 100644 --- a/relational_store/frameworks/js/napi/cloud_data/include/js_error_utils.h +++ b/relational_store/frameworks/js/napi/cloud_data/include/js_error_utils.h @@ -21,7 +21,7 @@ #include "cloud_service.h" #include "js_native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" +#include "napi/native_common.h" namespace OHOS { namespace CloudData { diff --git a/relational_store/frameworks/js/napi/cloud_data/include/napi_queue.h b/relational_store/frameworks/js/napi/cloud_data/include/napi_queue.h index ed7c7e7f..b1f8b045 100644 --- a/relational_store/frameworks/js/napi/cloud_data/include/napi_queue.h +++ b/relational_store/frameworks/js/napi/cloud_data/include/napi_queue.h @@ -21,9 +21,9 @@ #include #include "logger.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS::CloudData { using namespace OHOS::Rdb; diff --git a/relational_store/frameworks/js/napi/common/include/js_ability.h b/relational_store/frameworks/js/napi/common/include/js_ability.h index a1d858f3..91ca1e2b 100644 --- a/relational_store/frameworks/js/napi/common/include/js_ability.h +++ b/relational_store/frameworks/js/napi/common/include/js_ability.h @@ -19,9 +19,9 @@ #include #include "ability.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_base_context.h" namespace OHOS { diff --git a/relational_store/frameworks/js/napi/common/include/js_utils.h b/relational_store/frameworks/js/napi/common/include/js_utils.h index aa039420..1a50f884 100644 --- a/relational_store/frameworks/js/napi/common/include/js_utils.h +++ b/relational_store/frameworks/js/napi/common/include/js_utils.h @@ -24,9 +24,9 @@ #include #include #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace AppDataMgrJsKit { @@ -216,9 +216,13 @@ int32_t JSUtils::Convert2Value(napi_env env, napi_value jsValue, std::variant(env, jsValue, value); } diff --git a/relational_store/frameworks/js/napi/common/include/js_uv_queue.h b/relational_store/frameworks/js/napi/common/include/js_uv_queue.h index 49c6af80..f9fb07c8 100644 --- a/relational_store/frameworks/js/napi/common/include/js_uv_queue.h +++ b/relational_store/frameworks/js/napi/common/include/js_uv_queue.h @@ -15,9 +15,9 @@ #ifndef DISTRIBUTEDDATAMGR_APPDATAMGR_UV_QUEUE_H #define DISTRIBUTEDDATAMGR_APPDATAMGR_UV_QUEUE_H #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "uv.h" namespace OHOS::AppDataMgrJsKit { diff --git a/relational_store/frameworks/js/napi/common/mock/include/js_ability.h b/relational_store/frameworks/js/napi/common/mock/include/js_ability.h index f722295d..490fe2c3 100644 --- a/relational_store/frameworks/js/napi/common/mock/include/js_ability.h +++ b/relational_store/frameworks/js/napi/common/mock/include/js_ability.h @@ -21,9 +21,9 @@ #if defined(ANDROID_PLATFORM) || defined(IOS_PLATFORM) #include "context.h" #endif -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace AppDataMgrJsKit { diff --git a/relational_store/frameworks/js/napi/common/mock/include/napi_async_proxy.h b/relational_store/frameworks/js/napi/common/mock/include/napi_async_proxy.h index 50a12940..e3ac9bc5 100644 --- a/relational_store/frameworks/js/napi/common/mock/include/napi_async_proxy.h +++ b/relational_store/frameworks/js/napi/common/mock/include/napi_async_proxy.h @@ -16,9 +16,9 @@ #define PREFERENCES_JSKIT_NAPI_ASYNC_PROXY_H #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace AppDataMgrJsKit { diff --git a/relational_store/frameworks/js/napi/common/src/js_utils.cpp b/relational_store/frameworks/js/napi/common/src/js_utils.cpp index 6551c141..737f5fa1 100644 --- a/relational_store/frameworks/js/napi/common/src/js_utils.cpp +++ b/relational_store/frameworks/js/napi/common/src/js_utils.cpp @@ -226,13 +226,7 @@ int32_t JSUtils::Convert2Value(napi_env env, napi_value jsValue, std::monostate value = std::monostate(); return napi_ok; } - napi_get_undefined(env, &tempValue); - napi_strict_equals(env, jsValue, tempValue, &equal); - if (equal) { - value = std::monostate(); - return napi_ok; - } - LOG_DEBUG("jsValue is not undefined or null"); + LOG_DEBUG("jsValue is not null"); return napi_invalid_arg; } diff --git a/relational_store/frameworks/js/napi/dataability/include/napi_async_proxy.h b/relational_store/frameworks/js/napi/dataability/include/napi_async_proxy.h index 844d9950..9faad503 100644 --- a/relational_store/frameworks/js/napi/dataability/include/napi_async_proxy.h +++ b/relational_store/frameworks/js/napi/dataability/include/napi_async_proxy.h @@ -16,9 +16,9 @@ #define PREFERENCES_JSKIT_NAPI_ASYNC_PROXY_H #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "securec.h" namespace OHOS { diff --git a/relational_store/frameworks/js/napi/dataability/include/napi_data_ability_predicates.h b/relational_store/frameworks/js/napi/dataability/include/napi_data_ability_predicates.h index b826edbd..983ded14 100644 --- a/relational_store/frameworks/js/napi/dataability/include/napi_data_ability_predicates.h +++ b/relational_store/frameworks/js/napi/dataability/include/napi_data_ability_predicates.h @@ -18,9 +18,9 @@ #include #include "data_ability_predicates.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace DataAbilityJsKit { diff --git a/relational_store/frameworks/js/napi/dataability/include/napi_predicates_utils.h b/relational_store/frameworks/js/napi/dataability/include/napi_predicates_utils.h index 7c1e04ad..4c4ee48b 100644 --- a/relational_store/frameworks/js/napi/dataability/include/napi_predicates_utils.h +++ b/relational_store/frameworks/js/napi/dataability/include/napi_predicates_utils.h @@ -16,9 +16,9 @@ #ifndef APPDATAMGR_NAPI_PREDICATES_UTILS_H #define APPDATAMGR_NAPI_PREDICATES_UTILS_H -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace DataAbilityJsKit { diff --git a/relational_store/frameworks/js/napi/dataability/src/entry_point.cpp b/relational_store/frameworks/js/napi/dataability/src/entry_point.cpp index 770181fa..4401f491 100644 --- a/relational_store/frameworks/js/napi/dataability/src/entry_point.cpp +++ b/relational_store/frameworks/js/napi/dataability/src/entry_point.cpp @@ -13,8 +13,8 @@ * limitations under the License. */ -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" #include "napi_data_ability_predicates.h" #include "napi_predicates_utils.h" diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_async_call.h b/relational_store/frameworks/js/napi/rdb/include/napi_async_call.h index 8314db2f..8ca32471 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_async_call.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_async_call.h @@ -20,9 +20,9 @@ #include "js_utils.h" #include "logger.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_rdb_error.h" namespace OHOS { diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_const_properties.h b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_const_properties.h index 3e4599a5..bfdad8a9 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_const_properties.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_const_properties.h @@ -16,9 +16,9 @@ #ifndef NAPI_RDB_CONST_PROPERTIES_H #define NAPI_RDB_CONST_PROPERTIES_H -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_common.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS::RdbJsKit { napi_status InitConstProperties(napi_env env, napi_value exports); diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_error.h b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_error.h index e9ff9aed..4b81bc0a 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_error.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_error.h @@ -15,7 +15,6 @@ #ifndef RDB_JS_NAPI_ERROR_H #define RDB_JS_NAPI_ERROR_H -#include #include "logger.h" namespace OHOS { diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_predicates.h b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_predicates.h index 95cb30b3..81ba767f 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_predicates.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_predicates.h @@ -18,9 +18,9 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_rdb_error.h" #include "rdb_predicates.h" diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store.h b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store.h index a406083d..7cfcc6fb 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store.h @@ -19,9 +19,9 @@ #include #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_rdb_error.h" #include "napi_rdb_store_observer.h" #include "rdb_helper.h" diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_helper.h b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_helper.h index 9d735d42..cab34be9 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_helper.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_rdb_store_helper.h @@ -20,9 +20,9 @@ #include #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace RdbJsKit { diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_result_set.h b/relational_store/frameworks/js/napi/rdb/include/napi_result_set.h index 8c7340e6..22f532aa 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_result_set.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_result_set.h @@ -19,9 +19,9 @@ #include #include "abs_shared_result_set.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_rdb_error.h" #include "result_set_bridge.h" diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_uv_queue.h b/relational_store/frameworks/js/napi/rdb/include/napi_uv_queue.h index 61464980..b59c1cb2 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_uv_queue.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_uv_queue.h @@ -18,9 +18,9 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS::RdbJsKit { class NapiUvQueue { diff --git a/relational_store/frameworks/js/napi/rdb/include/napi_values_bucket.h b/relational_store/frameworks/js/napi/rdb/include/napi_values_bucket.h index 71d0e173..a67d08b2 100644 --- a/relational_store/frameworks/js/napi/rdb/include/napi_values_bucket.h +++ b/relational_store/frameworks/js/napi/rdb/include/napi_values_bucket.h @@ -16,9 +16,9 @@ #ifndef APPDATAMGR_NAPI_VALUES_BUCKET_H #define APPDATAMGR_NAPI_VALUES_BUCKET_H -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "values_bucket.h" EXTERN_C_START diff --git a/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_predicates.h b/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_predicates.h index 708d1a3c..c452312a 100644 --- a/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_predicates.h +++ b/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_predicates.h @@ -18,9 +18,9 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_rdb_error.h" #include "rdb_predicates.h" diff --git a/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_store.h b/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_store.h index e2170748..f0f862bb 100644 --- a/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_store.h +++ b/relational_store/frameworks/js/napi/rdb/mock/include/napi_rdb_store.h @@ -19,9 +19,9 @@ #include #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_rdb_error.h" #include "rdb_helper.h" diff --git a/relational_store/frameworks/js/napi/rdb/mock/include/napi_result_set.h b/relational_store/frameworks/js/napi/rdb/mock/include/napi_result_set.h index c3fa6083..3be1867e 100644 --- a/relational_store/frameworks/js/napi/rdb/mock/include/napi_result_set.h +++ b/relational_store/frameworks/js/napi/rdb/mock/include/napi_result_set.h @@ -18,9 +18,9 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_rdb_error.h" #include "result_set.h" diff --git a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp index 5417b475..9fba8774 100644 --- a/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp +++ b/relational_store/frameworks/js/napi/rdb/src/napi_rdb_store.cpp @@ -437,7 +437,9 @@ int ParseSql(const napi_env env, const napi_value arg, std::shared_ptr context) { napi_value keys = 0; - napi_get_property_names(env, arg, &keys); + napi_get_all_property_names(env, arg, napi_key_own_only, + static_cast(napi_key_enumerable | napi_key_skip_symbols), + napi_key_numbers_to_strings, &keys); uint32_t arrLen = 0; napi_status status = napi_get_array_length(env, keys, &arrLen); std::shared_ptr paramError = std::make_shared("values", "a ValuesBucket."); @@ -459,8 +461,10 @@ int ParseValuesBucket(const napi_env env, const napi_value arg, std::shared_ptr< int32_t ret = JSUtils::Convert2Value(env, value, valueObject.value); if (ret == napi_ok) { context->valuesBucket.Put(keyStr, std::move(valueObject)); - } else { - LOG_WARN("bad value type of key %{public}s", keyStr.c_str()); + } else if (ret != napi_generic_failure) { + std::shared_ptr paramError = std::make_shared( + "The value type of " + keyStr, "valid."); + RDB_CHECK_RETURN_CALL_RESULT(false, context->SetError(paramError)); } } LOG_DEBUG("ParseValuesBucket end"); diff --git a/relational_store/frameworks/js/napi/relationalstore/include/napi_async_call.h b/relational_store/frameworks/js/napi/relationalstore/include/napi_async_call.h index cc08320e..16e01901 100644 --- a/relational_store/frameworks/js/napi/relationalstore/include/napi_async_call.h +++ b/relational_store/frameworks/js/napi/relationalstore/include/napi_async_call.h @@ -20,9 +20,9 @@ #include "js_utils.h" #include "logger.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_rdb_error.h" namespace OHOS { diff --git a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_const_properties.h b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_const_properties.h index 0c68d0df..41316245 100644 --- a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_const_properties.h +++ b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_const_properties.h @@ -16,9 +16,9 @@ #ifndef NAPI_RDB_CONST_PROPERTIES_H #define NAPI_RDB_CONST_PROPERTIES_H -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_common.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS::RelationalStoreJsKit { napi_status InitConstProperties(napi_env env, napi_value exports); diff --git a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_predicates.h b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_predicates.h index 9087707b..5317cbf1 100644 --- a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_predicates.h +++ b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_predicates.h @@ -18,9 +18,9 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_rdb_error.h" #include "rdb_predicates.h" diff --git a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_store.h b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_store.h index a259ea8a..b9b8408d 100644 --- a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_store.h +++ b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_store.h @@ -20,9 +20,9 @@ #include #include "js_uv_queue.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_rdb_error.h" #include "napi_rdb_store_observer.h" #include "rdb_helper.h" diff --git a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_store_helper.h b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_store_helper.h index 0a9308cb..b301c759 100644 --- a/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_store_helper.h +++ b/relational_store/frameworks/js/napi/relationalstore/include/napi_rdb_store_helper.h @@ -20,9 +20,9 @@ #include #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS { namespace RelationalStoreJsKit { diff --git a/relational_store/frameworks/js/napi/relationalstore/include/napi_result_set.h b/relational_store/frameworks/js/napi/relationalstore/include/napi_result_set.h index 8a4225d4..d9d8b6d9 100644 --- a/relational_store/frameworks/js/napi/relationalstore/include/napi_result_set.h +++ b/relational_store/frameworks/js/napi/relationalstore/include/napi_result_set.h @@ -19,9 +19,9 @@ #include #include "asset_value.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_rdb_error.h" #include "result_set.h" #include "result_set_bridge.h" diff --git a/relational_store/frameworks/js/napi/relationalstore/include/napi_uv_queue.h b/relational_store/frameworks/js/napi/relationalstore/include/napi_uv_queue.h index f4df00d6..5f3d618b 100644 --- a/relational_store/frameworks/js/napi/relationalstore/include/napi_uv_queue.h +++ b/relational_store/frameworks/js/napi/relationalstore/include/napi_uv_queue.h @@ -18,9 +18,9 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" namespace OHOS::RelationalStoreJsKit { class NapiUvQueue { diff --git a/relational_store/frameworks/js/napi/relationalstore/mock/include/napi_rdb_store.h b/relational_store/frameworks/js/napi/relationalstore/mock/include/napi_rdb_store.h index d56815be..71aae8c5 100644 --- a/relational_store/frameworks/js/napi/relationalstore/mock/include/napi_rdb_store.h +++ b/relational_store/frameworks/js/napi/relationalstore/mock/include/napi_rdb_store.h @@ -20,9 +20,9 @@ #include #include "js_uv_queue.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_rdb_error.h" #include "rdb_helper.h" diff --git a/relational_store/frameworks/js/napi/relationalstore/mock/include/napi_result_set.h b/relational_store/frameworks/js/napi/relationalstore/mock/include/napi_result_set.h index 991bd447..4d3ab59a 100644 --- a/relational_store/frameworks/js/napi/relationalstore/mock/include/napi_result_set.h +++ b/relational_store/frameworks/js/napi/relationalstore/mock/include/napi_result_set.h @@ -18,9 +18,9 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "result_set.h" namespace OHOS { diff --git a/relational_store/frameworks/js/napi/relationalstore/src/entry_point.cpp b/relational_store/frameworks/js/napi/relationalstore/src/entry_point.cpp index 91fcb6b6..bd71af43 100644 --- a/relational_store/frameworks/js/napi/relationalstore/src/entry_point.cpp +++ b/relational_store/frameworks/js/napi/relationalstore/src/entry_point.cpp @@ -17,7 +17,7 @@ #include "napi_rdb_store.h" #include "napi_rdb_store_helper.h" #include "napi_rdb_const_properties.h" -#include "innerkits/napi/ace_napi/include/napi/native_api.h" +#include "napi/native_api.h" using namespace OHOS::RelationalStoreJsKit; diff --git a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_predicates.cpp b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_predicates.cpp index 4adbc4b2..e1ee53f5 100644 --- a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_predicates.cpp +++ b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_predicates.cpp @@ -72,10 +72,8 @@ void RdbPredicatesProxy::Init(napi_env env, napi_value exports) DECLARE_NAPI_GETTER_SETTER("joinTypes", GetJoinTypes, SetJoinTypes), DECLARE_NAPI_GETTER("statement", GetStatement), DECLARE_NAPI_GETTER("bindArgs", GetBindArgs), -#if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) DECLARE_NAPI_FUNCTION("inDevices", InDevices), DECLARE_NAPI_FUNCTION("inAllDevices", InAllDevices), -#endif }; napi_value cons; @@ -856,7 +854,6 @@ std::shared_ptr RdbPredicatesProxy::GetPredicates() co return this->predicates_; } -#if !defined(WINDOWS_PLATFORM) && !defined(MAC_PLATFORM) && !defined(ANDROID_PLATFORM) && !defined(IOS_PLATFORM) napi_value RdbPredicatesProxy::InDevices(napi_env env, napi_callback_info info) { LOG_DEBUG("RdbPredicatesProxy::InDevices begin."); @@ -878,6 +875,5 @@ napi_value RdbPredicatesProxy::InAllDevices(napi_env env, napi_callback_info inf predicatesProxy->predicates_->InAllDevices(); return thiz; } -#endif } // namespace RelationalStoreJsKit } // namespace OHOS diff --git a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store.cpp b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store.cpp index 97c6a18a..f2017704 100644 --- a/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store.cpp +++ b/relational_store/frameworks/js/napi/relationalstore/src/napi_rdb_store.cpp @@ -449,7 +449,9 @@ int ParseSql(const napi_env env, const napi_value arg, std::shared_ptr context) { napi_value keys = 0; - napi_get_property_names(env, arg, &keys); + napi_get_all_property_names(env, arg, napi_key_own_only, + static_cast(napi_key_enumerable | napi_key_skip_symbols), + napi_key_numbers_to_strings, &keys); uint32_t arrLen = 0; napi_status status = napi_get_array_length(env, keys, &arrLen); CHECK_RETURN_SET(status == napi_ok, std::make_shared("values", "a ValuesBucket.")); @@ -465,8 +467,8 @@ int ParseValuesBucket(const napi_env env, const napi_value arg, std::shared_ptr< int32_t ret = JSUtils::Convert2Value(env, value, valueObject.value); if (ret == napi_ok) { context->valuesBucket.Put(keyStr, valueObject); - } else { - LOG_WARN("bad value type of key %{public}s", keyStr.c_str()); // TD: need to throw error here + } else if (ret != napi_generic_failure) { + CHECK_RETURN_SET(false, std::make_shared("The value type of " + keyStr, "valid.")); } } return OK; diff --git a/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h b/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h index 8dbdd573..acc1ee9e 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h +++ b/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h @@ -32,12 +32,6 @@ public: SubscribeOption subscribeOption{ SubscribeMode::REMOTE }; }; using Observers = ConcurrentMap>; - struct SyncAgent { - Observers observers; - bool AddObserver(const std::string &storeName, const ObserverParam ¶m); - std::pair RemoveObserver( - const std::string &storeName, RdbStoreObserver *observer); - }; explicit RdbServiceProxy(const sptr& object); @@ -95,8 +89,8 @@ private: std::string RemoveSuffix(const std::string& name); std::atomic seqNum_ {}; + ConcurrentMap syncCallbacks_; - SyncAgent syncAgent_; Observers observers_; sptr notifier_; diff --git a/relational_store/frameworks/native/rdb/include/rdb_store_manager.h b/relational_store/frameworks/native/rdb/include/rdb_store_manager.h index 7f5627d5..e6cbab51 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_store_manager.h +++ b/relational_store/frameworks/native/rdb/include/rdb_store_manager.h @@ -41,7 +41,6 @@ public: private: int ProcessOpenCallback(RdbStore &rdbStore, const RdbStoreConfig &config, int version, RdbOpenCallback &openCallback); - std::string bundleName_; std::mutex mutex_; std::map> storeCache_; }; diff --git a/relational_store/frameworks/native/rdb/src/rdb_service_proxy.cpp b/relational_store/frameworks/native/rdb/src/rdb_service_proxy.cpp index 4b290a45..6054d533 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_service_proxy.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_service_proxy.cpp @@ -246,11 +246,20 @@ int32_t RdbServiceProxy::Subscribe(const RdbSyncerParam ¶m, const SubscribeO LOG_ERROR("subscribe mode invalid"); return RDB_ERROR; } - auto name = RemoveSuffix(param.storeName_); - auto isCreate = syncAgent_.AddObserver(name, { observer, param.bundleName_, option }); - if (isCreate && DoSubscribe(param, option) != RDB_OK) { - syncAgent_.RemoveObserver(name, observer); + if (DoSubscribe(param, option) != RDB_OK) { + return RDB_ERROR; } + auto name = RemoveSuffix(param.storeName_); + observers_.Compute(name, [observer, ¶m, &option](const auto &key, std::list &value) { + for (const auto &element : value) { + if (element.observer == observer) { + LOG_ERROR("duplicate observer"); + return true; + } + } + value.push_back({ observer, param.bundleName_, option }); + return true; + }); return RDB_OK; } @@ -273,12 +282,18 @@ int32_t RdbServiceProxy::UnSubscribe(const RdbSyncerParam ¶m, const Subscrib LOG_ERROR("observer is null"); return RDB_ERROR; } - auto name = RemoveSuffix(param.storeName_); - auto [observerParam, isDestroy] = syncAgent_.RemoveObserver(name, observer); - if (isDestroy && DoUnSubscribe(param) != RDB_OK) { - syncAgent_.AddObserver(name, observerParam); + if (DoUnSubscribe(param) != RDB_OK) { return RDB_ERROR; } + auto name = RemoveSuffix(param.storeName_); + observers_.ComputeIfPresent(name, [observer](const auto &key, std::list &value) { + LOG_INFO("before remove size=%{public}d", static_cast(value.size())); + value.remove_if([observer](const ObserverParam ¶m) { + return param.observer == observer; + }); + LOG_INFO("after remove size=%{public}d", static_cast(value.size())); + return !(value.empty()); + }); return RDB_OK; } @@ -354,44 +369,4 @@ int32_t RdbServiceProxy::Delete(const RdbSyncerParam ¶m) } return status; } - -bool RdbServiceProxy::SyncAgent::AddObserver(const std::string &storeName, const ObserverParam ¶m) -{ - bool isCreate = false; - observers.Compute(storeName, [¶m, &isCreate](const auto &key, std::list &value) { - for (const auto &element : value) { - if (element.observer == param.observer) { - LOG_ERROR("duplicate observer, storeName:%{public}s", SqliteUtils::Anonymous(key).c_str()); - return true; - } - } - value.push_back(param); - isCreate = value.size() == 1; - return true; - }); - return isCreate; -} - -std::pair RdbServiceProxy::SyncAgent::RemoveObserver( - const std::string &storeName, RdbStoreObserver *observer) -{ - RdbServiceProxy::ObserverParam observerParam; - bool isDestroy = false; - observers.ComputeIfPresent( - storeName, [observer, &observerParam, &isDestroy](const auto &key, std::list &value) { - LOG_INFO("before remove size=%{public}d", static_cast(value.size())); - value.remove_if([observer, &observerParam, &isDestroy](const ObserverParam ¶m) { - if (param.observer == observer) { - isDestroy = true; - observerParam = param; - return true; - } - return false; - }); - LOG_INFO("after remove size=%{public}d", static_cast(value.size())); - isDestroy = isDestroy && value.empty(); - return !(value.empty()); - }); - return { observerParam, isDestroy }; -} } // namespace OHOS::DistributedRdb \ No newline at end of file diff --git a/relational_store/frameworks/native/rdb/src/rdb_store_manager.cpp b/relational_store/frameworks/native/rdb/src/rdb_store_manager.cpp index 7abe3a5a..1cf2d6b1 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_store_manager.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_store_manager.cpp @@ -58,7 +58,6 @@ std::shared_ptr RdbStoreManager::GetRdbStore(const RdbStoreConfig &con { std::string path = config.GetPath(); std::lock_guard lock(mutex_); // TOD this lock should only work on storeCache_, add one more lock for connectionpool - bundleName_ = config.GetBundleName(); if (storeCache_.find(path) != storeCache_.end()) { std::shared_ptr rdbStore = storeCache_[path].lock(); if (rdbStore != nullptr && rdbStore->GetConfig() == config) { @@ -167,7 +166,6 @@ bool RdbStoreManager::Delete(const std::string &path) if (!tokens.empty()) { DistributedRdb::RdbSyncerParam param; param.storeName_ = *tokens.rbegin(); - param.bundleName_ = bundleName_; auto [err, service] = DistributedRdb::RdbManagerImpl::GetInstance().GetRdbService(param); if (err == E_OK && service != nullptr) { err = service->Delete(param); diff --git a/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp b/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp index 0b6f6402..67aede4e 100644 --- a/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp +++ b/relational_store/frameworks/native/rdb/src/sqlite_statement.cpp @@ -22,6 +22,7 @@ #include "raw_data_parser.h" #include "rdb_errno.h" #include "sqlite_errno.h" +#include "sqlite_utils.h" namespace OHOS { namespace NativeRdb { @@ -404,13 +405,13 @@ int SqliteStatement::GetColumn(int index, ValueObject &value) const int size = sqlite3_column_bytes(stmtHandle, index); auto blob = static_cast(sqlite3_column_blob(stmtHandle, index)); std::string declType = decl; - if (declType == ValueObject::DeclType()) { + if (SqliteUtils::StrToUpper(declType) == ValueObject::DeclType()) { Asset asset; RawDataParser::ParserRawData(blob, size, asset); value = std::move(asset); return E_OK; } - if (declType == ValueObject::DeclType()) { + if (SqliteUtils::StrToUpper(declType) == ValueObject::DeclType()) { Assets assets; RawDataParser::ParserRawData(blob, size, assets); value = std::move(assets); diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbStoreAssetResultSetJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbStoreAssetResultSetJsunit.test.js index f940ce76..050cf433 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbStoreAssetResultSetJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbStoreAssetResultSetJsunit.test.js @@ -374,7 +374,7 @@ describe('rdbAssetResultSetTest', function () { expect(null).assertFail(); done(); } catch (e) { - expect(e.code == 14800000).assertTrue() + expect(e.code == 401).assertTrue() done(); } }) @@ -403,7 +403,7 @@ describe('rdbAssetResultSetTest', function () { expect(null).assertFail(); done(); } catch (e) { - expect(e.code == 14800000).assertTrue() + expect(e.code == 401).assertTrue() done(); } }) diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreCallBackJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreCallBackJsunit.test.js index c47d5155..1b63ab1d 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreCallBackJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreCallBackJsunit.test.js @@ -12,53 +12,60 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility'; -const TAG = "[RELATIONAL_STORE_JSKITS_TEST]" -const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + - "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; +const TAG = "[RELATIONAL_STORE_CALLBACK_TEST]" +const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + + "name TEXT NOT NULL, age INTEGER, salary REAL, blobType BLOB)"; const STORE_CONFIG = { name: "RDBCallbackTest.db", securityLevel: data_relationalStore.SecurityLevel.S1, } -var context = ability_featureAbility.getContext() +let context = ability_featureAbility.getContext() describe('rdbStoreCallBackTest', async function () { beforeAll(function () { - console.log(TAG + 'beforeAll') + console.info(TAG, 'beforeAll') }) beforeEach(async function () { - console.log(TAG + 'beforeEach') + console.info(TAG, 'beforeEach') }) afterEach(async function () { - console.log(TAG + 'afterEach') + console.info(TAG, 'afterEach') }) afterAll(async function () { - console.log(TAG + 'afterAll') + console.info(TAG, 'afterAll') }) - console.log(TAG + "*************Unit Test Begin*************"); + console.info(TAG, "*************Unit Test Begin*************"); /** - * @tc.name rdb callback test * @tc.number testRdbStoreCallBackTest0001 - * @tc.desc rdb callback test + * @tc.name Normal test case of using database + * @tc.desc 1.Configure name and securityLevel + * 2.Execute getRdbStore + * 3.Create Table + * 4.Insert data + * 5.Query data + * 6.Execute deleteRdbStore */ it('testRdbStoreCallBackTest0001', 0, async function (done) { - console.log(TAG + "************* testRdbStoreCallBackTest0001 start *************"); + console.info(TAG, "************* testRdbStoreCallBackTest0001 start *************"); try { await data_relationalStore.getRdbStore(context, STORE_CONFIG, async (err, rdbStore) => { if (err) { - console.log("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } - console.log("Get RdbStore successfully.") + console.info(TAG, "Get RdbStore successfully.") await rdbStore.executeSql(CREATE_TABLE_TEST, null) const valueBucket = { "name": "zhangsan", @@ -67,7 +74,6 @@ describe('rdbStoreCallBackTest', async function () { "blobType": new Uint8Array([1, 2, 3]), } let rowId = await rdbStore.insert("test", valueBucket) - console.log("Insert is successful, rowId = " + rowId) let predicates = new data_relationalStore.RdbPredicates("test") predicates.equalTo("name", "zhangsan") let resultSet = await rdbStore.query(predicates, []) @@ -90,154 +96,162 @@ describe('rdbStoreCallBackTest', async function () { expect(1).assertEqual(rows) data_relationalStore.deleteRdbStore(context, "RDBCallbackTest.db", (err) => { if (err) { - console.log("Delete RdbStore is failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Delete RdbStore is failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } done() - console.log(TAG + "************* testRdbStoreCallBackTest0001 end *************") + console.info(TAG, "************* testRdbStoreCallBackTest0001 end *************") }); resultSet.close() rdbStore = null }) - } catch (e) { - console.log("catch err: Get RdbStore failed, err: code=" + e.code + " message=" + e.message) + } catch (err) { + console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } }) /** - * @tc.name rdb callback test getRdbStore err params * @tc.number testRdbStoreCallBackTest0002 - * @tc.desc rdb callback test getRdbStore err params + * @tc.name Abnormal test case of getRdbStore, configure wrong param dbname + * @tc.desc 1.Configure wrong param dbname + * 2.Execute getRdbStore */ it('testRdbStoreCallBackTest0002', 0, function (done) { - console.log(TAG + "************* testRdbStoreCallBackTest0002 start *************") + console.info(TAG, "************* testRdbStoreCallBackTest0002 start *************") try { data_relationalStore.getRdbStore(context, {dbname: "RDBCallbackTest.db", securityLevel: data_relationalStore.SecurityLevel.S1,}, (err, rdbStore) => { if (err) { - console.log("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } - console.log("Get RdbStore successfully.") + console.info(TAG, "Get RdbStore successfully.") expect(false).assertTrue() }) - } catch (e) { - console.log("catch err: Get RdbStore failed, err: code=" + e.code + " message=" + e.message) - expect("401").assertEqual(e.code) + } catch (err) { + console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect("401").assertEqual(err.code) done() - console.log(TAG + "************* testRdbStoreCallBackTest0002 end *************") + console.info(TAG, "************* testRdbStoreCallBackTest0002 end *************") } }) /** - * @tc.name rdb callback test getRdbStore err params * @tc.number testRdbStoreCallBackTest0003 - * @tc.desc rdb callback test getRdbStore err params + * @tc.name Abnormal test case of getRdbStore, if context is null + * @tc.desc 1.Configure context as null + * 2.Execute getRdbStore */ it('testRdbStoreCallBackTest0003', 0, function (done) { - console.log(TAG + "************* testRdbStoreCallBackTest0003 start *************") + console.info(TAG, "************* testRdbStoreCallBackTest0003 start *************") try { data_relationalStore.getRdbStore(null, { name: "RDBCallbackTest.db", securityLevel: data_relationalStore.SecurityLevel.S1 }, (err, rdbStore) => { if (err) { - console.log("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } - console.log("Get RdbStore successfully.") + console.info(TAG, "Get RdbStore successfully.") expect(false).assertTrue() }) - } catch (e) { - console.log("catch err: Get RdbStore failed, err: code=" + e.code + " message=" + e.message) - expect("401").assertEqual(e.code) + } catch (err) { + console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect("401").assertEqual(err.code) done() - console.log(TAG + "************* testRdbStoreCallBackTest0003 end *************") + console.info(TAG, "************* testRdbStoreCallBackTest0003 end *************") } }) /** - * @tc.name rdb callback test getRdbStore ok params * @tc.number testRdbStoreCallBackTest0004 - * @tc.desc rdb callback test getRdbStore ok params + * @tc.name Normal test case of getRdbStore + * @tc.desc 1.Configure database name and securityLevel + * 2.Execute getRdbStore */ it('testRdbStoreCallBackTest0004', 0, function (done) { - console.log(TAG + "************* testRdbStoreCallBackTest0004 start *************") + console.info(TAG, "************* testRdbStoreCallBackTest0004 start *************") try { data_relationalStore.getRdbStore(context, STORE_CONFIG, (err, rdbStore) => { if (err) { - console.log("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } rdbStore = null done() - console.log(TAG + "************* testRdbStoreCallBackTest0004 end *************") + console.info(TAG, "************* testRdbStoreCallBackTest0004 end *************") }) - } catch (e) { - console.log("catch err: Get RdbStore failed, err: code=" + e.code + " message=" + e.message) + } catch (err) { + console.error("catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } }) /** - * @tc.name rdb callback test deleteRdbStore err params * @tc.number testRdbStoreCallBackTest0005 - * @tc.desc rdb callback test deleteRdbStore err params + * @tc.name Abnormal test case of deleteRdbStore, if database name is number + * @tc.desc 1.Execute getRdbStore + * 2.Configure database name as number + * 3.Execute deleteRdbStore */ it('testRdbStoreCallBackTest0005', 0, async function (done) { - console.log(TAG + "************* testRdbStoreCallBackTest0005 start *************"); + console.info(TAG, "************* testRdbStoreCallBackTest0005 start *************"); data_relationalStore.getRdbStore(context, STORE_CONFIG).then((rdbStore) => { try { rdbStore = null data_relationalStore.deleteRdbStore(context, 12345, (err) => { if (err) { - console.log("Delete RdbStore is failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Delete RdbStore is failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } - console.log("Delete RdbStore successfully.") + console.info(TAG, "Delete RdbStore successfully.") expect(false).assertTrue() }); - } catch (e) { - console.log("catch err: Delete RdbStore failed, err: code=" + e.code + " message=" + e.message) - expect("401").assertEqual(e.code) + } catch (err) { + console.info(TAG, "catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) + expect("401").assertEqual(err.code) done() - console.log(TAG + "************* testRdbStoreCallBackTest0005 end *************"); + console.info(TAG, "************* testRdbStoreCallBackTest0005 end *************"); } - }).catch((err2) => { - console.info("Get RdbStore failed, err: code=" + err2.code + " message=" + err2.message) + }).catch((err) => { + console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() }) }) /** - * @tc.name rdb callback test deleteRdbStore OK params * @tc.number testRdbStoreCallBackTest0006 - * @tc.desc rdb callback test deleteRdbStore OK params + * @tc.name Normal test case of deleteRdbStore + * @tc.desc 1.Execute getRdbStore + * 2.Configure database name + * 3.Execute deleteRdbStore */ it('testRdbStoreCallBackTest0006', 0, async function (done) { - console.log(TAG + "************* testRdbStoreCallBackTest0006 start *************") + console.info(TAG, "************* testRdbStoreCallBackTest0006 start *************") data_relationalStore.getRdbStore(context, STORE_CONFIG).then((rdbStore) => { try { rdbStore = null data_relationalStore.deleteRdbStore(context, "RDBCallbackTest.db", (err) => { if (err) { - console.log("Delete RdbStore is failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Delete RdbStore is failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } - console.log("Delete RdbStore successfully.") + console.info(TAG, "Delete RdbStore successfully.") done() - console.log(TAG + "************* testRdbStoreCallBackTest0006 end *************") + console.info(TAG, "************* testRdbStoreCallBackTest0006 end *************") }); } catch (err) { + console.error(TAG, "Delete RdbStore is failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } }).catch((err) => { - console.info("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() }) }) - console.log(TAG + "*************Unit Test End*************"); + console.info(TAG, "*************Unit Test End*************"); }) \ No newline at end of file diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertJsunit.test.js index 38d48dbe..31a536d3 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstoreInsertJsunit.test.js @@ -336,6 +336,106 @@ describe('rdbStoreInsertTest', function () { console.log(TAG + "************* testRdbStoreInsert0007 end *************"); }) + /** + * @tc.name rdb insert test + * @tc.number SUB_DDM_AppDataFWK_JSRDB_Insert_0008 + * @tc.desc rdb insert test + */ + it('testRdbStoreInsert0008', 0, async function (done) { + console.log(TAG + "************* testRdbStoreInsert0008 start *************"); + var u8 = new Uint8Array([1, 2, 3]) + { + const valueBucket = { + "id": 1, + "name": "zhangsan", + "age": null, + "salary": undefined, + "blobType": u8, + } + await rdbStore.insert("test", valueBucket); + } + + { + const valueBucket = { + "id": 2, + "name": "lisi", + "age": 19, + "salary": 200.5, + "blobType": u8, + } + await rdbStore.insert("test", valueBucket); + } + let predicates = new data_relationalStore.RdbPredicates("test"); + let resultSet = await rdbStore.query(predicates); + try { + done() + expect(true).assertEqual(resultSet.goToFirstRow()); + expect(true).assertEqual(resultSet.isColumnNull(resultSet.getColumnIndex("age"))); + expect(true).assertEqual(resultSet.isColumnNull(resultSet.getColumnIndex("salary"))); + } catch (err) { + console.log("query error" + err); + } + + { + const valueBucket = { + "age": null, + "salary": undefined, + } + predicates.equalTo("name", "lisi") + await rdbStore.update(valueBucket, predicates) + } + + predicates.clear(); + resultSet = await rdbStore.query(predicates); + try { + done(); + expect(true).assertEqual(resultSet.goToFirstRow()); + expect(true).assertEqual(resultSet.goToNextRow()); + expect(true).assertEqual(resultSet.isColumnNull(resultSet.getColumnIndex("age"))); + expect(200.5).assertEqual(resultSet.getDouble(resultSet.getColumnIndex("salary"))); + } catch (err) { + console.log("query error" + err); + } + + resultSet.close() + resultSet = null + console.log(TAG + "************* testRdbStoreInsert0008 end *************"); + }) + + /** + * @tc.name rdb insert test + * @tc.number SUB_DDM_AppDataFWK_JSRDB_Insert_0009 + * @tc.desc rdb insert test + */ + it('testRdbStoreInsert0009', 0, async function (done) { + console.log(TAG + "************* testRdbStoreInsert0009 start *************"); + var u8 = new Uint8Array([1, 2, 3]) + { + const valueBucket = { + "name": "zhangsan", + "age": new Date(), + "salary": 100.5, + "blobType": u8, + } + try { + let insertPromise = rdbStore.insert("test", valueBucket) + insertPromise.then(async (ret) => { + done(); + expect(null).assertFail() + }).catch((err) => { + done(); + expect(null).assertFail() + }) + } catch (err) { + done(); + console.log("catch err: failed, err: code=" + err.code + " message=" + err.message) + expect("401").assertEqual(err.code) + } + } + console.log(TAG + "************* testRdbStoreInsert0009 end *************"); + }) + + /** * @tc.name rdb inserttWithConflictResolution test * @tc.number SUB_DDM_AppDataFWK_JSRDB_InsertWithConflictResolution_0001 diff --git a/relational_store/test/js/relationalstore/unittest/src/RdbstorePromiseJsunit.test.js b/relational_store/test/js/relationalstore/unittest/src/RdbstorePromiseJsunit.test.js index 709eeb63..9998916f 100644 --- a/relational_store/test/js/relationalstore/unittest/src/RdbstorePromiseJsunit.test.js +++ b/relational_store/test/js/relationalstore/unittest/src/RdbstorePromiseJsunit.test.js @@ -12,58 +12,65 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' import data_relationalStore from '@ohos.data.relationalStore'; import ability_featureAbility from '@ohos.ability.featureAbility'; const TAG = "[RELATIONAL_STORE_JSKITS_TEST]" -const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + - "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; +const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + + "name TEXT NOT NULL, age INTEGER, salary REAL, blobType BLOB)"; const STORE_CONFIG = { name: "RDBPromiseTest.db", securityLevel: data_relationalStore.SecurityLevel.S1, } -var context = ability_featureAbility.getContext() +let context = ability_featureAbility.getContext() describe('rdbStorePromiseTest', function () { beforeAll(function () { - console.info(TAG + 'beforeAll') + console.info(TAG, 'beforeAll') }) beforeEach(async function () { - console.info(TAG + 'beforeEach') + console.info(TAG, 'beforeEach') }) afterEach(async function () { - console.info(TAG + 'afterEach') + console.info(TAG, 'afterEach') }) afterAll(async function () { - console.info(TAG + 'afterAll') + console.info(TAG, 'afterAll') }) console.log(TAG + "*************Unit Test Begin*************"); + /** - * @tc.name rdb base use * @tc.number testRdbStorePromiseTest0001 - * @tc.desc rdb base use + * @tc.name Normal test case of using database + * @tc.desc 1.Configure name and securityLevel + * 2.Execute getRdbStore + * 3.Create Table + * 4.Insert data + * 5.Query data + * 6.Execute deleteRdbStore */ it('testRdbStorePromiseTest0001', 0, async function (done) { - console.log(TAG + "************* testRdbStorePromiseTest0001 start *************"); + console.info(TAG, "************* testRdbStorePromiseTest0001 start *************"); try { data_relationalStore.getRdbStore(context, STORE_CONFIG).then(async (rdbStore) => { - console.log("Get RdbStore successfully.") + console.info(TAG, "Get RdbStore successfully.") await rdbStore.executeSql(CREATE_TABLE_TEST, null) const valueBucket = { "name": "zhangsan", "age": 18, "salary": 100.5, "blobType": new Uint8Array([1, 2, 3]), - } + } await rdbStore.insert("test", valueBucket) let predicates = new data_relationalStore.RdbPredicates("test") - console.log("Create RdbPredicates OK") predicates.equalTo("name", "zhangsan") rdbStore.query(predicates, []).then((resultSet) => { expect(1).assertEqual(resultSet.rowCount) @@ -73,7 +80,6 @@ describe('rdbStorePromiseTest', function () { const age = resultSet.getLong(resultSet.getColumnIndex("age")) const salary = resultSet.getDouble(resultSet.getColumnIndex("salary")) const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) - console.log(TAG + "id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", blobType=" + blobType); expect(1).assertEqual(id); expect("zhangsan").assertEqual(name); expect(18).assertEqual(age); @@ -84,129 +90,136 @@ describe('rdbStorePromiseTest', function () { expect(false).assertEqual(resultSet.goToNextRow()) resultSet.close(); rdbStore.delete(predicates).then((rows) => { - console.log("Delete rows: " + rows) + console.info(TAG, "Delete rows: " + rows) expect(1).assertEqual(rows) data_relationalStore.deleteRdbStore(context, "RDBPromiseTest.db").then(() => { - console.log("Delete RdbStore successfully.") + console.info(TAG, "Delete RdbStore successfully.") done() - console.log(TAG + "************* testRdbStorePromiseTest0001 end *************"); + console.info(TAG, "************* testRdbStorePromiseTest0001 end *************"); }) }) }) }) } catch(err) { - console.info("catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(null).assertFail() done() - console.log(TAG + "************* testRdbStorePromiseTest0001 end *************"); + console.info(TAG, "************* testRdbStorePromiseTest0001 end *************"); } }) - + /** - * @tc.name rdb getRdbStore err params * @tc.number testRdbStorePromiseTest0002 - * @tc.desc rdb getRdbStore err params + * @tc.name Abnormal test case of getRdbStore, just configure database name + * @tc.desc 1.Configure database name + * 2.Execute getRdbStore */ it('testRdbStorePromiseTest0002', 0, async function (done) { - console.log(TAG + "************* testRdbStorePromiseTest0002 start *************") + console.info(TAG, "************* testRdbStorePromiseTest0002 start *************") try { data_relationalStore.getRdbStore(context, {dbname: "RDBCallbackTest.db"}).then((rdbStore) => { - console.log("Get RdbStore successfully.") + console.info(TAG, "Get RdbStore successfully.") expect(false).assertTrue() }).catch((err) => { - console.info("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() }) } catch(err) { - console.info("catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect("401").assertEqual(err.code) done() } done() - console.log(TAG + "************* testRdbStorePromiseTest0002 end *************") + console.info(TAG, "************* testRdbStorePromiseTest0002 end *************") }) - + /** - * @tc.name rdb getRdbStore ok params * @tc.number testRdbStorePromiseTest0003 - * @tc.desc rdb getRdbStore ok params + * @tc.name Normal test case of getRdbStore, Configure database name and securityLevel + * @tc.desc 1.Configure database name and securityLevel + * 2.Execute getRdbStore */ it('testRdbStorePromiseTest0003', 0, async function (done) { - console.log(TAG + "************* testRdbStorePromiseTest0003 start *************"); + console.info(TAG, "************* testRdbStorePromiseTest0003 start *************"); try { data_relationalStore.getRdbStore(context, STORE_CONFIG).then((rdbStore) => { - console.log("Get RdbStore successfully.") + console.info(TAG, "Get RdbStore successfully.") rdbStore = null done() }).catch((err) => { - console.info("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() }) } catch(err) { - console.info("catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } done() - console.log(TAG + "************* testRdbStorePromiseTest0003 end *************") + console.info(TAG, "************* testRdbStorePromiseTest0003 end *************") }) /** - * @tc.name rdb deleteRdbStore err params * @tc.number testRdbStorePromiseTest0004 - * @tc.desc rdb deleteRdbStore err params + * @tc.name Abnormal test case of deleteRdbStore, if database name is number + * @tc.desc 1.Execute getRdbStore + * 2.Configure database name as number + * 3.Execute deleteRdbStore */ it('testRdbStorePromiseTest0004', 0, async function (done) { - console.log(TAG + "************* testRdbStorePromiseTest0004 start *************") + console.info(TAG, "************* testRdbStorePromiseTest0004 start *************") let rdbStore = await data_relationalStore.getRdbStore(context, STORE_CONFIG) try { data_relationalStore.deleteRdbStore(context, 123454345).then((rdbStore) => { - console.log("Delete RdbStore successfully.") + console.info(TAG, "Delete RdbStore successfully.") rdbStore = null expect(false).assertTrue() }).catch((err) => { - console.info("Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() }) } catch(err) { - console.info("catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) expect("401").assertEqual(err.code) done() } done() - console.log(TAG + "************* testRdbStorePromiseTest0004 end *************") + console.info(TAG, "************* testRdbStorePromiseTest0004 end *************") }) - + /** - * @tc.name rdb deleteRdbStore OK params - * @tc.number testRdbStorePromiseTest0004 - * @tc.desc rdb deleteRdbStore OK params + * @tc.number testRdbStorePromiseTest0005 + * @tc.name Normal test case of deleteRdbStore, if param is database name + * @tc.desc 1.Execute getRdbStore + * 2.Configure database name + * 3.Execute deleteRdbStore */ it('testRdbStorePromiseTest0005', 0, async function (done) { - console.log(TAG + "************* testRdbStorePromiseTest0005 start *************"); + console.info(TAG, "************* testRdbStorePromiseTest0005 start *************"); let rdbStore = await data_relationalStore.getRdbStore(context, STORE_CONFIG) try { data_relationalStore.deleteRdbStore(context, "RDBCallbackTest.db").then((err) => { - console.log("Delete RdbStore successfully.") + console.info(TAG, "Delete RdbStore successfully.") done() }).catch((err) => { - console.info("Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() }) } catch(err) { - console.info("catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } done() - console.log(TAG + "************* testRdbStorePromiseTest0005 end *************") + console.info(TAG, "************* testRdbStorePromiseTest0005 end *************") }) /** - * @tc.name rdb getRdbStore err params * @tc.number testRdbStorePromiseTest0006 - * @tc.desc rdb getRdbStore with dataGroupId in FA mode + * @tc.name Abnormal test case of getRdbStore, if configure dataGroupId in FA mode + * @tc.desc 1.configure dataGroupId in FA mode + * 2.Execute getRdbStore */ it('testRdbStorePromiseTest0006', 0, async function (done) { - console.log(TAG + "************* testRdbStorePromiseTest0006 start *************") + console.info(TAG, "************* testRdbStorePromiseTest0006 start *************") try { const STORE_CONFIG = { name: "dataGroupId.db", @@ -215,28 +228,29 @@ describe('rdbStorePromiseTest', function () { dataGroupId: "12345678", } data_relationalStore.getRdbStore(context, STORE_CONFIG).then((rdbStore) => { - console.log("Get RdbStore successfully.") + console.info(TAG, "Get RdbStore successfully.") expect(false).assertTrue() }).catch((err) => { - console.info("Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() }) } catch (err) { - console.info("catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "catch err: Get RdbStore failed, err: code=" + err.code + " message=" + err.message) expect("14801001").assertEqual(err.code) done() } done() - console.log(TAG + "************* testRdbStorePromiseTest0006 end *************") + console.info(TAG, "************* testRdbStorePromiseTest0006 end *************") }) /** - * @tc.name rdb deleteRdbStore use storeConfig * @tc.number testRdbStorePromiseTest0007 - * @tc.desc rdb deleteRdbStore use storeConfig + * @tc.name Normal test case of deleteRdbStore, if param is STORE_CONFIG + * @tc.desc 1.Execute getRdbStore + * 2.Execute deleteRdbStore */ it('testRdbStorePromiseTest0007', 0, async function (done) { - console.log(TAG + "************* testRdbStorePromiseTest0007 start *************"); + console.info(TAG, "************* testRdbStorePromiseTest0007 start *************"); const STORE_CONFIG = { name: "dataGroupId.db", securityLevel: data_relationalStore.SecurityLevel.S1, @@ -244,19 +258,19 @@ describe('rdbStorePromiseTest', function () { await data_relationalStore.getRdbStore(context, STORE_CONFIG) try { data_relationalStore.deleteRdbStore(context, STORE_CONFIG).then((err) => { - console.log("Delete RdbStore successfully.") + console.info(TAG, "Delete RdbStore successfully.") done() }).catch((err) => { - console.info("Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() }) } catch(err) { - console.info("catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) + console.error(TAG, "catch err: Delete RdbStore failed, err: code=" + err.code + " message=" + err.message) expect(false).assertTrue() } done() - console.log(TAG + "************* testRdbStorePromiseTest0007 end *************") + console.info(TAG, "************* testRdbStorePromiseTest0007 end *************") }) - console.log(TAG + "*************Unit Test End*************"); + console.info(TAG, "*************Unit Test End*************"); }) diff --git a/relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/BUILD.gn b/relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/BUILD.gn index 54346bcb..2f6508fd 100644 --- a/relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/BUILD.gn +++ b/relational_store/test/native/rdb/fuzztest/rdbimpl_fuzzer/BUILD.gn @@ -18,7 +18,7 @@ import("//foundation/distributeddatamgr/relational_store/relational_store.gni") ##############################fuzztest########################################## ohos_fuzztest("RdbImplFuzzTest") { - module_out_path = "relational_store/nativerdb" + module_out_path = "relational_store/relational_store" include_dirs = [ "${relational_store_native_path}/rdb/include", diff --git a/relational_store/test/native/rdb/fuzztest/rdbstore_fuzzer/BUILD.gn b/relational_store/test/native/rdb/fuzztest/rdbstore_fuzzer/BUILD.gn index bd277be0..a30acba3 100644 --- a/relational_store/test/native/rdb/fuzztest/rdbstore_fuzzer/BUILD.gn +++ b/relational_store/test/native/rdb/fuzztest/rdbstore_fuzzer/BUILD.gn @@ -18,7 +18,7 @@ import("//foundation/distributeddatamgr/relational_store/relational_store.gni") ##############################fuzztest########################################## ohos_fuzztest("RdbStoreFuzzTest") { - module_out_path = "relational_store/nativerdb" + module_out_path = "relational_store/relational_store" include_dirs = [ "${relational_store_native_path}/rdb/include" ] diff --git a/relational_store/test/native/rdb/unittest/rdb_store_impl_test.cpp b/relational_store/test/native/rdb/unittest/rdb_store_impl_test.cpp index 69990fa8..6832d09a 100644 --- a/relational_store/test/native/rdb/unittest/rdb_store_impl_test.cpp +++ b/relational_store/test/native/rdb/unittest/rdb_store_impl_test.cpp @@ -267,8 +267,8 @@ HWTEST_F(RdbStoreImplTest, Rdb_RemoteQueryTest_001, TestSize.Level2) EXPECT_EQ(E_OK, errCode); // GetRdbService succeeded if configuration file has already been configured - ret = RdbStoreImplTest::store->RemoteQuery("", predicates, {}, errCode); - EXPECT_NE(E_OK, errCode); + ret = store->RemoteQuery("", predicates, {}, errCode); + EXPECT_EQ(E_OK, errCode); EXPECT_EQ(nullptr, ret); RdbHelper::DeleteRdbStore(RdbStoreImplTest::DATABASE_NAME); @@ -325,13 +325,13 @@ HWTEST_F(RdbStoreImplTest, Rdb_BackupTest_001, TestSize.Level2) EXPECT_EQ(E_OK, errCode); // isEncrypt_ is true, and destEncryptKey is not emtpy - errCode = RdbStoreImplTest::store->Backup(databasePath, destEncryptKey); + errCode = store->Backup(databasePath, destEncryptKey); EXPECT_EQ(E_OK, errCode); RdbHelper::DeleteRdbStore(databasePath); // isEncrypt_ is true, and destEncryptKey is not emtpy destEncryptKey.pop_back(); - errCode = RdbStoreImplTest::store->Backup(databasePath, destEncryptKey); + errCode = store->Backup(databasePath, destEncryptKey); EXPECT_EQ(E_OK, errCode); RdbHelper::DeleteRdbStore(databasePath); RdbHelper::DeleteRdbStore(DATABASE_NAME); diff --git a/udmf/framework/innerkitsimpl/test/fuzztest/udmfclient_fuzzer/BUILD.gn b/udmf/framework/innerkitsimpl/test/fuzztest/udmfclient_fuzzer/BUILD.gn index 0d066a76..c35490fb 100644 --- a/udmf/framework/innerkitsimpl/test/fuzztest/udmfclient_fuzzer/BUILD.gn +++ b/udmf/framework/innerkitsimpl/test/fuzztest/udmfclient_fuzzer/BUILD.gn @@ -18,7 +18,7 @@ import("//foundation/distributeddatamgr/udmf/udmf.gni") ##############################fuzztest########################################## ohos_fuzztest("UdmfClientFuzzTest") { - module_out_path = "udmf/innerkitsImpl" + module_out_path = "udmf/udmf" include_dirs = [ "${udmf_interfaces_path}/innerkits/client", diff --git a/udmf/framework/service/udmf_service_client.cpp b/udmf/framework/service/udmf_service_client.cpp index 1d2a8875..939f1cce 100644 --- a/udmf/framework/service/udmf_service_client.cpp +++ b/udmf/framework/service/udmf_service_client.cpp @@ -16,6 +16,7 @@ #include "udmf_service_client.h" #include "iservice_registry.h" +#include "datamgr_service_proxy.h" #include "system_ability_definition.h" #include "logger.h" @@ -66,7 +67,7 @@ sptr UdmfServiceClient::GetDistributedKvData } auto remote = samgr->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); - kvDataServiceProxy_ = iface_cast(remote); + kvDataServiceProxy_ = iface_cast(remote); if (kvDataServiceProxy_ == nullptr) { LOG_ERROR(UDMF_SERVICE, "initialize proxy failed."); return nullptr; diff --git a/udmf/interfaces/innerkits/BUILD.gn b/udmf/interfaces/innerkits/BUILD.gn index 09e2d256..03701aa6 100644 --- a/udmf/interfaces/innerkits/BUILD.gn +++ b/udmf/interfaces/innerkits/BUILD.gn @@ -26,6 +26,7 @@ config("udmf_client_config") { "//third_party/node/src", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/include", "${kv_store_path}/frameworks/innerkitsimpl/distributeddatafwk/src", + "${kv_store_path}/frameworks/innerkitsimpl/distributeddatasvc/include", "${kv_store_path}/interfaces/innerkits/distributeddata/include", ] } @@ -68,6 +69,7 @@ ohos_shared_library("udmf_client") { "hitrace:libhitracechain", "ipc:ipc_core", "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", "samgr:samgr_proxy", ] diff --git a/udmf/interfaces/jskits/common/napi_data_utils.h b/udmf/interfaces/jskits/common/napi_data_utils.h index 01b28c23..bc19dd56 100644 --- a/udmf/interfaces/jskits/common/napi_data_utils.h +++ b/udmf/interfaces/jskits/common/napi_data_utils.h @@ -23,9 +23,9 @@ #include #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_common_want.h" #include "securec.h" diff --git a/udmf/interfaces/jskits/common/napi_error_utils.h b/udmf/interfaces/jskits/common/napi_error_utils.h index c75ac461..51a52640 100644 --- a/udmf/interfaces/jskits/common/napi_error_utils.h +++ b/udmf/interfaces/jskits/common/napi_error_utils.h @@ -21,7 +21,7 @@ #include #include "js_native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" +#include "napi/native_common.h" #include "error_code.h" #include "logger.h" diff --git a/udmf/interfaces/jskits/common/napi_queue.h b/udmf/interfaces/jskits/common/napi_queue.h index e2c78c75..093ef7b5 100644 --- a/udmf/interfaces/jskits/common/napi_queue.h +++ b/udmf/interfaces/jskits/common/napi_queue.h @@ -20,9 +20,9 @@ #include #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_common.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" #include "napi_error_utils.h" namespace OHOS { diff --git a/udmf/interfaces/jskits/data/application_defined_record_napi.h b/udmf/interfaces/jskits/data/application_defined_record_napi.h index 4791117a..ff12f1c2 100644 --- a/udmf/interfaces/jskits/data/application_defined_record_napi.h +++ b/udmf/interfaces/jskits/data/application_defined_record_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/audio_napi.h b/udmf/interfaces/jskits/data/audio_napi.h index eee3cad0..89b0fc69 100644 --- a/udmf/interfaces/jskits/data/audio_napi.h +++ b/udmf/interfaces/jskits/data/audio_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/file_napi.h b/udmf/interfaces/jskits/data/file_napi.h index 527133b1..b76eb679 100644 --- a/udmf/interfaces/jskits/data/file_napi.h +++ b/udmf/interfaces/jskits/data/file_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/folder_napi.h b/udmf/interfaces/jskits/data/folder_napi.h index 49cc3b66..39199115 100644 --- a/udmf/interfaces/jskits/data/folder_napi.h +++ b/udmf/interfaces/jskits/data/folder_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/html_napi.h b/udmf/interfaces/jskits/data/html_napi.h index 69920f7f..8807a26b 100644 --- a/udmf/interfaces/jskits/data/html_napi.h +++ b/udmf/interfaces/jskits/data/html_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/image_napi.h b/udmf/interfaces/jskits/data/image_napi.h index 02962536..fb7589ff 100644 --- a/udmf/interfaces/jskits/data/image_napi.h +++ b/udmf/interfaces/jskits/data/image_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/link_napi.h b/udmf/interfaces/jskits/data/link_napi.h index d3db14e1..081457d1 100644 --- a/udmf/interfaces/jskits/data/link_napi.h +++ b/udmf/interfaces/jskits/data/link_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/plain_text_napi.h b/udmf/interfaces/jskits/data/plain_text_napi.h index b0b48bfa..67620600 100644 --- a/udmf/interfaces/jskits/data/plain_text_napi.h +++ b/udmf/interfaces/jskits/data/plain_text_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/summary_napi.h b/udmf/interfaces/jskits/data/summary_napi.h index d4f70336..069cabf8 100644 --- a/udmf/interfaces/jskits/data/summary_napi.h +++ b/udmf/interfaces/jskits/data/summary_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/system_defined_appitem_napi.h b/udmf/interfaces/jskits/data/system_defined_appitem_napi.h index 5f641ba4..deef6081 100644 --- a/udmf/interfaces/jskits/data/system_defined_appitem_napi.h +++ b/udmf/interfaces/jskits/data/system_defined_appitem_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/system_defined_form_napi.h b/udmf/interfaces/jskits/data/system_defined_form_napi.h index 01d77565..191ba59a 100644 --- a/udmf/interfaces/jskits/data/system_defined_form_napi.h +++ b/udmf/interfaces/jskits/data/system_defined_form_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/system_defined_pixelmap_napi.h b/udmf/interfaces/jskits/data/system_defined_pixelmap_napi.h index 58258090..eb64b3ba 100644 --- a/udmf/interfaces/jskits/data/system_defined_pixelmap_napi.h +++ b/udmf/interfaces/jskits/data/system_defined_pixelmap_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/system_defined_record_napi.h b/udmf/interfaces/jskits/data/system_defined_record_napi.h index 16594273..8881c49c 100644 --- a/udmf/interfaces/jskits/data/system_defined_record_napi.h +++ b/udmf/interfaces/jskits/data/system_defined_record_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/text_napi.h b/udmf/interfaces/jskits/data/text_napi.h index 8c5fd6c4..110f12d4 100644 --- a/udmf/interfaces/jskits/data/text_napi.h +++ b/udmf/interfaces/jskits/data/text_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/unified_data_channel_napi.h b/udmf/interfaces/jskits/data/unified_data_channel_napi.h index 718fc86a..81534559 100644 --- a/udmf/interfaces/jskits/data/unified_data_channel_napi.h +++ b/udmf/interfaces/jskits/data/unified_data_channel_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/unified_data_napi.h b/udmf/interfaces/jskits/data/unified_data_napi.h index c2c5d6d5..f9cd9bed 100644 --- a/udmf/interfaces/jskits/data/unified_data_napi.h +++ b/udmf/interfaces/jskits/data/unified_data_napi.h @@ -18,7 +18,7 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" +#include "napi/native_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/unified_record_napi.h b/udmf/interfaces/jskits/data/unified_record_napi.h index 4c001936..c3833df7 100644 --- a/udmf/interfaces/jskits/data/unified_record_napi.h +++ b/udmf/interfaces/jskits/data/unified_record_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/uniform_type_descriptor_napi.h b/udmf/interfaces/jskits/data/uniform_type_descriptor_napi.h index 2f005441..3553fcfb 100644 --- a/udmf/interfaces/jskits/data/uniform_type_descriptor_napi.h +++ b/udmf/interfaces/jskits/data/uniform_type_descriptor_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { diff --git a/udmf/interfaces/jskits/data/video_napi.h b/udmf/interfaces/jskits/data/video_napi.h index 4d154527..a848f04d 100644 --- a/udmf/interfaces/jskits/data/video_napi.h +++ b/udmf/interfaces/jskits/data/video_napi.h @@ -18,8 +18,8 @@ #include -#include "innerkits/napi/ace_napi/include/napi/native_api.h" -#include "innerkits/napi/ace_napi/include/napi/native_node_api.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { namespace UDMF { -- Gitee