From fcd1a921698353119ee208f739d0faabf9f51bc4 Mon Sep 17 00:00:00 2001 From: ding_dong_dong Date: Tue, 4 Jul 2023 10:06:43 +0800 Subject: [PATCH] add udmf --- CMakeLists.txt | 3 +- bin/update/updata.bat | 6 +- data_object/bundle.json | 19 +- data_object/data_object.gni | 14 + .../adaptor/distributed_objectstore_impl.h | 1 + .../innerkitsimpl/include/common/logger.h | 67 +- .../include/communicator/visibility.h | 8 +- .../src/adaptor/distributed_object_impl.cpp | 8 +- .../adaptor/distributed_object_store_impl.cpp | 8 +- data_object/interfaces/innerkits/BUILD.gn | 8 +- data_object/interfaces/jskits/BUILD.gn | 10 +- data_share/CMakeLists.txt | 31 +- data_share/bundle.json | 37 +- .../js/napi/common/include/datashare_error.h | 2 + .../common/include/datashare_error_impl.h | 14 + .../napi/common/include/datashare_js_utils.h | 6 +- .../common/include/napi_callbacks_manager.h | 187 ++ .../napi/common/src/datashare_error_impl.cpp | 20 + .../js/napi/common/src/datashare_js_utils.cpp | 112 +- .../common/src/datashare_predicates_proxy.cpp | 4 +- .../frameworks/js/napi/dataShare/BUILD.gn | 14 +- .../dataShare/src/napi_datashare_helper.cpp | 26 +- .../include/napi_subscriber_manager.h | 70 +- .../js/napi/observer/src/napi_observer.cpp | 2 +- .../observer/src/napi_subscriber_manager.cpp | 44 +- .../native/common/include/base_proxy.h | 227 -- .../native/common/include/callbacks_manager.h | 239 +- .../native/common/include/datashare_log.h | 82 +- .../include/idata_share_service.h | 65 +- .../native/common/include/idatashare.h | 41 +- .../common/include/ikvstore_data_service.h | 49 + .../native/common/include/itypes_utils.h | 292 --- .../common/src/datashare_abs_result_set.cpp | 2 +- .../native/common/src/datashare_template.cpp | 137 ++ .../common/src/ikvstore_data_service.cpp | 55 + .../native/common/src/itypes_utils.cpp | 172 -- .../controller/common/general_controller.h | 58 +- .../provider/include/ext_special_controller.h | 55 + .../general_controller_porvider_impl.h | 55 + .../provider/src/ext_special_controller.cpp | 148 ++ .../src/general_controller_provider_impl.cpp | 122 + .../include/general_controller_service_impl.h | 49 + .../include/persistent_data_controller.h | 49 + .../include/published_data_controller.h | 50 + .../src/general_controller_service_impl.cpp | 94 + .../src/persistent_data_controller.cpp | 92 + .../service/src/published_data_controller.cpp | 91 + .../consumer/include/datashare_connection.h | 9 +- .../consumer/include/datashare_helper_impl.h | 102 + .../native/consumer/include/datashare_proxy.h | 34 +- .../consumer/src/connection_factory.cpp | 68 - .../consumer/src/datashare_connection.cpp | 17 +- .../native/consumer/src/datashare_helper.cpp | 869 +------ .../consumer/src/datashare_helper_impl.cpp | 352 +++ .../native/consumer/src/datashare_proxy.cpp | 68 - .../native/provider/include/datashare_stub.h | 23 +- .../provider/include/datashare_stub_impl.h | 20 - .../include/js_datashare_ext_ability.h | 11 +- .../native/provider/src/datashare_stub.cpp | 68 - .../provider/src/datashare_stub_impl.cpp | 69 - .../provider/src/js_datashare_ext_ability.cpp | 119 +- .../proxy/include/data_share_manager_impl.h | 38 +- .../proxy/include/data_share_service_proxy.h | 36 +- .../published_data_subscriber_manager.h | 39 +- .../proxy/include/rdb_subscriber_manager.h | 38 +- .../proxy/src/data_share_manager_impl.cpp | 98 +- .../proxy/src/data_share_service_proxy.cpp | 54 +- .../src/published_data_subscriber_manager.cpp | 105 +- .../proxy/src/rdb_subscriber_manager.cpp | 99 +- data_share/interfaces/inner_api/BUILD.gn | 11 +- .../interfaces/inner_api/common/BUILD.gn | 6 +- .../common/include/datashare_errno.h | 5 + .../include/datashare_predicates_objects.h | 3 +- .../common/include/datashare_template.h | 124 +- .../common/include/datashare_values_bucket.h | 3 +- .../inner_api/common/libdatashare_common.map | 2 + .../consumer/include/datashare_helper.h | 100 +- .../consumer/libdatashare_consumer.map | 3 + data_share/test/native/BUILD.gn | 54 +- .../DataShareExtAbility.ts | 30 +- .../native/resource/ohos_test/ohos_test.xml | 9 + .../proxydatas_with_permission_test.cpp | 279 ++- .../include/mediadatashare_unit_test.h | 5 +- .../src/mediadatashare_unit_test.cpp | 495 ++-- datamgr_service/bundle.json | 59 +- datamgr_service/conf/BUILD.gn | 5 +- datamgr_service/datamgr_service.gni | 5 + .../distributeddataservice/adapter/BUILD.gn | 1 - .../adapter/CMakeLists.txt | 23 +- .../src/account_delegate_default_impl.cpp | 2 +- .../account/src/account_delegate_impl.cpp | 3 - .../adapter/autils/src/constant.cpp | 124 - .../adapter/autils/src/directory_utils.cpp | 164 -- .../thread_pool/kv_store_thread_pool_impl.cpp | 111 - .../unittest/kv_store_thread_pool_test.cpp | 130 -- .../communicator/src/softbus_adapter.h | 1 - .../src/softbus_adapter_standard.cpp | 2 +- .../adapter/dfx/BUILD.gn | 5 +- .../adapter/dfx/test/BUILD.gn | 2 - .../adapter/include/autils/constant.h | 184 -- .../include/permission/permission_validator.h | 2 + .../permission/src/permission_validator.cpp | 7 + .../adapter/test/BUILD.gn | 1 - .../distributeddataservice/app/BUILD.gn | 2 +- .../app/distributed_data.cfg | 2 +- .../app/src/dump_helper.cpp | 38 +- .../app/src/flowctrl_manager/BUILD.gn | 1 - .../app/src/kvstore_data_service.cpp | 55 +- .../app/src/kvstore_data_service.h | 38 +- .../app/src/kvstore_meta_manager.cpp | 3 +- .../app/src/kvstore_meta_manager.h | 2 +- .../app/src/security/security.cpp | 3 +- .../src/session_manager/upgrade_manager.cpp | 5 +- .../app/src/task_manager.cpp | 3 +- .../app/src/uninstaller/uninstaller_impl.cpp | 8 +- .../app/src/uninstaller/uninstaller_impl.h | 5 +- .../kvstore_flowctrl_manager_test.cpp | 8 +- .../distributeddataservice/framework/BUILD.gn | 3 + .../framework/cloud/asset_loader.cpp | 8 +- .../framework/cloud/cloud_db.cpp | 5 + .../framework/cloud/cloud_event.cpp | 11 +- .../framework/cloud/cloud_info.cpp | 39 +- .../framework/cloud/schema_meta.cpp | 31 +- .../framework/cloud/sync_event.cpp | 72 +- .../framework/include/cloud/asset_loader.h | 6 +- .../framework/include/cloud/change_event.h | 30 + .../framework/include/cloud/cloud_db.h | 2 + .../framework/include/cloud/cloud_event.h | 9 +- .../framework/include/cloud/cloud_info.h | 9 +- .../framework/include/cloud/schema_meta.h | 59 +- .../framework/include/cloud/sync_event.h | 52 + .../framework/include/error/general_error.h | 3 + .../include/metadata/store_meta_data.h | 1 + .../include/serializable/serializable.h | 1 + .../framework/include/store/auto_cache.h | 5 +- .../framework/include/store/cursor.h | 2 + .../framework/include/store/general_store.h | 32 +- .../framework/include/store/general_value.h | 47 +- .../framework/include/store/general_watcher.h | 29 +- .../framework/include/utils/constant.h | 41 +- .../include/utils}/ref_count.h | 7 +- .../framework/metadata/store_meta_data.cpp | 6 + .../metadata/store_meta_data_local.cpp | 4 +- .../framework/serializable/serializable.cpp | 6 + .../framework/store/auto_cache.cpp | 50 +- .../framework/utils/constant.cpp | 14 +- .../kvdb => framework/utils}/ref_count.cpp | 4 +- .../sa_profile/1301.json | 12 + .../sa_profile/1301.xml | 26 - .../distributeddataservice/service/BUILD.gn | 9 +- .../service/CMakeLists.txt | 35 +- .../service/backup/src/backup_manager.cpp | 2 +- .../service/cloud/cloud_service_impl.cpp | 317 ++- .../service/cloud/cloud_service_impl.h | 36 +- .../service/cloud/cloud_service_stub.cpp | 7 + .../service/cloud/sync_manager.cpp | 310 +++ .../service/cloud/sync_manager.h | 87 + .../service/data_share/BUILD.gn | 12 +- .../data_share/common/app_connect_manager.cpp | 58 + .../app_connect_manager.h} | 72 +- .../service/data_share/common/callback_impl.h | 2 +- .../service/data_share/common/context.h | 4 +- .../service/data_share/common/db_delegate.cpp | 18 +- .../service/data_share/common/db_delegate.h | 14 +- .../extension_connect_adaptor.cpp} | 171 +- .../common/extension_connect_adaptor.h | 34 +- .../service/data_share/common/kv_delegate.cpp | 51 +- .../service/data_share/common/kv_delegate.h | 10 +- .../data_share/common/rdb_delegate.cpp | 14 +- .../service/data_share/common/rdb_delegate.h | 2 +- .../data_share/common/scheduler_manager.cpp | 76 +- .../data_share/common/scheduler_manager.h | 22 +- .../data_share/common/seq_strategy.cpp | 5 +- .../service/data_share/common/uri_utils.cpp | 46 +- .../service/data_share/common/uri_utils.h | 3 +- .../data_share/data/published_data.cpp | 99 +- .../service/data_share/data/published_data.h | 18 +- .../data/resultset_json_formatter.cpp | 63 +- .../data/resultset_json_formatter.h | 1 + .../service/data_share/data/template_data.cpp | 62 +- .../service/data_share/data/template_data.h | 13 +- .../data_share/data_share_service_impl.cpp | 209 +- .../data_share/data_share_service_impl.h | 20 +- .../data_share/data_share_service_stub.cpp | 15 +- .../data_share/data_share_service_stub.h | 4 +- .../data_share/datamgr_service_data_share.gni | 23 + .../src/common/include/document_type.h | 34 + .../src/common/include/json_common.h | 6 +- .../gaussdb_rd/src/common/src/db_config.cpp | 12 +- .../gaussdb_rd/src/common/src/json_common.cpp | 178 +- .../src/executor/document/check_common.h | 8 +- .../src/interface/include/document_store.h | 15 +- .../src/interface/include/projection_tree.h | 3 +- .../src/interface/include/result_set.h | 17 +- .../src/interface/include/result_set_common.h | 5 +- .../src/interface/src/collection.cpp | 7 +- .../src/interface/src/document_store.cpp | 526 +++-- .../src/interface/src/projection_tree.cpp | 4 +- .../src/interface/src/result_set.cpp | 137 +- .../src/interface/src/result_set_common.cpp | 20 +- .../src/oh_adapter/src/json_object.cpp | 26 +- .../src/oh_adapter/src/kv_store_manager.cpp | 5 +- .../src/sqlite_store_executor_impl.cpp | 5 +- .../src/oh_adapter/src/sqlite_utils.cpp | 12 +- .../test/unittest/api/documentdb_api_test.cpp | 14 +- .../api/documentdb_collection_test.cpp | 2 +- .../unittest/api/documentdb_data_test.cpp | 10 +- .../unittest/api/documentdb_find_test.cpp | 4 +- .../unittest/api/documentdb_insert_test.cpp | 8 +- .../documentdb_json_common_test.cpp | 39 +- .../oh_adapter/documentdb_jsonobject_test.cpp | 2 +- .../service/data_share/idata_share_service.h | 4 +- ...d_config_from_data_proxy_node_strategy.cpp | 9 + .../data_share/strategies/delete_strategy.cpp | 23 +- .../data_share/strategies/delete_strategy.h | 6 +- .../general/cross_permission_strategy.cpp | 38 + ...strategy.h => cross_permission_strategy.h} | 62 +- .../general/load_config_common_strategy.cpp | 20 +- .../load_config_data_info_strategy.cpp | 15 +- .../general/permission_strategy.cpp | 2 +- .../strategies/get_data_strategy.cpp | 76 +- .../data_share/strategies/get_data_strategy.h | 7 +- .../data_share/strategies/insert_strategy.cpp | 22 +- .../data_share/strategies/insert_strategy.h | 6 +- .../strategies/publish_strategy.cpp | 24 +- .../data_share/strategies/publish_strategy.h | 2 +- .../data_share/strategies/query_strategy.cpp | 22 +- .../data_share/strategies/query_strategy.h | 6 +- .../strategies/subscribe_strategy.cpp | 29 +- .../strategies/subscribe_strategy.h | 6 +- .../strategies/template_strategy.cpp} | 70 +- .../data_share/strategies/template_strategy.h | 35 + .../data_share/strategies/update_strategy.cpp | 22 +- .../data_share/strategies/update_strategy.h | 6 +- .../published_data_subscriber_manager.cpp | 241 ++ .../published_data_subscriber_manager.h} | 205 +- .../rdb_subscriber_manager.cpp} | 824 +++---- .../rdb_subscriber_manager.h | 101 + .../service/kvdb/auth_delegate.cpp | 2 +- .../service/kvdb/kvdb_service_impl.cpp | 46 +- .../service/kvdb/kvdb_service_impl.h | 3 +- .../service/kvdb/kvdb_service_stub.cpp | 70 +- .../service/kvdb/kvstore_sync_manager.h | 4 +- .../service/kvdb/store_cache.cpp | 17 +- .../service/kvdb/store_cache.h | 4 +- .../service/kvdb/upgrade.h | 2 +- .../service/matrix/src/device_matrix.cpp | 2 +- .../service/object/object_service_impl.cpp | 13 +- .../service/object/object_service_impl.h | 2 + .../permission/src/permit_delegate.cpp | 2 +- .../service/rdb/rdb_asset_loader.cpp | 64 + .../service/rdb/rdb_asset_loader.h | 43 + .../service/rdb/rdb_cloud.cpp | 138 ++ .../service/rdb/rdb_cloud.h | 48 + .../service/rdb/rdb_cloud_data_translate.cpp | 177 ++ .../service/rdb/rdb_cloud_data_translate.h | 51 + .../service/rdb/rdb_cursor.cpp | 110 + .../service/rdb/rdb_cursor.h | 42 + .../service/rdb/rdb_general_store.cpp | 212 +- .../service/rdb/rdb_general_store.h | 53 +- .../service/rdb/rdb_notifier_proxy.cpp | 8 +- .../service/rdb/rdb_notifier_proxy.h | 4 +- .../service/rdb/rdb_query.cpp | 5 + .../service/rdb/rdb_query.h | 7 +- .../service/rdb/rdb_service_impl.cpp | 463 ++-- .../service/rdb/rdb_service_impl.h | 96 +- .../service/rdb/rdb_service_stub.cpp | 97 +- .../service/rdb/rdb_service_stub.h | 24 - .../service/rdb/rdb_store_observer_impl.cpp | 6 +- .../service/rdb/rdb_store_observer_impl.h | 7 +- .../service/rdb/rdb_syncer.cpp | 240 +- .../service/rdb/rdb_syncer.h | 33 +- .../service/rdb/rdb_watcher.cpp | 37 +- .../service/rdb/rdb_watcher.h | 18 +- .../service/rdb/value_proxy.cpp | 395 ++++ .../service/rdb/value_proxy.h | 221 ++ .../service/test/BUILD.gn | 33 + .../service/test/cloud_data_test.cpp | 76 +- .../service/test/crypto_manager_test.cpp | 3 + .../service/test/mock/db_store_mock.cpp | 10 +- .../service/test/value_proxy_test.cpp | 247 ++ .../service/udmf/BUILD.gn | 74 + .../service/udmf/data_manager.cpp | 343 +++ .../udmf/data_manager.h} | 63 +- .../udmf/lifecycle/clean_after_get.cpp} | 16 +- .../service/udmf/lifecycle/clean_after_get.h | 26 + .../lifecycle/clean_on_startup.cpp} | 60 +- .../service/udmf/lifecycle/clean_on_startup.h | 28 + .../udmf/lifecycle/clean_on_timeout.cpp | 30 + .../service/udmf/lifecycle/clean_on_timeout.h | 28 + .../udmf/lifecycle/lifecycle_manager.cpp | 92 + .../udmf/lifecycle/lifecycle_manager.h | 47 + .../udmf/lifecycle/lifecycle_policy.cpp | 101 + .../service/udmf/lifecycle/lifecycle_policy.h | 45 + .../udmf/permission/checker_manager.cpp | 58 + .../service/udmf/permission/checker_manager.h | 51 + .../udmf/permission/data_checker.cpp} | 38 +- .../udmf/permission/data_checker.h} | 35 +- .../permission/uri_permission_manager.cpp | 46 + .../udmf/permission/uri_permission_manager.h | 22 +- .../udmf/preprocess/preprocess_utils.cpp | 104 + .../udmf/preprocess/preprocess_utils.h | 43 + .../same_process_ipc_guard.h} | 43 +- .../service/udmf/store/runtime_store.cpp | 303 +++ .../service/udmf/store/runtime_store.h | 59 + .../udmf/store/store.h} | 52 +- .../service/udmf/store/store_cache1.cpp | 49 + .../service/udmf/store/store_cache1.h | 28 +- .../service/udmf/udmf_service_impl.cpp | 108 + .../service/udmf/udmf_service_impl.h | 76 +- .../service/udmf/udmf_service_stub.cpp | 269 +++ .../service/udmf/udmf_service_stub.h | 60 + kv_store/bundle.json | 51 +- kv_store/frameworks/CMakeLists.txt | 31 +- kv_store/frameworks/common/executor.h | 1 - kv_store/frameworks/common/itypes_util.h | 7 +- kv_store/frameworks/common/log_print.h | 57 +- .../common/test/executor_pool_test.cpp | 5 +- .../frameworks/common/test/traits_test.cpp | 6 +- kv_store/frameworks/common/traits.h | 49 +- .../test/unittest/device_kvstore_test.cpp | 31 +- ...stributed_kv_data_manager_encrypt_test.cpp | 3 + .../local_subscribe_device_store_test.cpp | 7 +- .../unittest/local_subscribe_store_test.cpp | 7 +- .../single_kvstore_client_query_test.cpp | 3 + .../unittest/single_kvstore_client_test.cpp | 31 +- .../kvdb/include/task_executor.h | 2 +- .../innerkitsimpl/kvdb/src/backup_manager.cpp | 6 +- .../kvdb/src/kvdb_service_client.cpp | 32 +- .../kvdb/src/single_store_impl.cpp | 55 +- .../innerkitsimpl/kvdb/src/store_factory.cpp | 8 +- .../innerkitsimpl/kvdb/src/store_manager.cpp | 11 +- .../kvdb/test/backup_manager_test.cpp | 3 + .../kvdb/test/single_store_impl_test.cpp | 3 + .../kvdb/test/store_factory_test.cpp | 4 + .../distributeddata/include/js_field_node.h | 22 +- .../distributeddata/include/js_kv_store.h | 4 +- .../include/js_kv_store_resultset.h | 1 - .../distributeddata/include/js_query.h | 2 +- .../distributeddata/include/js_schema.h | 14 +- .../distributeddata/include/js_util.h | 23 +- .../distributeddata/include/napi_queue.h | 3 +- .../distributeddata/include/uv_queue.h | 2 +- .../src/js_const_properties.cpp | 4 +- .../src/js_device_kv_store.cpp | 8 +- .../distributeddata/src/js_field_node.cpp | 50 +- .../distributeddata/src/js_kv_manager.cpp | 4 +- .../distributeddata/src/js_kv_store.cpp | 4 +- .../src/js_kv_store_resultset.cpp | 4 +- .../distributeddata/src/js_query.cpp | 6 +- .../distributeddata/src/js_schema.cpp | 58 +- .../src/js_single_kv_store.cpp | 12 +- .../distributeddata/src/js_util.cpp | 86 +- .../include/js_error_utils.h | 2 +- .../include/js_field_node.h | 22 +- .../include/js_kv_store_resultset.h | 1 - .../distributedkvstore/include/js_query.h | 2 +- .../distributedkvstore/include/js_schema.h | 14 +- .../include/js_single_kv_store.h | 2 +- .../distributedkvstore/include/js_util.h | 35 +- .../distributedkvstore/include/uv_queue.h | 2 +- .../src/js_const_properties.cpp | 2 +- .../src/js_device_kv_store.cpp | 55 +- .../distributedkvstore/src/js_error_utils.cpp | 4 +- .../distributedkvstore/src/js_field_node.cpp | 72 +- .../distributedkvstore/src/js_kv_manager.cpp | 22 +- .../src/js_kv_store_resultset.cpp | 43 +- .../distributedkvstore/src/js_query.cpp | 66 +- .../distributedkvstore/src/js_schema.cpp | 70 +- .../src/js_single_kv_store.cpp | 153 +- .../distributedkvstore/src/js_util.cpp | 144 +- kv_store/frameworks/libs/CMakeLists.txt | 34 +- .../frameworks/libs/distributeddb/BUILD.gn | 5 + .../common/include/auto_launch.h | 17 +- .../common/include/cloud/cloud_db_constant.h | 39 + .../common/include/cloud/cloud_db_types.h | 79 + .../distributeddb/common/include/db_common.h | 5 + .../common/include/db_constant.h | 1 + .../distributeddb/common/include/db_errno.h | 3 + .../distributeddb/common/include/db_types.h | 4 + .../relational/relational_row_data_set.h | 1 - .../common/include/relational/table_info.h | 2 - .../common/include/runtime_context.h | 15 +- .../distributeddb/common/src/auto_launch.cpp | 147 +- .../distributeddb/common/src/db_common.cpp | 2 +- .../common/src/evloop/src/event_impl.cpp | 3 - .../libs/distributeddb/common/src/query.cpp | 26 + .../common/src/query_expression.cpp | 20 + .../relational/relational_row_data_set.cpp | 13 - .../common/src/relational/table_info.cpp | 21 +- .../common/src/runtime_context_impl.cpp | 88 +- .../common/src/runtime_context_impl.h | 19 +- .../common/src/time_tick_monitor.cpp | 5 +- .../common/src/time_tick_monitor.h | 3 +- .../include/communicator_aggregator.h | 11 +- .../include/send_task_scheduler.h | 1 + .../communicator/src/communicator.cpp | 17 +- .../src/communicator_aggregator.cpp | 58 +- .../communicator/src/communicator_linker.cpp | 7 +- .../communicator/src/frame_retainer.cpp | 2 +- .../communicator/src/network_adapter.cpp | 4 + .../communicator/src/protocol_proto.cpp | 4 +- .../libs/distributeddb/distributeddb.gni | 11 + .../libs/distributeddb/include/query.h | 12 + .../distributeddb/include/query_expression.h | 8 + .../include/cloud/cloud_store_types.h | 110 +- .../interfaces/include/cloud/iAssetLoader.h | 44 + .../include/cloud/icloud_data_translate.h | 37 + .../interfaces/include/cloud/icloud_db.h | 49 + .../interfaces/include/ithread_pool.h | 2 +- .../include/kv_store_delegate_manager.h | 2 + .../relational/relational_store_delegate.h | 32 +- .../relational/relational_store_manager.h | 5 +- .../interfaces/include/runtime_config.h | 17 + .../interfaces/include/store_changed_data.h | 2 + .../interfaces/include/store_observer.h | 34 +- .../interfaces/include/store_types.h | 35 +- .../src/kv_store_delegate_manager.cpp | 13 +- .../interfaces/src/kv_store_errno.cpp | 2 + .../src/kv_store_nb_delegate_impl.cpp | 8 + .../relational_store_changed_data_impl.h | 1 + .../relational_store_delegate_impl.cpp | 111 +- .../relational_store_delegate_impl.h | 18 +- .../relational/relational_store_manager.cpp | 44 +- .../relational/relational_sync_able_storage.h | 61 +- .../interfaces/src/runtime_config.cpp | 38 + .../storage/include/cloud/cloud_meta_data.h | 59 + .../include/cloud/cloud_storage_utils.h | 98 + .../storage/include/cloud/schema_mgr.h | 46 + .../storage/include/db_properties.h | 6 +- .../include/icloud_sync_storage_interface.h | 94 + .../include/relational_store_connection.h | 12 +- .../storage/include/storage_engine_manager.h | 2 - .../storage/include/storage_proxy.h | 98 + .../storage/src/cloud/cloud_meta_data.cpp | 166 ++ .../storage/src/cloud/cloud_storage_utils.cpp | 539 +++++ .../storage/src/cloud/schema_mgr.cpp | 159 ++ .../storage/src/data_transformer.cpp | 1 - .../storage/src/data_transformer.h | 8 + .../storage/src/db_properties.cpp | 1 + .../storage/src/generic_kvdb.cpp | 14 +- .../storage/src/kvdb_manager.cpp | 2 +- .../storage/src/relational_store_instance.cpp | 2 +- .../src/relational_sync_able_storage.cpp | 348 ++- .../storage/src/result_entries_window.cpp | 2 +- .../sqlite/cloud_sync_log_table_manager.cpp | 34 +- .../src/sqlite/cloud_sync_log_table_manager.h | 2 +- .../collaboration_log_table_manager.cpp | 4 + .../storage/src/sqlite/query_object.cpp | 2 + .../storage/src/sqlite/query_object.h | 2 + .../storage/src/sqlite/query_sync_object.cpp | 10 + .../storage/src/sqlite/query_sync_object.h | 4 + .../relational/sqlite_relational_store.cpp | 190 +- .../relational/sqlite_relational_store.h | 26 +- .../sqlite_relational_store_connection.cpp | 96 + .../sqlite_relational_store_connection.h | 9 + .../relational/sqlite_relational_utils.cpp | 77 + .../relational/sqlite_relational_utils.h | 5 + ...qlite_single_relational_storage_engine.cpp | 6 + .../sqlite_single_relational_storage_engine.h | 2 +- .../sqlite/split_device_log_table_manager.cpp | 4 + .../src/sqlite/sqlite_query_helper.cpp | 51 + .../storage/src/sqlite/sqlite_query_helper.h | 2 + .../sqlite_single_ver_natural_store.cpp | 13 +- .../sqlite/sqlite_single_ver_natural_store.h | 4 +- ...te_single_ver_natural_store_connection.cpp | 9 + ...e_single_ver_relational_continue_token.cpp | 43 + ...ite_single_ver_relational_continue_token.h | 7 + ...single_ver_relational_storage_executor.cpp | 1338 ++++++++++- ...e_single_ver_relational_storage_executor.h | 120 + ...ver_relational_storage_extend_executor.cpp | 247 ++ .../sqlite/sqlite_single_ver_storage_engine.h | 2 +- .../sqlite_single_ver_storage_executor.h | 6 +- .../src/sqlite/sqlite_storage_engine.cpp | 5 - .../src/sqlite/sqlite_storage_engine.h | 4 +- .../storage/src/sqlite/sqlite_utils.cpp | 167 +- .../storage/src/sqlite/sqlite_utils.h | 9 +- .../storage/src/storage_engine.cpp | 10 +- .../storage/src/storage_engine.h | 2 - .../storage/src/storage_engine_manager.cpp | 8 - .../storage/src/storage_proxy.cpp | 331 +++ .../storage/src/sync_able_engine.cpp | 32 +- .../storage/src/sync_able_engine.h | 6 - .../storage/src/sync_able_kvdb.cpp | 15 +- .../distributeddb/syncer/include/isyncer.h | 2 +- .../syncer/include/syncer_proxy.h | 2 +- .../distributeddb/syncer/src/ability_sync.cpp | 47 +- .../distributeddb/syncer/src/ability_sync.h | 22 +- .../syncer/src/cloud/cloud_db_proxy.cpp | 441 ++++ .../syncer/src/cloud/cloud_db_proxy.h | 143 ++ .../src/cloud/cloud_force_pull_strategy.cpp | 51 + .../src/cloud/cloud_force_pull_strategy.h | 31 + .../src/cloud/cloud_force_push_strategy.cpp | 51 + .../src/cloud/cloud_force_push_strategy.h | 31 + .../syncer/src/cloud/cloud_merge_strategy.cpp | 51 + .../syncer/src/cloud/cloud_merge_strategy.h | 35 +- .../syncer/src/cloud/cloud_sync_strategy.h | 54 + .../syncer/src/cloud/cloud_syncer.cpp | 2042 +++++++++++++++++ .../syncer/src/cloud/cloud_syncer.h | 266 +++ .../syncer/src/cloud/strategy_factory.cpp | 38 + .../syncer/src/cloud/strategy_factory.h | 28 + .../syncer/src/device_manager.cpp | 2 - .../syncer/src/generic_syncer.cpp | 87 +- .../distributeddb/syncer/src/generic_syncer.h | 7 +- .../distributeddb/syncer/src/meta_data.cpp | 43 +- .../libs/distributeddb/syncer/src/meta_data.h | 15 + .../src/query_sync_water_mark_helper.cpp | 10 +- .../syncer/src/remote_executor.cpp | 7 +- .../src/single_ver_data_message_schedule.cpp | 10 +- .../syncer/src/single_ver_data_sync.cpp | 1 + .../syncer/src/single_ver_data_sync.h | 4 +- .../syncer/src/single_ver_data_sync_utils.cpp | 2 +- .../src/single_ver_kv_sync_task_context.cpp | 1 + ...ingle_ver_relational_sync_task_context.cpp | 30 +- .../single_ver_relational_sync_task_context.h | 3 + .../src/single_ver_relational_syncer.cpp | 3 + .../syncer/src/single_ver_sync_engine.cpp | 18 +- .../src/single_ver_sync_state_machine.cpp | 4 + .../src/single_ver_sync_task_context.cpp | 16 +- .../syncer/src/single_ver_sync_task_context.h | 4 +- .../syncer/src/single_ver_syncer.cpp | 21 +- .../syncer/src/single_ver_syncer.h | 2 +- .../syncer/src/subscribe_manager.cpp | 2 - .../distributeddb/syncer/src/sync_engine.cpp | 7 +- .../syncer/src/sync_operation.cpp | 8 + .../distributeddb/syncer/src/sync_operation.h | 3 + .../syncer/src/sync_state_machine.cpp | 12 +- .../syncer/src/sync_task_context.cpp | 26 +- .../syncer/src/sync_task_context.h | 2 +- .../distributeddb/syncer/src/syncer_proxy.cpp | 4 +- .../distributeddb/syncer/src/time_helper.cpp | 10 + .../distributeddb/syncer/src/time_helper.h | 1 + .../libs/distributeddb/test/BUILD.gn | 86 +- .../test/fuzztest/delegate_fuzzer/BUILD.gn | 4 + .../test/fuzztest/fileoper_fuzzer/BUILD.gn | 4 + .../test/fuzztest/importfile_fuzzer/BUILD.gn | 4 + .../iprocesscommunicator_fuzzer/BUILD.gn | 4 + .../kvdelegatemanager_fuzzer/BUILD.gn | 4 + .../fuzztest/kvstoreresultset_fuzzer/BUILD.gn | 4 + .../test/fuzztest/nbdelegate_fuzzer/BUILD.gn | 4 + .../test/fuzztest/parseckeck_fuzzer/BUILD.gn | 4 + .../test/fuzztest/query_fuzzer/BUILD.gn | 5 + .../test/fuzztest/rekey_fuzzer/BUILD.gn | 4 + .../relationalstoredelegate_fuzzer/BUILD.gn | 5 +- .../relationalstoredelegate_fuzzer.cpp | 3 +- .../relationalstoremanager_fuzzer/BUILD.gn | 4 + .../fuzztest/schemadelegate_fuzzer/BUILD.gn | 4 + .../test/fuzztest/sync_fuzzer/BUILD.gn | 4 + .../include/distributeddb_data_generator.h | 2 +- .../src/distributeddb_schema_test_tools.cpp | 2 +- .../src/distributeddb_nb_batch_crud_test.cpp | 4 +- .../src/distributeddb_nb_cursor_testcase.cpp | 27 +- ...distributeddb_nb_local_batch_crud_test.cpp | 6 +- .../common/distributeddb_auto_launch_test.cpp | 127 +- .../common/distributeddb_thread_pool_test.cpp | 44 + .../common/distributeddb_tools_unit_test.cpp | 107 +- .../common/distributeddb_tools_unit_test.h | 12 + .../common/communicator/adapter_stub.cpp | 17 + .../common/communicator/adapter_stub.h | 5 + .../distributeddb_communicator_deep_test.cpp | 102 +- .../distributeddb_communicator_test.cpp | 2 +- ..._cloud_interfaces_relational_ext_test.cpp} | 142 +- ...eddb_interfaces_device_identifier_test.cpp | 2 +- ...teddb_interfaces_encrypt_database_test.cpp | 49 + ...nterfaces_nb_delegate_local_batch_test.cpp | 22 + ...tributeddb_interfaces_nb_delegate_test.cpp | 224 +- ...uteddb_interfaces_register_syncdb_test.cpp | 5 + ...stributeddb_interfaces_relational_test.cpp | 75 +- ..._cloud_interfaces_relational_sync_test.cpp | 1546 +++++++++++++ .../distributeddb_cloud_meta_data_test.cpp | 197 ++ ...stributeddb_cloud_save_cloud_data_test.cpp | 705 ++++++ .../distributeddb_cloud_schema_mgr_test.cpp | 416 ++++ ...relational_cloud_syncable_storage_test.cpp | 1087 +++++++++ ...distributeddb_relational_get_data_test.cpp | 14 + ...uteddb_relational_schema_analysis_test.cpp | 29 +- ...buteddb_storage_register_observer_test.cpp | 5 +- ...rage_single_ver_natural_store_testcase.cpp | 4 + ...e_sqlite_single_ver_natural_store_test.cpp | 34 + .../syncer/cloud/cloud_db_data_utils.cpp | 75 + .../common/syncer/cloud/cloud_db_data_utils.h | 34 + .../common/syncer/cloud/cloud_syncer_test.h | 244 ++ ...distributeddb_cloud_asset_compare_test.cpp | 607 +++++ .../distributeddb_cloud_db_proxy_test.cpp | 426 ++++ .../distributeddb_cloud_strategy_test.cpp | 247 ++ ...stributeddb_cloud_syncer_download_test.cpp | 694 ++++++ ...ddb_cloud_syncer_progress_manager_test.cpp | 294 +++ ...distributeddb_cloud_syncer_upload_test.cpp | 1318 +++++++++++ .../mock_icloud_sync_storage_interface.h | 48 + .../common/syncer/cloud/mock_iclouddb.h | 53 +- .../syncer/cloud/virtual_asset_loader.cpp | 37 + .../syncer/cloud/virtual_asset_loader.h | 32 + .../cloud/virtual_cloud_data_translate.cpp | 112 + .../cloud/virtual_cloud_data_translate.h | 32 + .../common/syncer/cloud/virtual_cloud_db.cpp | 253 ++ .../common/syncer/cloud/virtual_cloud_db.h | 79 + .../syncer/cloud/virtual_cloud_syncer.cpp | 71 + .../syncer/cloud/virtual_cloud_syncer.h | 40 + .../distributeddb_anti_dos_sync_test.cpp | 7 +- .../distributeddb_mock_sync_module_test.cpp | 284 ++- ...stributeddb_relational_multi_user_test.cpp | 11 +- ...ributeddb_relational_ver_p2p_sync_test.cpp | 220 +- ...stributeddb_single_ver_multi_user_test.cpp | 6 +- ...teddb_single_ver_p2p_complex_sync_test.cpp | 57 +- ...buteddb_single_ver_p2p_query_sync_test.cpp | 25 + ...uteddb_single_ver_p2p_simple_sync_test.cpp | 16 +- ...buteddb_single_ver_p2p_sync_check_test.cpp | 41 + .../common/syncer/kv_virtual_device.cpp | 11 + .../common/syncer/kv_virtual_device.h | 3 + .../unittest/common/syncer/mock_auto_launch.h | 15 + .../common/syncer/mock_single_ver_kv_syncer.h | 22 + .../common/syncer/mock_sync_task_context.h | 17 +- .../virtual_communicator_aggregator.cpp | 1 - ...rtual_relational_ver_sync_db_interface.cpp | 6 +- .../virtual_single_ver_sync_db_Interface.cpp | 20 +- .../virtual_single_ver_sync_db_Interface.h | 8 +- .../jskits/distributeddata/BUILD.gn | 4 +- .../distributeddata/distributed_data.js | 94 +- .../jskits/distributedkvstore/BUILD.gn | 4 +- .../distributedkvstore/distributed_kvstore.js | 94 +- .../innerkitsimpl/kvdb/src/store_factory.cpp | 2 +- .../innerkitsimpl/kvdb/src/store_manager.cpp | 9 +- .../distributeddata/src/js_util.cpp | 24 +- .../DeviceKvStoreKVCallbackJsTest.js | 1001 ++++---- .../KvManagerKVCallbackJsTest.js | 2 +- .../SingleKvStoreKVCallbackJsTest.js | 837 ++++--- mock/include/CMakeLists.txt | 1 + .../include/uri_permission_load_callback.h | 34 +- .../include/uri_permission_manager_client.h | 89 + .../uri_permission_manager_interface.h | 70 + .../include/uri_permission_manager_proxy.h | 34 +- .../include/uri_permission_manager_stub.h | 41 +- .../include/accesstoken_kit.h | 1 + .../ipc/ipc_core/include/message_parcel.h | 1 + mock/src/mock_access_token.cpp | 20 +- mock/src/mock_hilog.cpp | 5 + mock/src/mock_ipc.cpp | 21 +- mock/src/mock_uri_permission_manager.cpp | 66 + preferences/CMakeLists.txt | 1 + preferences/bundle.json | 13 +- .../frameworks/common/include/log_print.h | 89 + .../js/napi/common/include/js_utils.h | 159 +- .../js/napi/common/include/napi_async_call.h | 2 +- .../common/include/napi_preferences_error.h | 48 +- .../mock/cross_platform/src/js_ability.cpp | 2 +- .../js/napi/common/mock/src/js_ability.cpp | 2 +- .../js/napi/common/src/js_ability.cpp | 2 +- .../js/napi/common/src/js_utils.cpp | 259 +-- .../js/napi/common/src/napi_async_call.cpp | 4 +- .../common/src/napi_preferences_observer.cpp | 7 +- .../js/napi/common/src/uv_queue.cpp | 2 +- .../frameworks/js/napi/preferences/BUILD.gn | 6 +- .../preferences/include/napi_preferences.h | 7 + .../napi/preferences/src/napi_preferences.cpp | 424 +--- .../src/napi_preferences_helper.cpp | 48 +- .../frameworks/js/napi/storage/BUILD.gn | 5 +- .../js/napi/storage/src/napi_storage.cpp | 18 +- .../napi/storage/src/napi_storage_helper.cpp | 4 +- .../js/napi/system_storage/BUILD.gn | 5 +- .../src/napi_system_storage.cpp | 12 +- .../native/include/preferences_impl.h | 13 +- .../native/include/task_scheduler.h | 2 +- .../native/src/preferences_helper.cpp | 4 +- .../native/src/preferences_impl.cpp | 69 +- .../native/src/preferences_xml_utils.cpp | 5 +- preferences/interfaces/inner_api/BUILD.gn | 1 + .../inner_api/include/preferences.h | 4 +- .../inner_api/include/preferences_value.h | 1 - preferences/test/js/BUILD.gn | 6 +- .../js/unittest/preferences/src}/BUILD.gn | 40 +- .../src/PreferencesCallBackJsunit.test.js | 480 ++++ .../src/PreferencesHelperJsunit.test.js | 147 ++ .../src/PreferencesHelperSyncJsunit.test.js | 52 + .../src/PreferencesPromiseJsunit.test.js | 518 +++++ .../src/PreferencesSyncJsunit.test.js | 355 +++ .../src/V9_PreferencesCallBackJsunit.test.js | 598 +++++ .../src/V9_PreferencesPromiseJsunit.test.js | 362 +++ .../js/unittest/preferences/src/config.json | 62 + .../preferences/src/openharmony_sx.p7b | Bin 0 -> 3437 bytes .../test/js/unittest/storage/src/BUILD.gn | 29 + .../storage/src/StorageCallBackJsunit.test.js | 494 ++++ .../storage/src/StorageHelperJsunit.test.js | 134 ++ .../storage/src/StoragePromiseJsunit.test.js | 326 +++ .../storage/src/StorageSyncJsunit.test.js | 449 ++++ .../test/js/unittest/storage/src/config.json | 62 + .../unittest/storage/src/openharmony_sx.p7b | Bin 0 -> 3437 bytes .../js/unittest/system_storage/src/BUILD.gn | 29 + .../src/SystemStorageJsunit.test.js | 514 +++++ .../unittest/system_storage/src/config.json | 62 + .../system_storage/src/openharmony_sx.p7b | Bin 0 -> 3437 bytes preferences/test/native/BUILD.gn | 1 + .../native/unittest/preferences_file_test.cpp | 4 +- .../unittest/preferences_helper_test.cpp | 6 +- .../test/native/unittest/preferences_test.cpp | 4 +- .../unittest/preferences_xml_utils_test.cpp | 100 +- relational_store/CMakeLists.txt | 27 +- relational_store/bundle.json | 50 +- .../frameworks/common/include/logger.h | 89 + .../frameworks/js/napi/cloud_data/BUILD.gn | 3 +- .../js/napi/cloud_data/include/js_config.h | 2 +- .../napi/cloud_data/include/js_error_utils.h | 4 +- .../js/napi/cloud_data/include/napi_queue.h | 60 +- .../js/napi/cloud_data/src/entry_point.cpp | 9 +- .../js/napi/cloud_data/src/js_config.cpp | 32 +- .../cloud_data/src/js_const_properties.cpp | 5 +- .../js/napi/cloud_data/src/js_error_utils.cpp | 13 +- .../js/napi/cloud_data/src/napi_queue.cpp | 31 +- .../js/napi/common/include/js_logger.h | 34 - .../js/napi/common/include/js_utils.h | 28 +- .../js/napi/common/mock/src/js_ability.cpp | 4 +- .../js/napi/common/src/js_ability.cpp | 4 +- .../js/napi/common/src/js_utils.cpp | 133 +- .../frameworks/js/napi/dataability/BUILD.gn | 9 +- .../src/napi_data_ability_predicates.cpp | 3 +- .../dataability/src/napi_predicates_utils.cpp | 3 +- .../frameworks/js/napi/rdb/BUILD.gn | 25 +- .../js/napi/rdb/include/napi_async_call.h | 2 +- .../js/napi/rdb/include/napi_rdb_error.h | 38 +- .../napi/rdb/mock/include/napi_result_set.h | 1 + .../js/napi/rdb/src/napi_async_call.cpp | 4 +- .../js/napi/rdb/src/napi_rdb_js_utils.cpp | 32 +- .../js/napi/rdb/src/napi_rdb_predicates.cpp | 6 +- .../js/napi/rdb/src/napi_rdb_store.cpp | 53 +- .../js/napi/rdb/src/napi_rdb_store_helper.cpp | 10 +- .../napi/rdb/src/napi_rdb_store_observer.cpp | 4 +- .../js/napi/rdb/src/napi_result_set.cpp | 14 +- .../js/napi/rdb/src/napi_uv_queue.cpp | 7 +- .../js/napi/rdb/src/napi_values_bucket.cpp | 3 +- .../js/napi/relationalstore/BUILD.gn | 21 +- .../relationalstore/include/napi_async_call.h | 2 +- .../relationalstore/include/napi_rdb_error.h | 6 +- .../include/napi_rdb_js_utils.h | 21 + .../relationalstore/include/napi_rdb_store.h | 9 + .../include/napi_rdb_store_observer.h | 16 +- .../relationalstore/include/napi_result_set.h | 9 +- .../mock/include/napi_result_set.h | 2 + .../relationalstore/src/napi_async_call.cpp | 3 +- .../src/napi_rdb_const_properties.cpp | 58 + .../relationalstore/src/napi_rdb_js_utils.cpp | 174 +- .../src/napi_rdb_predicates.cpp | 6 +- .../relationalstore/src/napi_rdb_store.cpp | 169 +- .../src/napi_rdb_store_helper.cpp | 13 +- .../src/napi_rdb_store_observer.cpp | 32 +- .../relationalstore/src/napi_result_set.cpp | 42 +- .../relationalstore/src/napi_uv_queue.cpp | 7 +- .../native/appdatafwk/src/mingw_endian.cpp | 35 + .../src/serializable.cpp | 22 +- .../native/appdatafwk/src/shared_block.cpp | 6 +- .../native/cloud_data/src/cloud_manager.cpp | 27 +- .../cloud_data/src/cloud_service_proxy.cpp | 16 +- .../src/ishared_result_set_proxy.cpp | 7 +- .../src/ishared_result_set_stub.cpp | 6 +- .../native/dataability/src/logger.h | 35 - .../native/rdb/include/irdb_service.h | 9 +- .../native/rdb/include/raw_data_parser.h | 14 + .../native/rdb/include/rdb_manager_impl.h | 7 +- .../native/rdb/include/rdb_notifier_stub.h | 9 +- .../native/rdb/include/rdb_security_manager.h | 2 - .../native/rdb/include/rdb_service_proxy.h | 49 +- .../native/rdb/include/rdb_store_impl.h | 56 +- .../native/rdb/include/rdb_store_manager.h | 19 +- .../native/rdb/include/rdb_types_util.h | 45 +- .../native/rdb/include/result_set_proxy.h | 1 + .../include/shared_block_serializer_info.h | 3 +- .../native/rdb/include/sqlite_config.h | 79 - .../native/rdb/include/sqlite_connection.h | 7 + .../rdb/include/sqlite_shared_result_set.h | 29 +- .../native/rdb/include/sqlite_statement.h | 2 + .../native/rdb/include/step_result_set.h | 14 +- .../native/rdb/include/store_session.h | 81 - .../native/rdb/include/task_executor.h | 39 + .../native/rdb/mock/include/rdb_store_impl.h | 30 +- .../rdb/mock/include/rdb_store_manager.h | 19 +- .../native/rdb/mock/include/sqlite_config.h | 73 - .../rdb/mock/include/sqlite_connection.h | 6 + .../rdb/mock/include/sqlite_connection_pool.h | 1 + .../native/rdb/mock/include/sqlite_errno.h | 5 +- .../rdb/mock/include/sqlite_global_config.h | 20 +- .../rdb/mock/include/sqlite_sql_builder.h | 2 +- .../rdb/mock/include/sqlite_statement.h | 5 +- .../native/rdb/mock/include/sqlite_utils.h | 4 +- .../native/rdb/mock/include/step_result_set.h | 16 +- .../native/rdb/mock/include/store_session.h | 76 - .../native/rdb/mock/include/string_utils.h | 2 +- .../native/rdb/mock/include/task_executor.h | 83 + .../native/rdb/mock/include/traits.h | 133 ++ .../native/rdb/mock/src/task_executor.cpp | 39 +- .../native/rdb/src/abs_predicates.cpp | 4 +- .../native/rdb/src/abs_rdb_predicates.cpp | 30 +- .../native/rdb/src/abs_result_set.cpp | 23 +- .../native/rdb/src/abs_shared_result_set.cpp | 62 +- .../frameworks/native/rdb/src/logger.h | 39 - .../native/rdb/src/raw_data_parser.cpp | 135 +- .../frameworks/native/rdb/src/rdb_helper.cpp | 11 +- .../native/rdb/src/rdb_manager_impl.cpp | 152 +- .../native/rdb/src/rdb_notifier_stub.cpp | 63 +- .../native/rdb/src/rdb_predicates.cpp | 5 +- .../native/rdb/src/rdb_security_manager.cpp | 63 +- .../native/rdb/src/rdb_service_proxy.cpp | 213 +- .../native/rdb/src/rdb_sql_utils.cpp | 84 + .../native/rdb/src/rdb_store_config.cpp | 4 +- .../native/rdb/src/rdb_store_impl.cpp | 543 +++-- .../native/rdb/src/rdb_store_manager.cpp | 107 +- .../native/rdb/src/rdb_types_util.cpp | 93 +- .../native/rdb/src/result_set_proxy.cpp | 11 +- .../native/rdb/src/security_policy.cpp | 2 + .../frameworks/native/rdb/src/share_block.cpp | 22 +- .../rdb/src/shared_block_serializer_info.cpp | 23 +- .../native/rdb/src/sqlite_config.cpp | 169 -- .../native/rdb/src/sqlite_connection.cpp | 136 +- .../native/rdb/src/sqlite_connection_pool.cpp | 24 +- .../native/rdb/src/sqlite_database_utils.cpp | 230 -- .../native/rdb/src/sqlite_global_config.cpp | 4 +- .../rdb/src/sqlite_shared_result_set.cpp | 94 +- .../native/rdb/src/sqlite_sql_builder.cpp | 1 + .../native/rdb/src/sqlite_statement.cpp | 126 +- .../native/rdb/src/sqlite_utils.cpp | 11 +- .../native/rdb/src/step_result_set.cpp | 99 +- .../native/rdb/src/store_session.cpp | 447 ---- .../native/rdb/src/task_executor.cpp | 47 + .../native/rdb/src/value_object.cpp | 2 +- .../native/rdb/src/values_bucket.cpp | 13 +- .../src/data_share_profile_info.cpp | 20 +- .../src/rdb_result_set_bridge.cpp | 6 +- .../rdb_data_share_adapter/src/rdb_utils.cpp | 8 +- .../src/rdb_device_manager_adapter.cpp | 4 +- .../interfaces/inner_api/appdatafwk/BUILD.gn | 74 +- .../inner_api/appdatafwk/include/logger.h | 33 - .../include/multi_platform_endian.h | 31 + .../include/serializable.h | 6 +- .../interfaces/inner_api/cloud_data/BUILD.gn | 4 +- .../cloud_data/include/cloud_service.h | 3 +- .../interfaces/inner_api/dataability/BUILD.gn | 4 +- .../interfaces/inner_api/rdb/BUILD.gn | 50 +- .../rdb/include/abs_rdb_predicates.h | 15 +- .../inner_api/rdb/include/abs_result_set.h | 4 +- .../rdb/include/abs_shared_result_set.h | 10 +- .../inner_api/rdb/include/asset_value.h | 15 + .../inner_api/rdb/include/rdb_errno.h | 10 + .../inner_api/rdb/include/rdb_notifier.h | 9 +- .../inner_api/rdb/include/rdb_service.h | 38 +- .../inner_api/rdb/include/rdb_sql_utils.h | 36 + .../inner_api/rdb/include/rdb_store.h | 56 +- .../inner_api/rdb/include/rdb_store_config.h | 2 +- .../inner_api/rdb/include/rdb_types.h | 92 +- .../inner_api/rdb/include/rdb_visibility.h | 6 +- .../inner_api/rdb/include/remote_result_set.h | 4 + .../inner_api/rdb/include/result_set.h | 7 + .../inner_api/rdb/include/shared_result_set.h | 5 +- .../rdb/include/sqlite_database_utils.h | 70 - .../rdb/include/transaction_observer.h | 52 - .../inner_api/rdb/include/values_bucket.h | 16 +- .../rdb/mock/include/abs_rdb_predicates.h | 6 +- .../rdb/mock/include/abs_result_set.h | 2 + .../inner_api/rdb/mock/include/asset_value.h | 15 + .../inner_api/rdb/mock/include/rdb_store.h | 14 +- .../inner_api/rdb/mock/include/result_set.h | 1 + .../rdb/mock/include/sqlite_database_utils.h | 70 - .../rdb/mock/include/values_bucket.h | 3 +- .../inner_api/rdb_bms_adapter/BUILD.gn | 12 +- .../rdb_bms_adapter/include/data_properties.h | 1 + .../rdb_data_ability_adapter/BUILD.gn | 4 +- .../inner_api/rdb_data_share_adapter/BUILD.gn | 5 +- relational_store/interfaces/ndk/BUILD.gn | 64 + .../interfaces/ndk/include/oh_cursor.h | 254 ++ .../interfaces/ndk/include/oh_predicates.h | 403 ++++ .../interfaces/ndk/include/oh_value_object.h | 120 + .../interfaces/ndk/include/oh_values_bucket.h | 146 ++ .../interfaces/ndk/include/relational_store.h | 339 +++ .../ndk/include/relational_store_error_code.h | 316 +++ .../interfaces/ndk/libnative_rdb.ndk.json | 21 + .../interfaces/ndk/src/relational_cursor.cpp | 234 ++ .../ndk/src/relational_cursor_impl.h | 36 + .../ndk/src/relational_predicates.cpp | 397 ++++ .../ndk/src/relational_predicates_impl.h | 35 + .../interfaces/ndk/src/relational_store.cpp | 287 +++ .../ndk/src/relational_store_impl.h | 38 + .../ndk/src/relational_value_object.cpp | 118 + .../ndk/src/relational_value_object_impl.h | 30 +- .../ndk/src/relational_values_bucket.cpp | 136 ++ .../ndk/src/relational_values_bucket_impl.h | 34 + relational_store/relational_store.gni | 3 + .../performance => clouddata}/BUILD.gn | 4 +- .../test/js/clouddata/unittest/config.json | 67 + .../js/clouddata/unittest/openharmony_sx.p7b | Bin 0 -> 3437 bytes .../test/js/clouddata/unittest/src/BUILD.gn | 29 + .../unittest/src/CloudSyncConfigCallback.js | 231 ++ .../unittest/src/CloudSyncConfigPromise.js | 214 ++ ...reBackupRestoreWithFAContextJsunit.test.js | 245 -- .../src/RdbStoreAssetResultSetJsunit.test.js | 682 ++++++ .../unittest/src/RdbStoreCloud.test.js | 426 ++++ .../src/RdbStoreResultSetGetRow.test.js | 26 +- ...reBackupRestoreWithFAContextJsunit.test.js | 1 + .../src/RdbstoreEncryptionJsunit.test.js | 33 + .../src/RdbstoreRdbstoreJsunit.test.js | 76 + relational_store/test/native/rdb/BUILD.gn | 2 + .../rdb_store_impl_test/BUILD.gn | 1 + .../distributed_test_agent.cpp | 14 +- .../rdb/fuzztest/rdbimpl_fuzzer/BUILD.gn | 1 + .../rdbimpl_fuzzer/rdbimpl_fuzzer.cpp | 9 +- .../rdbstore_fuzzer/rdbstore_fuzzer.cpp | 4 +- .../test/native/rdb/unittest/logger.h | 35 - .../native/rdb/unittest/rdb_attach_test.cpp | 12 +- .../native/rdb/unittest/rdb_delete_test.cpp | 9 +- .../rdb/unittest/rdb_distributed_test.cpp | 2 +- .../rdb/unittest/rdb_encrypt_decrypt_test.cpp | 330 +++ .../native/rdb/unittest/rdb_execute_test.cpp | 7 +- .../rdb/unittest/rdb_get_store_test.cpp | 9 +- .../native/rdb/unittest/rdb_helper_test.cpp | 8 +- .../native/rdb/unittest/rdb_insert_test.cpp | 27 +- .../rdb/unittest/rdb_open_callback_test.cpp | 13 +- .../unittest/rdb_predicates_join_b_test.cpp | 18 +- .../rdb/unittest/rdb_predicates_join_test.cpp | 16 +- .../rdb/unittest/rdb_predicates_test.cpp | 180 +- .../rdb_sqlite_shared_result_set_test.cpp | 205 +- .../unittest/rdb_step_result_get_row_test.cpp | 13 +- .../rdb/unittest/rdb_step_result_set_test.cpp | 58 +- .../unittest/rdb_store_concurrent_test.cpp | 7 +- .../rdb/unittest/rdb_store_config_test.cpp | 25 +- .../rdb/unittest/rdb_store_interface_test.cpp | 7 +- .../rdb/unittest/rdb_store_rekey_test.cpp | 327 +++ .../rdb/unittest/rdb_store_subscribe_test.cpp | 149 ++ .../rdb/unittest/rdb_transaction_test.cpp | 23 +- .../native/rdb/unittest/rdb_update_test.cpp | 23 +- .../native/rdb/unittest/rdb_upgrade_test.cpp | 13 +- .../rdb/unittest/rdb_value_bucket_test.cpp | 7 +- .../rdb/unittest/rdb_wal_limit_test.cpp | 10 +- .../test/native/rdb_bms_adapter/BUILD.gn | 50 + .../unittest/rdb_bms_adapter_test.cpp | 130 ++ .../native/rdb_data_share_adapter/BUILD.gn | 1 + .../unittest/rdb_data_share_adapter_test.cpp | 19 +- .../test/ndk}/BUILD.gn | 34 +- .../ndk/unittest/common.h} | 23 +- .../test/ndk/unittest/rdb_cursor_test.cpp | 266 +++ .../test/ndk/unittest/rdb_predicates_test.cpp | 621 +++++ .../test/ndk/unittest/rdb_store_test.cpp | 641 ++++++ test/CMakeLists.txt | 17 +- test/include/CMakeLists.txt | 32 +- udmf | 1 + 938 files changed, 49786 insertions(+), 13712 deletions(-) create mode 100644 data_object/data_object.gni create mode 100644 data_share/frameworks/js/napi/common/include/napi_callbacks_manager.h delete mode 100644 data_share/frameworks/native/common/include/base_proxy.h rename data_share/frameworks/native/{proxy => common}/include/idata_share_service.h (40%) create mode 100644 data_share/frameworks/native/common/include/ikvstore_data_service.h delete mode 100644 data_share/frameworks/native/common/include/itypes_utils.h create mode 100644 data_share/frameworks/native/common/src/datashare_template.cpp create mode 100644 data_share/frameworks/native/common/src/ikvstore_data_service.cpp delete mode 100644 data_share/frameworks/native/common/src/itypes_utils.cpp rename datamgr_service/services/distributeddataservice/adapter/include/autils/kv_store_thread_pool.h => data_share/frameworks/native/consumer/controller/common/general_controller.h (34%) create mode 100644 data_share/frameworks/native/consumer/controller/provider/include/ext_special_controller.h create mode 100644 data_share/frameworks/native/consumer/controller/provider/include/general_controller_porvider_impl.h create mode 100644 data_share/frameworks/native/consumer/controller/provider/src/ext_special_controller.cpp create mode 100644 data_share/frameworks/native/consumer/controller/provider/src/general_controller_provider_impl.cpp create mode 100644 data_share/frameworks/native/consumer/controller/service/include/general_controller_service_impl.h create mode 100644 data_share/frameworks/native/consumer/controller/service/include/persistent_data_controller.h create mode 100644 data_share/frameworks/native/consumer/controller/service/include/published_data_controller.h create mode 100644 data_share/frameworks/native/consumer/controller/service/src/general_controller_service_impl.cpp create mode 100644 data_share/frameworks/native/consumer/controller/service/src/persistent_data_controller.cpp create mode 100644 data_share/frameworks/native/consumer/controller/service/src/published_data_controller.cpp create mode 100644 data_share/frameworks/native/consumer/include/datashare_helper_impl.h delete mode 100644 data_share/frameworks/native/consumer/src/connection_factory.cpp create mode 100644 data_share/frameworks/native/consumer/src/datashare_helper_impl.cpp delete mode 100644 datamgr_service/services/distributeddataservice/adapter/autils/src/constant.cpp delete mode 100644 datamgr_service/services/distributeddataservice/adapter/autils/src/directory_utils.cpp delete mode 100644 datamgr_service/services/distributeddataservice/adapter/autils/src/thread_pool/kv_store_thread_pool_impl.cpp delete mode 100644 datamgr_service/services/distributeddataservice/adapter/autils/test/unittest/kv_store_thread_pool_test.cpp delete mode 100644 datamgr_service/services/distributeddataservice/adapter/include/autils/constant.h rename relational_store/frameworks/native/rdb/mock/src/timer.cpp => datamgr_service/services/distributeddataservice/framework/cloud/sync_event.cpp (32%) create mode 100644 datamgr_service/services/distributeddataservice/framework/include/cloud/change_event.h create mode 100644 datamgr_service/services/distributeddataservice/framework/include/cloud/sync_event.h rename datamgr_service/services/distributeddataservice/{service/kvdb => framework/include/utils}/ref_count.h (90%) rename datamgr_service/services/distributeddataservice/{service/kvdb => framework/utils}/ref_count.cpp (95%) create mode 100644 datamgr_service/services/distributeddataservice/sa_profile/1301.json delete mode 100644 datamgr_service/services/distributeddataservice/sa_profile/1301.xml create mode 100644 datamgr_service/services/distributeddataservice/service/cloud/sync_manager.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/cloud/sync_manager.h create mode 100644 datamgr_service/services/distributeddataservice/service/data_share/common/app_connect_manager.cpp rename datamgr_service/services/distributeddataservice/service/data_share/{data/json_formatter.h => common/app_connect_manager.h} (60%) rename datamgr_service/services/distributeddataservice/service/data_share/{strategies/general/connect_extension_strategy.cpp => common/extension_connect_adaptor.cpp} (53%) rename data_share/frameworks/native/consumer/include/connection_factory.h => datamgr_service/services/distributeddataservice/service/data_share/common/extension_connect_adaptor.h (48%) create mode 100644 datamgr_service/services/distributeddataservice/service/data_share/datamgr_service_data_share.gni create mode 100644 datamgr_service/services/distributeddataservice/service/data_share/gaussdb_rd/src/common/include/document_type.h create mode 100644 datamgr_service/services/distributeddataservice/service/data_share/strategies/general/cross_permission_strategy.cpp rename datamgr_service/services/distributeddataservice/service/data_share/strategies/general/{connect_extension_strategy.h => cross_permission_strategy.h} (61%) rename datamgr_service/services/distributeddataservice/{adapter/autils/src/thread_pool/kv_store_thread.cpp => service/data_share/strategies/template_strategy.cpp} (31%) create mode 100644 datamgr_service/services/distributeddataservice/service/data_share/strategies/template_strategy.h create mode 100644 datamgr_service/services/distributeddataservice/service/data_share/subscriber_managers/published_data_subscriber_manager.cpp rename datamgr_service/services/distributeddataservice/service/data_share/{common/template_manager.h => subscriber_managers/published_data_subscriber_manager.h} (39%) rename datamgr_service/services/distributeddataservice/service/data_share/{common/template_manager.cpp => subscriber_managers/rdb_subscriber_manager.cpp} (38%) create mode 100644 datamgr_service/services/distributeddataservice/service/data_share/subscriber_managers/rdb_subscriber_manager.h create mode 100644 datamgr_service/services/distributeddataservice/service/rdb/rdb_asset_loader.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/rdb/rdb_asset_loader.h create mode 100644 datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud.h create mode 100644 datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/rdb/rdb_cloud_data_translate.h create mode 100644 datamgr_service/services/distributeddataservice/service/rdb/rdb_cursor.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/rdb/rdb_cursor.h create mode 100644 datamgr_service/services/distributeddataservice/service/rdb/value_proxy.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/rdb/value_proxy.h create mode 100644 datamgr_service/services/distributeddataservice/service/test/value_proxy_test.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/BUILD.gn create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/data_manager.cpp rename datamgr_service/services/distributeddataservice/{adapter/autils/src/thread_pool/kv_store_thread_pool_impl.h => service/udmf/data_manager.h} (32%) rename datamgr_service/services/distributeddataservice/{adapter/include/autils/platform_specific.h => service/udmf/lifecycle/clean_after_get.cpp} (73%) create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/lifecycle/clean_after_get.h rename datamgr_service/services/distributeddataservice/service/{data_share/data/json_formatter.cpp => udmf/lifecycle/clean_on_startup.cpp} (64%) create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/lifecycle/clean_on_startup.h create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/lifecycle/clean_on_timeout.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/lifecycle/clean_on_timeout.h create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_manager.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_manager.h create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/lifecycle/lifecycle_policy.h create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/permission/checker_manager.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/permission/checker_manager.h rename datamgr_service/services/distributeddataservice/{adapter/autils/src/thread_pool/kv_store_thread_pool.cpp => service/udmf/permission/data_checker.cpp} (43%) rename datamgr_service/services/distributeddataservice/{adapter/autils/src/thread_pool/kv_store_task.cpp => service/udmf/permission/data_checker.h} (55%) create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/permission/uri_permission_manager.cpp rename data_share/test/native/unittest/mediadatashare_test/include/get_self_permissions.h => datamgr_service/services/distributeddataservice/service/udmf/permission/uri_permission_manager.h (60%) create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/preprocess/preprocess_utils.h rename datamgr_service/services/distributeddataservice/service/{kvdb/executor_factory.h => udmf/same_process_ipc_guard.h} (46%) create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/store/runtime_store.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/store/runtime_store.h rename datamgr_service/services/distributeddataservice/{adapter/include/autils/directory_utils.h => service/udmf/store/store.h} (39%) create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/store/store_cache1.cpp rename relational_store/frameworks/native/rdb/include/rdb_manager.h => datamgr_service/services/distributeddataservice/service/udmf/store/store_cache1.h (58%) create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/udmf_service_impl.cpp rename data_share/test/native/unittest/mediadatashare_test/src/get_self_permissions.cpp => datamgr_service/services/distributeddataservice/service/udmf/udmf_service_impl.h (34%) create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/udmf_service_stub.cpp create mode 100644 datamgr_service/services/distributeddataservice/service/udmf/udmf_service_stub.h create mode 100644 kv_store/frameworks/libs/distributeddb/common/include/cloud/cloud_db_constant.h create mode 100644 kv_store/frameworks/libs/distributeddb/common/include/cloud/cloud_db_types.h create mode 100644 kv_store/frameworks/libs/distributeddb/interfaces/include/cloud/iAssetLoader.h create mode 100644 kv_store/frameworks/libs/distributeddb/interfaces/include/cloud/icloud_data_translate.h create mode 100644 kv_store/frameworks/libs/distributeddb/interfaces/include/cloud/icloud_db.h create mode 100644 kv_store/frameworks/libs/distributeddb/storage/include/cloud/cloud_meta_data.h create mode 100644 kv_store/frameworks/libs/distributeddb/storage/include/cloud/cloud_storage_utils.h create mode 100644 kv_store/frameworks/libs/distributeddb/storage/include/cloud/schema_mgr.h create mode 100644 kv_store/frameworks/libs/distributeddb/storage/include/icloud_sync_storage_interface.h create mode 100644 kv_store/frameworks/libs/distributeddb/storage/include/storage_proxy.h create mode 100644 kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_meta_data.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/storage/src/cloud/cloud_storage_utils.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/storage/src/cloud/schema_mgr.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/storage/src/sqlite/sqlite_single_ver_relational_storage_extend_executor.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/storage/src/storage_proxy.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_db_proxy.h create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_pull_strategy.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_pull_strategy.h create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_push_strategy.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_force_push_strategy.h create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_merge_strategy.cpp rename datamgr_service/services/distributeddataservice/adapter/include/autils/time_utils.h => kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_merge_strategy.h (52%) create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_sync_strategy.h create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/cloud_syncer.h create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/strategy_factory.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/syncer/src/cloud/strategy_factory.h rename kv_store/frameworks/libs/distributeddb/test/unittest/common/interfaces/{distributeddb_interfaces_relational_ext_test.cpp => distributeddb_cloud_interfaces_relational_ext_test.cpp} (71%) create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_interfaces_relational_sync_test.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_meta_data_test.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/cloud/distributeddb_cloud_save_cloud_data_test.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_cloud_schema_mgr_test.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/storage/distributeddb_relational_cloud_syncable_storage_test.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/cloud_db_data_utils.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/cloud_db_data_utils.h create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/cloud_syncer_test.h create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_asset_compare_test.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_db_proxy_test.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_strategy_test.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_download_test.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_progress_manager_test.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/distributeddb_cloud_syncer_upload_test.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/mock_icloud_sync_storage_interface.h rename datamgr_service/services/distributeddataservice/app/test/unittest/uninstaller_test.cpp => kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/mock_iclouddb.h (40%) create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_asset_loader.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_asset_loader.h create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_data_translate.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_data_translate.h create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_db.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_db.h create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_syncer.cpp create mode 100644 kv_store/frameworks/libs/distributeddb/test/unittest/common/syncer/cloud/virtual_cloud_syncer.h rename datamgr_service/services/distributeddataservice/adapter/autils/src/thread_pool/kv_store_thread.h => mock/innerkits/ability_runtime/uri_permission/include/uri_permission_load_callback.h (47%) create mode 100644 mock/innerkits/ability_runtime/uri_permission/include/uri_permission_manager_client.h create mode 100644 mock/innerkits/ability_runtime/uri_permission/include/uri_permission_manager_interface.h rename relational_store/frameworks/native/rdb_data_share_adapter/include/rdb_logger.h => mock/innerkits/ability_runtime/uri_permission/include/uri_permission_manager_proxy.h (39%) rename data_share/frameworks/native/consumer/include/base_connection.h => mock/innerkits/ability_runtime/uri_permission/include/uri_permission_manager_stub.h (47%) create mode 100644 mock/src/mock_uri_permission_manager.cpp create mode 100644 preferences/frameworks/common/include/log_print.h rename {datamgr_service/services/distributeddataservice/adapter/autils => preferences/test/js/unittest/preferences/src}/BUILD.gn (38%) create mode 100644 preferences/test/js/unittest/preferences/src/PreferencesCallBackJsunit.test.js create mode 100644 preferences/test/js/unittest/preferences/src/PreferencesHelperJsunit.test.js create mode 100644 preferences/test/js/unittest/preferences/src/PreferencesHelperSyncJsunit.test.js create mode 100644 preferences/test/js/unittest/preferences/src/PreferencesPromiseJsunit.test.js create mode 100644 preferences/test/js/unittest/preferences/src/PreferencesSyncJsunit.test.js create mode 100644 preferences/test/js/unittest/preferences/src/V9_PreferencesCallBackJsunit.test.js create mode 100644 preferences/test/js/unittest/preferences/src/V9_PreferencesPromiseJsunit.test.js create mode 100644 preferences/test/js/unittest/preferences/src/config.json create mode 100644 preferences/test/js/unittest/preferences/src/openharmony_sx.p7b create mode 100644 preferences/test/js/unittest/storage/src/BUILD.gn create mode 100644 preferences/test/js/unittest/storage/src/StorageCallBackJsunit.test.js create mode 100644 preferences/test/js/unittest/storage/src/StorageHelperJsunit.test.js create mode 100644 preferences/test/js/unittest/storage/src/StoragePromiseJsunit.test.js create mode 100644 preferences/test/js/unittest/storage/src/StorageSyncJsunit.test.js create mode 100644 preferences/test/js/unittest/storage/src/config.json create mode 100644 preferences/test/js/unittest/storage/src/openharmony_sx.p7b create mode 100644 preferences/test/js/unittest/system_storage/src/BUILD.gn create mode 100644 preferences/test/js/unittest/system_storage/src/SystemStorageJsunit.test.js create mode 100644 preferences/test/js/unittest/system_storage/src/config.json create mode 100644 preferences/test/js/unittest/system_storage/src/openharmony_sx.p7b create mode 100644 relational_store/frameworks/common/include/logger.h delete mode 100644 relational_store/frameworks/js/napi/common/include/js_logger.h create mode 100644 relational_store/frameworks/native/appdatafwk/src/mingw_endian.cpp rename relational_store/frameworks/native/{rdb_bms_adaptor => appdatafwk}/src/serializable.cpp (91%) delete mode 100644 relational_store/frameworks/native/dataability/src/logger.h delete mode 100644 relational_store/frameworks/native/rdb/include/sqlite_config.h delete mode 100644 relational_store/frameworks/native/rdb/include/store_session.h create mode 100644 relational_store/frameworks/native/rdb/include/task_executor.h delete mode 100644 relational_store/frameworks/native/rdb/mock/include/sqlite_config.h delete mode 100644 relational_store/frameworks/native/rdb/mock/include/store_session.h create mode 100644 relational_store/frameworks/native/rdb/mock/include/task_executor.h create mode 100644 relational_store/frameworks/native/rdb/mock/include/traits.h rename datamgr_service/services/distributeddataservice/service/kvdb/executor_factory.cpp => relational_store/frameworks/native/rdb/mock/src/task_executor.cpp (46%) delete mode 100644 relational_store/frameworks/native/rdb/src/logger.h create mode 100644 relational_store/frameworks/native/rdb/src/rdb_sql_utils.cpp delete mode 100644 relational_store/frameworks/native/rdb/src/sqlite_config.cpp delete mode 100644 relational_store/frameworks/native/rdb/src/sqlite_database_utils.cpp delete mode 100644 relational_store/frameworks/native/rdb/src/store_session.cpp create mode 100644 relational_store/frameworks/native/rdb/src/task_executor.cpp delete mode 100644 relational_store/interfaces/inner_api/appdatafwk/include/logger.h create mode 100644 relational_store/interfaces/inner_api/appdatafwk/include/multi_platform_endian.h rename relational_store/interfaces/inner_api/{rdb_bms_adapter => appdatafwk}/include/serializable.h (95%) create mode 100644 relational_store/interfaces/inner_api/rdb/include/rdb_sql_utils.h delete mode 100644 relational_store/interfaces/inner_api/rdb/include/sqlite_database_utils.h delete mode 100644 relational_store/interfaces/inner_api/rdb/include/transaction_observer.h delete mode 100644 relational_store/interfaces/inner_api/rdb/mock/include/sqlite_database_utils.h create mode 100644 relational_store/interfaces/ndk/BUILD.gn create mode 100644 relational_store/interfaces/ndk/include/oh_cursor.h create mode 100644 relational_store/interfaces/ndk/include/oh_predicates.h create mode 100644 relational_store/interfaces/ndk/include/oh_value_object.h create mode 100644 relational_store/interfaces/ndk/include/oh_values_bucket.h create mode 100644 relational_store/interfaces/ndk/include/relational_store.h create mode 100644 relational_store/interfaces/ndk/include/relational_store_error_code.h create mode 100644 relational_store/interfaces/ndk/libnative_rdb.ndk.json create mode 100644 relational_store/interfaces/ndk/src/relational_cursor.cpp create mode 100644 relational_store/interfaces/ndk/src/relational_cursor_impl.h create mode 100644 relational_store/interfaces/ndk/src/relational_predicates.cpp create mode 100644 relational_store/interfaces/ndk/src/relational_predicates_impl.h create mode 100644 relational_store/interfaces/ndk/src/relational_store.cpp create mode 100644 relational_store/interfaces/ndk/src/relational_store_impl.h create mode 100644 relational_store/interfaces/ndk/src/relational_value_object.cpp rename datamgr_service/services/distributeddataservice/adapter/include/autils/kv_store_task.h => relational_store/interfaces/ndk/src/relational_value_object_impl.h (55%) create mode 100644 relational_store/interfaces/ndk/src/relational_values_bucket.cpp create mode 100644 relational_store/interfaces/ndk/src/relational_values_bucket_impl.h rename relational_store/test/js/{relationalstore/performance => clouddata}/BUILD.gn (92%) create mode 100644 relational_store/test/js/clouddata/unittest/config.json create mode 100644 relational_store/test/js/clouddata/unittest/openharmony_sx.p7b create mode 100644 relational_store/test/js/clouddata/unittest/src/BUILD.gn create mode 100644 relational_store/test/js/clouddata/unittest/src/CloudSyncConfigCallback.js create mode 100644 relational_store/test/js/clouddata/unittest/src/CloudSyncConfigPromise.js delete mode 100644 relational_store/test/js/rdb/unittest/src/RdbstoreBackupRestoreWithFAContextJsunit.test.js create mode 100644 relational_store/test/js/relationalstore/unittest/src/RdbStoreAssetResultSetJsunit.test.js create mode 100644 relational_store/test/js/relationalstore/unittest/src/RdbStoreCloud.test.js delete mode 100644 relational_store/test/native/rdb/unittest/logger.h create mode 100644 relational_store/test/native/rdb/unittest/rdb_encrypt_decrypt_test.cpp create mode 100644 relational_store/test/native/rdb/unittest/rdb_store_rekey_test.cpp create mode 100644 relational_store/test/native/rdb/unittest/rdb_store_subscribe_test.cpp create mode 100644 relational_store/test/native/rdb_bms_adapter/BUILD.gn create mode 100644 relational_store/test/native/rdb_bms_adapter/unittest/rdb_bms_adapter_test.cpp rename {datamgr_service/services/distributeddataservice/adapter/autils/test => relational_store/test/ndk}/BUILD.gn (56%) rename relational_store/{frameworks/native/rdb/src/rdb_manager.cpp => test/ndk/unittest/common.h} (62%) create mode 100644 relational_store/test/ndk/unittest/rdb_cursor_test.cpp create mode 100644 relational_store/test/ndk/unittest/rdb_predicates_test.cpp create mode 100644 relational_store/test/ndk/unittest/rdb_store_test.cpp create mode 160000 udmf diff --git a/CMakeLists.txt b/CMakeLists.txt index 7b7cf702..3ade48b4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -18,6 +18,7 @@ add_subdirectory(kv_store) add_subdirectory(preferences) add_subdirectory(data_object) add_subdirectory(datamgr_service) +add_subdirectory(udmf) set(CMAKE_CXX_FLAGS "-std=c++1y -fno-rtti -fvisibility=default -D_GNU_SOURCE") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdata-sections -fPIC -fpic -ffunction-sections -D_GLIBC_MOCK") @@ -33,7 +34,7 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}/mock/innerkits/ipc/ipc_single/in include_directories(${CMAKE_CURRENT_SOURCE_DIR}/mock/innerkits/ipc/libdbinder/include) set(MAIN_BINARY ${PROJECT_NAME}) -set(links secure mock relational_store data_share preferences jsoncpp crypto distributeddb data_object app adapter svcFwk kvdb service) +set(links secure mock relational_store data_share preferences jsoncpp crypto distributeddb data_object app adapter svcFwk kvdb service udmf) add_executable(${MAIN_BINARY} dllmain.cpp) target_link_libraries(${MAIN_BINARY} ${links}) diff --git a/bin/update/updata.bat b/bin/update/updata.bat index 09f49478..53dc71cf 100644 --- a/bin/update/updata.bat +++ b/bin/update/updata.bat @@ -7,9 +7,9 @@ cls @echo %date%-%time% mkdir tmp @echo "clone the datamgr_service" -git clone https://gitee.com/openharmony/distributeddatamgr_datamgr_service.git ./tmp/datamgr_service +git clone https://gitee.com/ding_dong_dong/distributeddatamgr_datamgr_service.git ./tmp/datamgr_service @echo "clone the kv_store" -git clone https://gitee.com/openharmony/distributeddatamgr_kv_store.git ./tmp/kv_store +git clone https://gitee.com/ding_dong_dong/distributeddatamgr_kv_store.git ./tmp/kv_store @echo "clone the relational_store" git clone https://gitee.com/openharmony/distributeddatamgr_relational_store.git ./tmp/relational_store @echo "clone the data_object" @@ -18,6 +18,8 @@ git clone https://gitee.com/openharmony/distributeddatamgr_data_object.git ./tmp git clone https://gitee.com/openharmony/distributeddatamgr_data_share.git ./tmp/data_share @echo "clone the preferences" git clone https://gitee.com/openharmony/distributeddatamgr_preferences.git ./tmp/preferences +@echo "clone the udmf" +git clone https://gitee.com/ding_dong_dong/distributeddatamgr_udmf.git ./tmp/udmf xcopy tmp\* ..\..\ /y /e /i /q rd /s /q tmp @echo "FINISHED" diff --git a/data_object/bundle.json b/data_object/bundle.json index 99f5c541..0112f2eb 100644 --- a/data_object/bundle.json +++ b/data_object/bundle.json @@ -1,11 +1,11 @@ { - "name": "@ohos/distributeddatamgr_data_object", - "version": "", + "name": "@ohos/data_object", + "version": "3.1.0", "description": "The distributed data object management framework is an object-oriented in-memory data management framework", "homePage": "https://gitee.com/openharmony", "license": "Apache V2", "repository": "https://gitee.com/openharmony/distributeddatamgr_data_object ", - "domain": "os", + "domain": "ohos", "language": "", "publishAs": "code-segment", "private": false, @@ -40,8 +40,8 @@ "adapted_system_type": [ "standard" ], - "rom": "", - "ram": "", + "rom": "1024KB", + "ram": "1024KB", "deps": { "components": [ "ability_base", @@ -55,10 +55,15 @@ "ipc", "hiviewdfx_hilog_native", "utils_base", - "access_token" + "access_token", + "c_utils", + "device_manager", + "kv_store", + "common_event_service" ], "third_party": [ - "libuv" + "libuv", + "bounds_checking_function" ] }, "build": { diff --git a/data_object/data_object.gni b/data_object/data_object.gni new file mode 100644 index 00000000..34155d9a --- /dev/null +++ b/data_object/data_object.gni @@ -0,0 +1,14 @@ +# 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. + +kvstore_path = "//foundation/distributeddatamgr/kv_store/frameworks" diff --git a/data_object/frameworks/innerkitsimpl/include/adaptor/distributed_objectstore_impl.h b/data_object/frameworks/innerkitsimpl/include/adaptor/distributed_objectstore_impl.h index 8fba8f4f..1db679ce 100644 --- a/data_object/frameworks/innerkitsimpl/include/adaptor/distributed_objectstore_impl.h +++ b/data_object/frameworks/innerkitsimpl/include/adaptor/distributed_objectstore_impl.h @@ -50,6 +50,7 @@ private: std::map> watchers_; std::shared_mutex dataMutex_ {}; std::vector objects_ {}; + std::mutex watchersLock_; }; class StatusNotifierProxy : public StatusWatcher { public: diff --git a/data_object/frameworks/innerkitsimpl/include/common/logger.h b/data_object/frameworks/innerkitsimpl/include/common/logger.h index 20b4ade4..ece6a014 100644 --- a/data_object/frameworks/innerkitsimpl/include/common/logger.h +++ b/data_object/frameworks/innerkitsimpl/include/common/logger.h @@ -19,23 +19,56 @@ #ifdef HILOG_ENABLE #include "hilog/log.h" namespace OHOS::ObjectStore { -static const OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0xD001652, "ObjectStore-x" }; - -#define LOG_DEBUG(fmt, ...) \ - ((void)OHOS::HiviewDFX::HiLog::Debug( \ - LABEL, "%{public}d: %{public}s " fmt " ", __LINE__, __FUNCTION__, ##__VA_ARGS__)) -#define LOG_INFO(fmt, ...) \ - ((void)OHOS::HiviewDFX::HiLog::Info( \ - LABEL, "%{public}d: %{public}s " fmt " ", __LINE__, __FUNCTION__, ##__VA_ARGS__)) -#define LOG_WARN(fmt, ...) \ - ((void)OHOS::HiviewDFX::HiLog::Warn( \ - LABEL, "%{public}d: %{public}s " fmt " ", __LINE__, __FUNCTION__, ##__VA_ARGS__)) -#define LOG_ERROR(fmt, ...) \ - ((void)OHOS::HiviewDFX::HiLog::Error( \ - LABEL, "%{public}d: %{public}s " fmt " ", __LINE__, __FUNCTION__, ##__VA_ARGS__)) -#define LOG_FATAL(fmt, ...) \ - ((void)OHOS::HiviewDFX::HiLog::Fatal( \ - LABEL, "%{public}d: %{public}s " fmt " ", __LINE__, __FUNCTION__, ##__VA_ARGS__)) +static inline OHOS::HiviewDFX::HiLogLabel LogLabel() +{ + return { LOG_CORE, 0xD001652, "ObjectStore-x" }; +} + +#define LOG_DEBUG(fmt, ...) \ + do { \ + using HiLog = OHOS::HiviewDFX::HiLog; \ + auto lable = LogLabel(); \ + if (HiLogIsLoggable(lable.domain, lable.tag, LogLevel::LOG_DEBUG)) { \ + HiLog::Debug(lable, "%{public}d: %{public}s " fmt " ", __LINE__, __FUNCTION__, ##__VA_ARGS__); \ + } \ + } while (0) + +#define LOG_INFO(fmt, ...) \ + do { \ + using HiLog = OHOS::HiviewDFX::HiLog; \ + auto lable = LogLabel(); \ + if (HiLogIsLoggable(lable.domain, lable.tag, LogLevel::LOG_INFO)) { \ + HiLog::Info(lable, "%{public}d: %{public}s " fmt " ", __LINE__, __FUNCTION__, ##__VA_ARGS__); \ + } \ + } while (0) + +#define LOG_WARN(fmt, ...) \ + do { \ + using HiLog = OHOS::HiviewDFX::HiLog; \ + auto lable = LogLabel(); \ + if (HiLogIsLoggable(lable.domain, lable.tag, LogLevel::LOG_WARN)) { \ + HiLog::Warn(lable, "%{public}d: %{public}s " fmt " ", __LINE__, __FUNCTION__, ##__VA_ARGS__); \ + } \ + } while (0) + +#define LOG_ERROR(fmt, ...) \ + do { \ + using HiLog = OHOS::HiviewDFX::HiLog; \ + auto lable = LogLabel(); \ + if (HiLogIsLoggable(lable.domain, lable.tag, LogLevel::LOG_ERROR)) { \ + HiLog::Error(lable, "%{public}d: %{public}s " fmt " ", __LINE__, __FUNCTION__, ##__VA_ARGS__); \ + } \ + } while (0) + +#define LOG_FATAL(fmt, ...) \ + do { \ + using HiLog = OHOS::HiviewDFX::HiLog; \ + auto lable = LogLabel(); \ + if (HiLogIsLoggable(lable.domain, lable.tag, LogLevel::LOG_FATAL)) { \ + HiLog::Fatal(lable, "%{public}d: %{public}s " fmt " ", __LINE__, __FUNCTION__, ##__VA_ARGS__); \ + } \ + } while (0) + } // namespace OHOS::ObjectStore #else #include diff --git a/data_object/frameworks/innerkitsimpl/include/communicator/visibility.h b/data_object/frameworks/innerkitsimpl/include/communicator/visibility.h index 3c5f9253..66c7b4fe 100644 --- a/data_object/frameworks/innerkitsimpl/include/communicator/visibility.h +++ b/data_object/frameworks/innerkitsimpl/include/communicator/visibility.h @@ -12,8 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +#ifndef VISIBILITY_H +#define VISIBILITY_H + #ifndef API_EXPORT -#if _WIN32 +#ifdef _WIN32 #define API_EXPORT __declspec(dllexport) #else #define API_EXPORT __attribute__((visibility ("default"))) @@ -22,3 +26,5 @@ #ifndef KVSTORE_API #define KVSTORE_API API_EXPORT #endif + +#endif diff --git a/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_impl.cpp b/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_impl.cpp index d7c0e464..ab6501b9 100644 --- a/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_impl.cpp +++ b/data_object/frameworks/innerkitsimpl/src/adaptor/distributed_object_impl.cpp @@ -55,7 +55,7 @@ uint32_t GetNum(Bytes &data, uint32_t offset, void *val, uint32_t valLen) uint32_t DistributedObjectImpl::PutDouble(const std::string &key, double value) { - DataObjectHiTrace trace(std::string(__FUNCTION__)); + DataObjectHiTrace trace("DistributedObjectImpl::PutDouble"); Bytes data; Type type = Type::TYPE_DOUBLE; PutNum(&type, 0, sizeof(type), data); @@ -69,7 +69,7 @@ uint32_t DistributedObjectImpl::PutDouble(const std::string &key, double value) uint32_t DistributedObjectImpl::PutBoolean(const std::string &key, bool value) { - DataObjectHiTrace trace(std::string(__FUNCTION__)); + DataObjectHiTrace trace("DistributedObjectImpl::PutBoolean"); Bytes data; Type type = Type::TYPE_BOOLEAN; PutNum(&type, 0, sizeof(type), data); @@ -83,7 +83,7 @@ uint32_t DistributedObjectImpl::PutBoolean(const std::string &key, bool value) uint32_t DistributedObjectImpl::PutString(const std::string &key, const std::string &value) { - DataObjectHiTrace trace(std::string(__FUNCTION__)); + DataObjectHiTrace trace("DistributedObjectImpl::PutString"); Bytes data; Type type = Type::TYPE_STRING; PutNum(&type, 0, sizeof(type), data); @@ -172,7 +172,7 @@ DistributedObjectImpl::DistributedObjectImpl(const std::string &sessionId, FlatO uint32_t DistributedObjectImpl::PutComplex(const std::string &key, const std::vector &value) { - DataObjectHiTrace trace(std::string(__FUNCTION__)); + DataObjectHiTrace trace("DistributedObjectImpl::PutComplex"); Bytes data; Type type = Type::TYPE_COMPLEX; PutNum(&type, 0, sizeof(type), data); 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 c99c4019..4743f88e 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 @@ -62,7 +62,7 @@ void DistributedObjectStoreImpl::RemoveCacheObject(const std::string &sessionId) DistributedObject *DistributedObjectStoreImpl::CreateObject(const std::string &sessionId) { - DataObjectHiTrace trace(std::string(__FUNCTION__)); + DataObjectHiTrace trace("DistributedObjectStoreImpl::CreateObject"); if (flatObjectStore_ == nullptr) { LOG_ERROR("DistributedObjectStoreImpl::CreateObject store not opened!"); return nullptr; @@ -83,7 +83,7 @@ DistributedObject *DistributedObjectStoreImpl::CreateObject(const std::string &s DistributedObject *DistributedObjectStoreImpl::CreateObject(const std::string &sessionId, uint32_t &status) { - DataObjectHiTrace trace(std::string(__FUNCTION__)); + DataObjectHiTrace trace("DistributedObjectStoreImpl::CreateObject"); if (flatObjectStore_ == nullptr) { LOG_ERROR("DistributedObjectStoreImpl::CreateObject store not opened!"); status = ERR_NULL_OBJECTSTORE; @@ -106,7 +106,7 @@ DistributedObject *DistributedObjectStoreImpl::CreateObject(const std::string &s uint32_t DistributedObjectStoreImpl::DeleteObject(const std::string &sessionId) { - DataObjectHiTrace trace(std::string(__FUNCTION__)); + DataObjectHiTrace trace("DistributedObjectStoreImpl::DeleteObject"); if (flatObjectStore_ == nullptr) { LOG_ERROR("DistributedObjectStoreImpl::Sync object err "); return ERR_NULL_OBJECTSTORE; @@ -144,6 +144,7 @@ uint32_t DistributedObjectStoreImpl::Watch(DistributedObject *object, std::share LOG_ERROR("DistributedObjectStoreImpl::Sync object err "); return ERR_NULL_OBJECTSTORE; } + std::lock_guard lock(watchersLock_); if (watchers_.count(object) != 0) { LOG_ERROR("DistributedObjectStoreImpl::Watch already gets object"); return ERR_EXIST; @@ -174,6 +175,7 @@ uint32_t DistributedObjectStoreImpl::UnWatch(DistributedObject *object) LOG_ERROR("DistributedObjectStoreImpl::Watch failed %{public}d", status); return status; } + std::lock_guard lock(watchersLock_); watchers_.erase(object); LOG_INFO("DistributedObjectStoreImpl:UnWatch object success."); return SUCCESS; diff --git a/data_object/interfaces/innerkits/BUILD.gn b/data_object/interfaces/innerkits/BUILD.gn index aa391f48..25a47e34 100644 --- a/data_object/interfaces/innerkits/BUILD.gn +++ b/data_object/interfaces/innerkits/BUILD.gn @@ -11,7 +11,7 @@ # See the License for the specific language governing permissions and # limitations under the License. import("//build/ohos.gni") - +import("//foundation/distributeddatamgr/data_object/data_object.gni") config("objectstore_config") { visibility = [ ":*" ] @@ -23,7 +23,7 @@ config("objectstore_config") { "../../frameworks/innerkitsimpl/include/communicator", "../../frameworks/innerkitsimpl/include", "../../interfaces/innerkits", - "//foundation/distributeddatamgr/kv_store/frameworks/common", + "${kvstore_path}/common", ] ldflags = [ "-Wl,--exclude-libs,ALL" ] @@ -55,7 +55,7 @@ object_source_config = [ "../../frameworks/innerkitsimpl/src/object_service_proxy.cpp", ] object_deps_config = [ - "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb:distributeddb", + "${kvstore_path}/libs/distributeddb:distributeddb", "//third_party/bounds_checking_function:libsec_shared", "//third_party/libuv:uv", ] @@ -84,10 +84,12 @@ ohos_shared_library("distributeddataobject_impl") { } ohos_static_library("distributeddataobject_static") { + part_name = "data_object" sources = object_source_config configs = [ ":objectstore_config" ] deps = object_deps_config external_deps = object_external_deps_config public_configs = [ ":objectstore_public_config" ] + subsystem_name = "distributeddatamgr" } diff --git a/data_object/interfaces/jskits/BUILD.gn b/data_object/interfaces/jskits/BUILD.gn index 482dd348..ce5ff55b 100644 --- a/data_object/interfaces/jskits/BUILD.gn +++ b/data_object/interfaces/jskits/BUILD.gn @@ -14,7 +14,7 @@ import("//arkcompiler/ets_frontend/ts2panda/ts2abc_config.gni") import("//build/ohos.gni") import("//build/ohos/ace/ace.gni") import("//foundation/arkui/ace_engine/ace_config.gni") - +import("//foundation/distributeddatamgr/data_object/data_object.gni") group("build_module") { deps = [ ":distributeddataobject" ] } @@ -54,10 +54,10 @@ config("objectstore_config") { "../../frameworks/innerkitsimpl/include/common", "../../frameworks/innerkitsimpl/include/communicator", "../../interfaces/innerkits", - "//foundation/distributeddatamgr/kv_store/frameworks/common", - "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/interfaces/include", - "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/interfaces/include/relational", - "//foundation/distributeddatamgr/kv_store/frameworks/libs/distributeddb/include", + "${kvstore_path}/common", + "${kvstore_path}/libs/distributeddb/interfaces/include", + "${kvstore_path}/libs/distributeddb/interfaces/include/relational", + "${kvstore_path}/libs/distributeddb/include", ] } diff --git a/data_share/CMakeLists.txt b/data_share/CMakeLists.txt index 2a20e43c..28c378aa 100644 --- a/data_share/CMakeLists.txt +++ b/data_share/CMakeLists.txt @@ -10,33 +10,40 @@ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage") 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}/ data_share_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/common/src data_share_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/dataShare/src data_share_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/observer/src data_share_src) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/common/src data_share_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/consumer/controller/provider/src data_share_src) +aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/consumer/controller/service/src data_share_src) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/consumer/src data_share_src) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/provider/src data_share_src) aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/proxy/src data_share_src) -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/common/src data_share_src) -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/dataShare/src data_share_src) -aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/observer/src data_share_src) -#aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/datashare_ext_ability data_share_src) -#aux_source_directory(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/datashare_ext_ability_context data_share_src) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/common/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/dataShare/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/observer/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/common/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/consumer/controller/common) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/consumer/controller/provider/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/consumer/controller/service/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/consumer/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/provider/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/native/proxy/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/common/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/dataShare/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/frameworks/js/napi/observer/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/common/include/basic) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/common/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/consumer/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/interfaces/inner_api/provider/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../utils_native/base/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../utils_native/safwk/native/include) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../relational_store/interfaces/inner_api/rdb/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../relational_store/interfaces/inner_api/appdatafwk/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../relational_store/interfaces/inner_api/dataability/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../relational_store/interfaces/inner_api/rdb/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../relational_store/interfaces/inner_api/rdb_bms_adapter/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../relational_store/interfaces/inner_api/rdb_data_ability_adapter/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../relational_store/interfaces/inner_api/rdb_data_share_adapter/include) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../kv_store/frameworks/common) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../datamgr_service/services/distributeddataservice/adapter/include/dfx) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../utils_native/base/include) +include_directories(${CMAKE_CURRENT_SOURCE_DIR}/../utils_native/safwk/native/include) include(${MOCK_DIR}/include/CMakeLists.txt OPTIONAL) set(links secure mock relational_store) diff --git a/data_share/bundle.json b/data_share/bundle.json index 30572a7c..d1378671 100644 --- a/data_share/bundle.json +++ b/data_share/bundle.json @@ -1,11 +1,11 @@ { - "name": "@ohos/distributeddatamgr_data_share", - "version": "3.1.0", - "description": "Local Data Management", + "name": "@ohos/data_share", + "version": "3.2.0", "homePage": "https://gitee.com/openharmony", - "license": "Apache V2", + "license": "Apache License 2.0", "repository": "https://gitee.com/openharmony/distributeddatamgr_data_share", - "domain": "os", + "description": "allows an application to manage its own data and share data with other applications", + "domain": "ohos", "language": "", "publishAs": "code-segment", "private": false, @@ -46,22 +46,29 @@ "adapted_system_type": [ "standard" ], - "rom": "", - "ram": "", + "rom": "3584KB", + "ram": "10240KB", "deps": { "components": [ - "relational_store", - "access_token", + "ability_base", "ability_runtime", - "ipc_js", - "napi", + "access_token", + "common_event_service", + "c_utils", + "hisysevent_native", + "hitrace_native", "hiviewdfx_hilog_native", - "libuv", "ipc", - "utils_base", - "ability_base" + "ipc_js", + "libuv", + "napi", + "relational_store", + "samgr", + "utils_base" ], - "third_party": [] + "third_party": [ + "libuv" + ] }, "build": { "group_type": { diff --git a/data_share/frameworks/js/napi/common/include/datashare_error.h b/data_share/frameworks/js/napi/common/include/datashare_error.h index 0c722746..31dfe495 100644 --- a/data_share/frameworks/js/napi/common/include/datashare_error.h +++ b/data_share/frameworks/js/napi/common/include/datashare_error.h @@ -26,6 +26,8 @@ public: static const int EXCEPTION_PARAMETER_CHECK = 401; static const int EXCEPTION_INNER = 15700000; static const int EXCEPTION_HELPER_UNINITIALIZED = 15700010; + static const int EXCEPTION_URI_NOT_EXIST = 15700011; + static const int EXCEPTION_DATA_AREA_NOT_EXIST = 15700012; virtual ~Error() {}; virtual std::string GetMessage() const = 0; virtual int GetCode() const = 0; diff --git a/data_share/frameworks/js/napi/common/include/datashare_error_impl.h b/data_share/frameworks/js/napi/common/include/datashare_error_impl.h index 3f14ec02..cf30fac1 100644 --- a/data_share/frameworks/js/napi/common/include/datashare_error_impl.h +++ b/data_share/frameworks/js/napi/common/include/datashare_error_impl.h @@ -63,6 +63,20 @@ private: int code_ = E_OK; std::string message_ = ""; }; + +class UriNotExistError : public Error { +public: + UriNotExistError() = default; + std::string GetMessage() const override; + int GetCode() const override; +}; + +class DataAreaNotExistError : public Error { +public: + DataAreaNotExistError() = default; + std::string GetMessage() const override; + int GetCode() const override; +}; } // namespace DataShare } // namespace OHOS #endif // DATASHARE_ERROR_IMPL_H 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 cf2630d3..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 @@ -25,8 +25,6 @@ #include "datashare_template.h" #include "datashare_value_object.h" #include "napi/native_api.h" -#include "napi/native_common.h" -#include "napi/native_node_api.h" #define NAPI_ASSERT_ERRCODE(env, assertion, error) \ do { \ @@ -70,12 +68,11 @@ public: static Template Convert2Template(napi_env env, napi_value value); static TemplateId Convert2TemplateId(napi_env env, napi_value value); static Data Convert2PublishedData(napi_env env, napi_value value); - static sptr Convert2Ashmem(napi_env env, napi_value value); static napi_value Convert2JSValue(napi_env env, const std::monostate &value = {}); static napi_value Convert2JSValue(napi_env env, const std::vector &value); static napi_value Convert2JSValue(napi_env env, const std::string &value); - static napi_value Convert2JSValue(napi_env env, const std::vector &value); + static napi_value Convert2JSValue(napi_env env, const std::vector &value, bool isTypedArray = true); static napi_value Convert2JSValue(napi_env env, int32_t value); static napi_value Convert2JSValue(napi_env env, int64_t value); static napi_value Convert2JSValue(napi_env env, double value); @@ -85,7 +82,6 @@ public: static napi_value Convert2JSValue(napi_env env, const std::variant &value); static napi_value Convert2JSValue(napi_env env, const TemplateId &templateId); static napi_value Convert2JSValue(napi_env env, const RdbChangeNode &changeNode); - static napi_value Convert2JSValue(napi_env env, sptr &ashmem); static napi_value Convert2JSValue(napi_env env, PublishedDataItem &publishedDataItem); static napi_value Convert2JSValue(napi_env env, std::vector &publishedDataItems); static napi_value Convert2JSValue(napi_env env, PublishedDataChangeNode &changeNode); diff --git a/data_share/frameworks/js/napi/common/include/napi_callbacks_manager.h b/data_share/frameworks/js/napi/common/include/napi_callbacks_manager.h new file mode 100644 index 00000000..c8936fd5 --- /dev/null +++ b/data_share/frameworks/js/napi/common/include/napi_callbacks_manager.h @@ -0,0 +1,187 @@ +/* + * 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 LDBPROJ_NAPI_CALLBACKS_MANAGER_H +#define LDBPROJ_NAPI_CALLBACKS_MANAGER_H +#include +#include +#include + +#include "datashare_errno.h" +#include "datashare_template.h" + +namespace OHOS::DataShare { +template +class NapiCallbacksManager { +public: + std::vector AddObservers(const std::vector &keys, const std::shared_ptr observer, + std::function &, const std::shared_ptr &observer, + std::vector &)>); + + std::vector DelObservers(const std::vector &keys, + const std::shared_ptr observer = nullptr, + std::function &, const std::shared_ptr &observer, + std::vector &)> processOnLastDel = NapiCallbacksManager::DefaultProcess); + + std::vector> GetEnabledObservers(const Key &); + + int GetEnabledSubscriberSize(); + +private: + static void DefaultProcess(const std::vector &, const std::shared_ptr &observer, + std::vector &){}; + struct ObserverNode { + std::shared_ptr observer_; + bool enabled_; + ObserverNode(const std::shared_ptr &observer) : observer_(observer) + { + enabled_ = true; + }; + ObserverNode(const std::shared_ptr &observer, bool enabled) + : observer_(observer), enabled_(enabled){}; + }; + bool IsRegistered(const Observer &, const std::vector &); + std::recursive_mutex mutex_{}; + std::map> callbacks_; +}; + +template +std::vector NapiCallbacksManager::AddObservers(const std::vector &keys, + const std::shared_ptr observer, std::function &, + const std::shared_ptr &observer, std::vector &)> processOnFirstAdd) +{ + std::vector result; + std::vector firstRegisterKey; + { + std::lock_guard lck(mutex_); + for (auto &key : keys) { + std::vector> enabledObservers = GetEnabledObservers(key); + if (enabledObservers.empty()) { + callbacks_[key].emplace_back(ObserverNode(observer)); + firstRegisterKey.emplace_back(key); + continue; + } + if (IsRegistered(*observer, callbacks_[key])) { + result.emplace_back(static_cast(key), E_REGISTERED_REPEATED); + continue; + } + callbacks_[key].emplace_back(observer); + result.emplace_back(key, E_OK); + } + } + processOnFirstAdd(firstRegisterKey, observer, result); + return result; +} + +template +bool NapiCallbacksManager::IsRegistered(const Observer &observer, + const std::vector &observers) +{ + for (auto &item : observers) { + if (*(item.observer_) == observer) { + return true; + } + } + return false; +} + +template +std::vector NapiCallbacksManager::DelObservers(const std::vector &keys, + const std::shared_ptr observer, + std::function &, const std::shared_ptr &, std::vector &)> + processOnLastDel) +{ + std::vector result; + std::vector lastDelKeys; + { + std::lock_guard lck(mutex_); + if (keys.empty() && observer == nullptr) { + for (auto &it : callbacks_) { + lastDelKeys.emplace_back(it.first); + } + callbacks_.clear(); + } + for (auto &key : keys) { + auto it = callbacks_.find(key); + if (it == callbacks_.end()) { + result.emplace_back(key, E_UNREGISTERED_EMPTY); + continue; + } + if (observer == nullptr) { + callbacks_.erase(key); + lastDelKeys.emplace_back(key); + continue; + } + if (!IsRegistered(*observer, it->second)) { + result.emplace_back(key, E_UNREGISTERED_EMPTY); + continue; + } + std::vector &callbacks = it->second; + auto callbackIt = callbacks.begin(); + while (callbackIt != callbacks.end()) { + if (!(*(callbackIt->observer_) == *observer)) { + callbackIt++; + continue; + } + callbackIt = callbacks.erase(callbackIt); + } + if (!it->second.empty()) { + result.emplace_back(key, E_OK); + continue; + } + callbacks_.erase(key); + lastDelKeys.emplace_back(key); + } + if (lastDelKeys.empty()) { + return result; + } + } + processOnLastDel(lastDelKeys, observer, result); + return result; +} + +template +std::vector> NapiCallbacksManager::GetEnabledObservers(const Key &inputKey) +{ + std::lock_guard lck(mutex_); + auto it = callbacks_.find(inputKey); + if (it == callbacks_.end()) { + return std::vector>(); + } + std::vector> results; + for (const auto &value : it->second) { + if (value.enabled_ && value.observer_ != nullptr) { + results.emplace_back(value.observer_); + } + } + return results; +} + +template +int NapiCallbacksManager::GetEnabledSubscriberSize() +{ + int count = 0; + std::lock_guard lck(mutex_); + for (auto &[key, value] : callbacks_) { + for (const auto &callback : value) { + if (callback.enabled_) { + count++; + } + } + } + return count; +} +} // namespace OHOS::DataShare +#endif //LDBPROJ_NAPI_CALLBACKS_MANAGER_H diff --git a/data_share/frameworks/js/napi/common/src/datashare_error_impl.cpp b/data_share/frameworks/js/napi/common/src/datashare_error_impl.cpp index 57a7f4b2..e3194776 100644 --- a/data_share/frameworks/js/napi/common/src/datashare_error_impl.cpp +++ b/data_share/frameworks/js/napi/common/src/datashare_error_impl.cpp @@ -66,5 +66,25 @@ std::string BusinessError::GetMessage() const { return message_; } + +std::string UriNotExistError::GetMessage() const +{ + return "The uri is not exist."; +} + +int UriNotExistError::GetCode() const +{ + return EXCEPTION_URI_NOT_EXIST; +} + +std::string DataAreaNotExistError::GetMessage() const +{ + return "The data area is not exist."; +} + +int DataAreaNotExistError::GetCode() const +{ + return EXCEPTION_DATA_AREA_NOT_EXIST; +} } // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/js/napi/common/src/datashare_js_utils.cpp b/data_share/frameworks/js/napi/common/src/datashare_js_utils.cpp index a0642273..194eac2b 100644 --- a/data_share/frameworks/js/napi/common/src/datashare_js_utils.cpp +++ b/data_share/frameworks/js/napi/common/src/datashare_js_utils.cpp @@ -59,19 +59,32 @@ std::vector DataShareJSUtils::Convert2StrVector(napi_env env, napi_ std::vector DataShareJSUtils::Convert2U8Vector(napi_env env, napi_value input_array) { bool isTypedArray = false; + bool isArrayBuffer = false; napi_is_typedarray(env, input_array, &isTypedArray); if (!isTypedArray) { - return {}; + napi_is_arraybuffer(env, input_array, &isArrayBuffer); + if (!isArrayBuffer) { + LOG_ERROR("unknow type"); + return {}; + } } - - napi_typedarray_type type; - napi_value input_buffer = nullptr; - size_t byte_offset = 0; size_t length = 0; void *data = nullptr; - napi_get_typedarray_info(env, input_array, &type, &length, &data, &input_buffer, &byte_offset); - if (type != napi_uint8_array || data == nullptr) { - return {}; + if (isTypedArray) { + napi_typedarray_type type; + napi_value input_buffer = nullptr; + size_t byte_offset = 0; + napi_get_typedarray_info(env, input_array, &type, &length, &data, &input_buffer, &byte_offset); + if (type != napi_uint8_array || data == nullptr) { + LOG_ERROR("napi_get_typedarray_info err"); + return {}; + } + } else { + napi_get_arraybuffer_info(env, input_array, &data, &length); + if (data == nullptr || length <= 0) { + LOG_ERROR("napi_get_arraybuffer_info err"); + return {}; + } } return std::vector((uint8_t *)data, ((uint8_t *)data) + length); } @@ -157,9 +170,8 @@ napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const std::string &va return jsValue; } -napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const std::vector &value) +napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const std::vector &value, bool isTypedArray) { - napi_value jsValue; void *native = nullptr; napi_value buffer = nullptr; if (value.empty()) { @@ -173,6 +185,10 @@ napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const std::vector 0) { return nullptr; } + if (!isTypedArray) { + return buffer; + } + napi_value jsValue; status = napi_create_typedarray(env, napi_uint8_array, value.size(), buffer, 0, &jsValue); if (status != napi_ok) { return nullptr; @@ -359,37 +375,6 @@ napi_value DataShareJSUtils::Convert2JSValue(napi_env env, const RdbChangeNode & return jsRdbChangeNode; } -napi_value DataShareJSUtils::Convert2JSValue(napi_env env, sptr &ashmem) -{ - napi_value global = nullptr; - napi_status status = napi_get_global(env, &global); - if (status != napi_ok) { - LOG_ERROR("get napi global failed"); - return nullptr; - } - napi_value constructor = nullptr; - status = napi_get_named_property(env, global, "AshmemConstructor_", &constructor); - if (status != napi_ok) { - LOG_ERROR("get Ashmem constructor failed"); - return nullptr; - } - napi_value jsAshmem; - status = napi_new_instance(env, constructor, 0, nullptr, &jsAshmem); - if (status != napi_ok) { - LOG_ERROR("failed to construct js Ashmem"); - return nullptr; - } - - NAPIAshmem *napiAshmem = nullptr; - napi_unwrap(env, jsAshmem, (void **)&napiAshmem); - if (napiAshmem == nullptr) { - LOG_ERROR("napiAshmem is null"); - return nullptr; - } - napiAshmem->SetAshmem(ashmem); - return jsAshmem; -} - napi_value DataShareJSUtils::Convert2JSValue(napi_env env, PublishedDataItem &publishedDataItem) { napi_value jsPublishedDataItem = nullptr; @@ -408,12 +393,7 @@ napi_value DataShareJSUtils::Convert2JSValue(napi_env env, PublishedDataItem &pu napi_value data = nullptr; if (publishedDataItem.IsAshmem()) { - sptr ashmem = publishedDataItem.MoveOutAshmem(); - if (ashmem == nullptr) { - LOG_ERROR("MoveOutAshmem null Ashmem"); - return nullptr; - } - data = Convert2JSValue(env, ashmem); + data = Convert2JSValue(env, std::get>(publishedDataItem.GetData()), false); } else { data = Convert2JSValue(env, std::get(publishedDataItem.GetData())); } @@ -599,15 +579,13 @@ bool DataShareJSUtils::UnwrapPublishedDataItem(napi_env env, napi_value jsObject napi_value jsDataValue = nullptr; napi_get_property(env, jsObject, jsDataKey, &jsDataValue); napi_typeof(env, jsDataValue, &valueType); + PublishedDataItem::DataType value; if (valueType == napi_object) { - sptr ashmem = Convert2Ashmem(env, jsDataValue); - if (ashmem == nullptr) { - LOG_ERROR("Convert ashmem failed"); - return false; - } - publishedDataItem.SetAshmem(ashmem); + value = Convert2U8Vector(env, jsDataValue); + publishedDataItem.Set(value); } else if (valueType == napi_string) { - publishedDataItem.Set(Convert2String(env, jsDataValue)); + value = Convert2String(env, jsDataValue); + publishedDataItem.Set(value); } else { LOG_ERROR("Convert dataValue failed, type is %{public}d", valueType); return false; @@ -679,32 +657,6 @@ Data DataShareJSUtils::Convert2PublishedData(napi_env env, napi_value value) return data; } -sptr DataShareJSUtils::Convert2Ashmem(napi_env env, napi_value value) -{ - napi_value global = nullptr; - napi_get_global(env, &global); - napi_value constructor = nullptr; - napi_status status = napi_get_named_property(env, global, "AshmemConstructor_", &constructor); - if (status != napi_ok) { - LOG_ERROR("get Ashmem constructor failed"); - return nullptr; - } - bool isAshmem = false; - napi_instanceof(env, value, constructor, &isAshmem); - if (!isAshmem) { - LOG_ERROR("parameter is not instanceof Ashmem"); - return nullptr; - } - NAPIAshmem *napiAshmem = nullptr; - napi_unwrap(env, value, (void **)&napiAshmem); - if (napiAshmem == nullptr) { - LOG_ERROR("napiAshmem is null"); - return nullptr; - } - sptr nativeAshmem = napiAshmem->GetAshmem(); - return nativeAshmem; -} - bool DataShareJSUtils::UnwrapStringByPropertyName( napi_env env, napi_value jsObject, const char *propertyName, std::string &value) { diff --git a/data_share/frameworks/js/napi/common/src/datashare_predicates_proxy.cpp b/data_share/frameworks/js/napi/common/src/datashare_predicates_proxy.cpp index 13e22552..47287de2 100644 --- a/data_share/frameworks/js/napi/common/src/datashare_predicates_proxy.cpp +++ b/data_share/frameworks/js/napi/common/src/datashare_predicates_proxy.cpp @@ -696,9 +696,9 @@ napi_value DataSharePredicatesProxy::Limit(napi_env env, napi_callback_info info napi_get_cb_info(env, info, &argc, args, &thiz, nullptr); NAPI_ASSERT(env, argc > 1, "Invalid argvs!"); int number = 0; - napi_status status = napi_get_value_int32(env, args[0], &number); + napi_get_value_int32(env, args[0], &number); int offset = 0; - status = napi_get_value_int32(env, args[1], &offset); + napi_get_value_int32(env, args[1], &offset); auto nativePredicates = GetNativePredicates(env, info); if (nativePredicates == nullptr) { LOG_ERROR("GetNativePredicates failed."); diff --git a/data_share/frameworks/js/napi/dataShare/BUILD.gn b/data_share/frameworks/js/napi/dataShare/BUILD.gn index f7e68b1d..0f58291d 100644 --- a/data_share/frameworks/js/napi/dataShare/BUILD.gn +++ b/data_share/frameworks/js/napi/dataShare/BUILD.gn @@ -33,8 +33,7 @@ ohos_shared_library("datashare") { ] deps = [ - "${ability_runtime_inner_api_path}/dataobs_manager:dataobs_manager", - "${ability_runtime_napi_path}/inner/napi_common:napi_common", + "${datashare_innerapi_path}:datashare_consumer", "${datashare_innerapi_path}/common:datashare_common", "//third_party/libuv:uv", ] @@ -44,11 +43,11 @@ ohos_shared_library("datashare") { "ability_base:want", "ability_base:zuri", "ability_runtime:abilitykit_native", + "ability_runtime:dataobs_manager", "ability_runtime:napi_base_context", + "ability_runtime:napi_common", "c_utils:utils", "common_event_service:cesfwk_innerkits", - "data_share:datashare_common", - "data_share:datashare_consumer", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_single", "napi:ace_napi", @@ -71,12 +70,13 @@ ohos_shared_library("datasharepredicates") { "${datashare_napi_path}/dataShare/src/native_datashare_predicates_module.cpp", ] - deps = [ "${datashare_innerapi_path}/common:datashare_common" ] + deps = [ + "${datashare_innerapi_path}:datashare_consumer", + "${datashare_innerapi_path}/common:datashare_common", + ] external_deps = [ "c_utils:utils", - "data_share:datashare_common", - "data_share:datashare_consumer", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_single", "napi:ace_napi", diff --git a/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp b/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp index bd335a96..ae772fcc 100644 --- a/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp +++ b/data_share/frameworks/js/napi/dataShare/src/napi_datashare_helper.cpp @@ -210,13 +210,6 @@ napi_value NapiDataShareHelper::Initialize(napi_env env, napi_callback_info info } auto finalize = [](napi_env env, void *data, void *hint) { NapiDataShareHelper *proxy = reinterpret_cast(data); - if (proxy->jsRdbObsManager_ == nullptr || proxy->jsPublishedObsManager_ == nullptr) { - LOG_ERROR("proxy->jsManager_ is nullptr"); - delete proxy; - return; - } - proxy->jsRdbObsManager_->DelObservers(env, nullptr); - proxy->jsPublishedObsManager_->DelObservers(env, nullptr); delete proxy; }; if (napi_wrap(env, self, proxy, finalize, nullptr, nullptr) != napi_ok) { @@ -676,6 +669,8 @@ napi_value NapiDataShareHelper::Napi_AddTemplate(napi_env env, napi_callback_inf Template tpl = DataShareJSUtils::Convert2Template(env, argv[PARAM2]); auto res = proxy->datashareHelper_->AddQueryTemplate(uri, atoll(subscriberId.c_str()), tpl); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, res != E_URI_NOT_EXIST && res != E_BUNDLE_NAME_NOT_EXIST, + error = std::make_shared(), error, nullptr); return DataShareJSUtils::Convert2JSValue(env, res); } @@ -707,6 +702,8 @@ napi_value NapiDataShareHelper::Napi_DelTemplate(napi_env env, napi_callback_inf std::string subscriberId = DataShareJSUtils::Convert2String(env, argv[1]); auto res = proxy->datashareHelper_->DelQueryTemplate(uri, atoll(subscriberId.c_str())); + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, res != E_URI_NOT_EXIST && res != E_BUNDLE_NAME_NOT_EXIST, + error = std::make_shared(), error, nullptr); return DataShareJSUtils::Convert2JSValue(env, res); } @@ -737,6 +734,12 @@ napi_value NapiDataShareHelper::Napi_Publish(napi_env env, napi_callback_info in }; auto output = [context](napi_env env, napi_value *result) -> napi_status { NAPI_ASSERT_BASE(env, context->status == napi_ok, "exec failed", napi_generic_failure); + for (auto &operationResult : context->results) { + if (operationResult.errCode_ == E_BUNDLE_NAME_NOT_EXIST) { + context->error = std::make_shared(); + return napi_generic_failure; + } + } *result = DataShareJSUtils::Convert2JSValue(env, context->results); context->results.clear(); return napi_ok; @@ -772,6 +775,10 @@ napi_value NapiDataShareHelper::Napi_GetPublishedData(napi_env env, napi_callbac }; auto output = [context](napi_env env, napi_value *result) -> napi_status { NAPI_ASSERT_BASE(env, context->status == napi_ok, "exec failed", napi_generic_failure); + if (context->resultNumber == E_BUNDLE_NAME_NOT_EXIST) { + context->error = std::make_shared(); + return napi_generic_failure; + } *result = DataShareJSUtils::Convert2JSValue(env, context->publishData.datas_); return napi_ok; }; @@ -780,7 +787,8 @@ napi_value NapiDataShareHelper::Napi_GetPublishedData(napi_env env, napi_callbac LOG_ERROR("dataShareHelper_ is nullptr"); return; } - context->publishData = context->proxy->datashareHelper_->GetPublishedData(context->bundleName); + context->publishData = context->proxy->datashareHelper_->GetPublishedData(context->bundleName, + context->resultNumber); context->status = napi_ok; }; context->SetAction(std::move(input), std::move(output)); @@ -1089,7 +1097,7 @@ napi_value NapiDataShareHelper::Napi_UnsubscribePublishedObserver(napi_env env, DataShareJSUtils::Convert2StrVector(env, argv[1], DataShareJSUtils::DEFAULT_BUF_SIZE); NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valueType)); - NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_number, + NAPI_ASSERT_CALL_ERRCODE_SYNC(env, valueType == napi_string, error = std::make_shared("subscriberId", "string"), error, jsResults); std::string subscriberId = DataShareJSUtils::Convert2String(env, argv[PARAM2]); if (proxy->jsPublishedObsManager_ == nullptr) { 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 264d6d7c..0a472814 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 @@ -19,7 +19,7 @@ #include #include -#include "callbacks_manager.h" +#include "napi_callbacks_manager.h" #include "datashare_helper.h" #include "napi/native_api.h" #include "napi/native_common.h" @@ -28,35 +28,85 @@ namespace OHOS { namespace DataShare { -class NapiRdbSubscriberManager : public CallbacksManager { +struct NapiRdbObserverMapKey { + std::string uri_; + TemplateId templateId_; + NapiRdbObserverMapKey(const std::string &uri, const TemplateId &templateId) : uri_(uri), templateId_(templateId){}; + bool operator==(const NapiRdbObserverMapKey &node) const + { + return uri_ == node.uri_ && templateId_ == node.templateId_; + } + bool operator!=(const NapiRdbObserverMapKey &node) const + { + return !(node == *this); + } + bool operator<(const NapiRdbObserverMapKey &node) const + { + if (uri_ != node.uri_) { + return uri_ < node.uri_; + } + return templateId_ < node.templateId_; + } + operator std::string() const + { + return uri_; + } +}; + +class NapiRdbSubscriberManager : public NapiCallbacksManager { public: - using Key = RdbObserverMapKey; + using Key = NapiRdbObserverMapKey; using Observer = NapiRdbObserver; - using BaseCallbacks = CallbacksManager; + using BaseCallbacks = NapiCallbacksManager; explicit NapiRdbSubscriberManager(std::weak_ptr dataShareHelper) : dataShareHelper_(dataShareHelper){}; std::vector AddObservers(napi_env env, napi_value callback, const std::vector &uris, const TemplateId &templateId); std::vector DelObservers(napi_env env, napi_value callback, - const std::vector &uris = std::vector(), - const TemplateId &templateId = TemplateId()); + const std::vector &uris, const TemplateId &templateId); void Emit(const RdbChangeNode &changeNode); private: std::weak_ptr dataShareHelper_; }; -class NapiPublishedSubscriberManager : public CallbacksManager { +struct NapiPublishedObserverMapKey { + std::string uri_; + int64_t subscriberId_; + NapiPublishedObserverMapKey(const std::string &uri, int64_t subscriberId) : uri_(uri), + subscriberId_(subscriberId){}; + bool operator==(const NapiPublishedObserverMapKey &node) const + { + return uri_ == node.uri_ && subscriberId_ == node.subscriberId_; + } + bool operator!=(const NapiPublishedObserverMapKey &node) const + { + return !(node == *this); + } + bool operator<(const NapiPublishedObserverMapKey &node) const + { + if (uri_ != node.uri_) { + return uri_ < node.uri_; + } + return subscriberId_ < node.subscriberId_; + } + operator std::string() const + { + return uri_; + } +}; + +class NapiPublishedSubscriberManager : public NapiCallbacksManager { public: - using Key = PublishedObserverMapKey; + using Key = NapiPublishedObserverMapKey; using Observer = NapiPublishedObserver; - using BaseCallbacks = CallbacksManager; + using BaseCallbacks = NapiCallbacksManager; explicit NapiPublishedSubscriberManager(std::weak_ptr dataShareHelper) : dataShareHelper_(dataShareHelper){}; std::vector AddObservers(napi_env env, napi_value callback, const std::vector &uris, int64_t subscriberId); std::vector DelObservers(napi_env env, napi_value callback, - const std::vector &uris = std::vector(), int64_t subscriberId = 0); + const std::vector &uris, int64_t subscriberId); void Emit(const PublishedDataChangeNode &changeNode); private: diff --git a/data_share/frameworks/js/napi/observer/src/napi_observer.cpp b/data_share/frameworks/js/napi/observer/src/napi_observer.cpp index 2ce5e148..d21d16ed 100644 --- a/data_share/frameworks/js/napi/observer/src/napi_observer.cpp +++ b/data_share/frameworks/js/napi/observer/src/napi_observer.cpp @@ -76,7 +76,7 @@ bool NapiObserver::operator==(const NapiObserver &rhs) const napi_get_reference_value(env_, ref_, &value1); napi_value value2 = nullptr; - napi_get_reference_value(env_, ref_, &value2); + napi_get_reference_value(env_, rhs.ref_, &value2); bool isEqual = false; napi_strict_equals(env_, value1, value2, &isEqual); diff --git a/data_share/frameworks/js/napi/observer/src/napi_subscriber_manager.cpp b/data_share/frameworks/js/napi/observer/src/napi_subscriber_manager.cpp index ffd6bf19..f686ff91 100644 --- a/data_share/frameworks/js/napi/observer/src/napi_subscriber_manager.cpp +++ b/data_share/frameworks/js/napi/observer/src/napi_subscriber_manager.cpp @@ -19,8 +19,8 @@ namespace OHOS { namespace DataShare { -std::vector NapiRdbSubscriberManager::AddObservers( - napi_env env, napi_value callback, const std::vector &uris, const TemplateId &templateId) +std::vector NapiRdbSubscriberManager::AddObservers(napi_env env, napi_value callback, + const std::vector &uris, const TemplateId &templateId) { auto datashareHelper = dataShareHelper_.lock(); if (datashareHelper == nullptr) { @@ -60,8 +60,8 @@ std::vector NapiRdbSubscriberManager::AddObservers( }); } -std::vector NapiRdbSubscriberManager::DelObservers( - napi_env env, napi_value callback, const std::vector &uris, const TemplateId &templateId) +std::vector NapiRdbSubscriberManager::DelObservers(napi_env env, napi_value callback, + const std::vector &uris, const TemplateId &templateId) { auto dataShareHelper = dataShareHelper_.lock(); if (dataShareHelper == nullptr) { @@ -72,16 +72,9 @@ std::vector NapiRdbSubscriberManager::DelObservers( std::for_each(uris.begin(), uris.end(), [&keys, &templateId](auto &uri) { keys.emplace_back(uri, templateId); }); - return BaseCallbacks::DelObservers(keys, - callback == nullptr ? nullptr : std::make_shared(env, callback), - [&dataShareHelper, &templateId, &callback, &uris](const std::vector &lastDelKeys, - const std::shared_ptr &observer, std::vector &opResult) { - // delete all obs - if (callback == nullptr && uris.empty()) { - dataShareHelper->UnsubscribeRdbData(); - return; - } - + return BaseCallbacks::DelObservers(keys, callback == nullptr ? nullptr : std::make_shared(env, callback), + [&dataShareHelper, &templateId](const std::vector &lastDelKeys, const std::shared_ptr &observer, + std::vector &opResult) { std::vector lastDelUris; std::for_each(lastDelKeys.begin(), lastDelKeys.end(), [&lastDelUris](auto &result) { lastDelUris.emplace_back(result); @@ -105,8 +98,8 @@ void NapiRdbSubscriberManager::Emit(const RdbChangeNode &changeNode) } } -std::vector NapiPublishedSubscriberManager::AddObservers( - napi_env env, napi_value callback, const std::vector &uris, int64_t subscriberId) +std::vector NapiPublishedSubscriberManager::AddObservers(napi_env env, napi_value callback, + const std::vector &uris, int64_t subscriberId) { auto dataShareHelper = dataShareHelper_.lock(); if (dataShareHelper == nullptr) { @@ -128,8 +121,8 @@ std::vector NapiPublishedSubscriberManager::AddObservers( if (firstAddUris.empty()) { return; } - auto subResults = dataShareHelper->SubscribePublishedData( - firstAddUris, subscriberId, [this](const PublishedDataChangeNode &changeNode) { + auto subResults = dataShareHelper->SubscribePublishedData(firstAddUris, subscriberId, + [this](const PublishedDataChangeNode &changeNode) { Emit(changeNode); }); std::vector failedKeys; @@ -146,8 +139,8 @@ std::vector NapiPublishedSubscriberManager::AddObservers( }); } -std::vector NapiPublishedSubscriberManager::DelObservers( - napi_env env, napi_value callback, const std::vector &uris, int64_t subscriberId) +std::vector NapiPublishedSubscriberManager::DelObservers(napi_env env, napi_value callback, + const std::vector &uris, int64_t subscriberId) { auto dataShareHelper = dataShareHelper_.lock(); if (dataShareHelper == nullptr) { @@ -158,16 +151,9 @@ std::vector NapiPublishedSubscriberManager::DelObservers( std::for_each(uris.begin(), uris.end(), [&keys, &subscriberId](auto &uri) { keys.emplace_back(uri, subscriberId); }); - return BaseCallbacks::DelObservers(keys, - callback == nullptr ? nullptr : std::make_shared(env, callback), + return BaseCallbacks::DelObservers(keys, callback == nullptr ? nullptr : std::make_shared(env, callback), [&dataShareHelper, &subscriberId, &callback, &uris](const std::vector &lastDelKeys, const std::shared_ptr &observer, std::vector &opResult) { - // delete all obs - if (callback == nullptr && uris.empty()) { - dataShareHelper->UnsubscribePublishedData(); - return; - } - std::vector lastDelUris; std::for_each(lastDelKeys.begin(), lastDelKeys.end(), [&lastDelUris](auto &result) { lastDelUris.emplace_back(result); @@ -184,7 +170,7 @@ void NapiPublishedSubscriberManager::Emit(const PublishedDataChangeNode &changeN { std::map, PublishedDataChangeNode> results; for (auto &data : changeNode.datas_) { - PublishedObserverMapKey key(data.key_, data.subscriberId_); + Key key(data.key_, data.subscriberId_); auto callbacks = BaseCallbacks::GetEnabledObservers(key); if (callbacks.empty()) { LOG_WARN("%{private}s nobody subscribe, but still notify", data.key_.c_str()); diff --git a/data_share/frameworks/native/common/include/base_proxy.h b/data_share/frameworks/native/common/include/base_proxy.h deleted file mode 100644 index 4de2110a..00000000 --- a/data_share/frameworks/native/common/include/base_proxy.h +++ /dev/null @@ -1,227 +0,0 @@ -/* - * 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. - */ - -#include -#include - -#include "data_proxy_observer.h" -#include "datashare_business_error.h" -#include "datashare_predicates.h" -#include "datashare_result_set.h" -#include "datashare_template.h" -#include "datashare_values_bucket.h" -#include "uri.h" - -#ifndef DATA_SHARE_BASE_PROXY_H -#define DATA_SHARE_BASE_PROXY_H -namespace OHOS { -namespace AAFwk { - class IDataAbilityObserver; -} - -namespace DataShare { -class BaseProxy { -public: - virtual ~BaseProxy() = default; - - /** - * @brief Opens a file in a specified remote path. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, - * or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the file descriptor. - */ - virtual int OpenFile(const Uri &uri, const std::string &mode) = 0; - - /** - * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets - * inside of their .hap. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing - * data, or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the RawFileDescriptor object containing file descriptor. - */ - virtual int OpenRawFile(const Uri &uri, const std::string &mode) = 0; - - /** - * @brief Inserts a single data record into the database. - * - * @param uri Indicates the path of the data to operate. - * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. - * - * @return Returns the index of the inserted data record. - */ - virtual int Insert(const Uri &uri, const DataShareValuesBucket &value) = 0; - - /** - * @brief Updates data records in the database. - * - * @param uri Indicates the path of data to update. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @param value Indicates the data to update. This parameter can be null. - * - * @return Returns the number of data records updated. - */ - virtual int Update(const Uri &uri, const DataSharePredicates &predicates, - const DataShareValuesBucket &value) = 0; - - /** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of the data to operate. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records deleted. - */ - virtual int Delete(const Uri &uri, const DataSharePredicates &predicates) = 0; - - /** - * @brief Query records from the database. - * - * @param uri Indicates the path of data to query. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. - * @param businessError Indicates the error by query. - * - * @return Returns the query result. - */ - virtual std::shared_ptr Query(const Uri &uri, const DataSharePredicates &predicates, - std::vector &columns, DatashareBusinessError &businessError) = 0; - - /** - * @brief Obtains the MIME type matching the data specified by the URI of the Data ability. This method should be - * implemented by a Data ability. Data abilities supports general data types, including text, HTML, and JPEG. - * - * @param uri Indicates the URI of the data. - * - * @return Returns the MIME type that matches the data specified by uri. - */ - virtual std::string GetType(const Uri &uri) = 0; - - /** - * @brief Inserts multiple data records into the database. - * - * @param uri Indicates the path of the data to operate. - * @param values Indicates the data records to insert. - * - * @return Returns the number of data records inserted. - */ - virtual int BatchInsert(const Uri &uri, const std::vector &values) = 0; - - /** - * @brief Registers an observer to DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - virtual bool RegisterObserver(const Uri &uri, const sptr &dataObserver) = 0; - - /** - * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ - virtual bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) = 0; - - /** - * @brief Notifies the registered observers of a change to the data resource specified by Uri. - * - * @param uri, Indicates the path of the data to operate. - * - * @return Return true if success. otherwise return false. - */ - virtual bool NotifyChange(const Uri &uri) = 0; - - /** - * @brief Converts the given uri that refer to the Data ability into a normalized URI. A normalized URI can be used - * across devices, persisted, backed up, and restored. It can refer to the same item in the Data ability even if - * the context has changed. If you implement URI normalization for a Data ability, you must also implement - * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to - * any method that is called on the Data ability must require normalization verification and denormalization. The - * default implementation of this method returns null, indicating that this Data ability does not support URI - * normalization. - * - * @param uri Indicates the Uri object to normalize. - * - * @return Returns the normalized Uri object if the Data ability supports URI normalization; returns null otherwise. - */ - virtual Uri NormalizeUri(const Uri &uri) = 0; - - /** - * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. - * The default implementation of this method returns the original URI passed to it. - * - * @param uri uri Indicates the Uri object to denormalize. - * - * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri - * passed to this method if there is nothing to do; returns null if the data identified by the original Uri cannot - * be found in the current environment. - */ - virtual Uri DenormalizeUri(const Uri &uri) = 0; - - /** - * @brief Obtains the MIME types of files supported. - * - * @param uri Indicates the path of the files to obtain. - * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. - * - * @return Returns the matched MIME types. If there is no match, null is returned. - */ - virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) = 0; - - virtual int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) = 0; - - virtual int DelQueryTemplate(const std::string &uri, int64_t subscriberId) = 0; - - virtual std::vector Publish(const Data &data, const std::string &bundleName) = 0; - - virtual Data GetPublishedData(const std::string &bundleName) = 0; - - virtual std::vector SubscribeRdbData(const std::vector &uris, - const TemplateId &templateId, const sptr &observer) = 0; - - virtual std::vector UnSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) = 0; - - virtual std::vector EnableSubscribeRdbData(const std::vector &uris, - const TemplateId &templateId) = 0; - - virtual std::vector DisableSubscribeRdbData(const std::vector &uris, - const TemplateId &templateId) = 0; - - virtual std::vector SubscribePublishedData(const std::vector &uris, - int64_t subscriberId, const sptr &observer) = 0; - - virtual std::vector UnSubscribePublishedData(const std::vector &uris, - int64_t subscriberId) = 0; - - virtual std::vector EnableSubscribePublishedData(const std::vector &uris, - int64_t subscriberId) = 0; - - virtual std::vector DisableSubscribePublishedData(const std::vector &uris, - int64_t subscriberId) = 0; -}; -} -} -#endif // DATA_SHARE_BASE_PROXY_H diff --git a/data_share/frameworks/native/common/include/callbacks_manager.h b/data_share/frameworks/native/common/include/callbacks_manager.h index ea5cd55c..43ddf0a9 100644 --- a/data_share/frameworks/native/common/include/callbacks_manager.h +++ b/data_share/frameworks/native/common/include/callbacks_manager.h @@ -26,46 +26,55 @@ namespace OHOS::DataShare { template class CallbacksManager { public: - std::vector AddObservers(const std::vector &keys, const std::shared_ptr observer, - std::function &, const std::shared_ptr &observer, std::vector &)>); - std::vector DelObservers(const std::vector &keys, - const std::shared_ptr observer = nullptr, - std::function &, const std::shared_ptr &observer, std::vector &)> - processOnLastDel = CallbacksManager::DefaultProcess); - std::vector EnableObservers( - const std::vector &keys, std::function &, std::vector &)>); - - std::vector DisableObservers(const std::vector &keys, + std::vector AddObservers(const std::vector &keys, void *subscriber, + const std::shared_ptr observer, + std::function &, const std::shared_ptr &observer, + std::vector &)>); + + std::vector DelObservers(const std::vector &keys, void *subscriber, + std::function &, std::vector &)> processOnLastDel = + CallbacksManager::DefaultProcess); + + std::vector DelObservers(void *subscriber, + std::function &, std::vector &)> processOnLastDel = + CallbacksManager::DefaultProcess); + + std::vector EnableObservers(const std::vector &keys, void *subscriber, + std::function &, std::vector &)>); + + std::vector DisableObservers(const std::vector &keys, void *subscriber, std::function &, std::vector &)> processOnLastDel = - CallbacksManager::DefaultProcess2); + CallbacksManager::DefaultProcess); + std::vector> GetEnabledObservers(const Key &); + int GetEnabledSubscriberSize(); + int GetEnabledSubscriberSize(const Key &key); + void RecoverObservers(std::function &)> recoverObservers); + private: - static void DefaultProcess2(const std::vector &, std::vector &){}; - static void DefaultProcess( - const std::vector &, const std::shared_ptr &observer, std::vector &){}; + static void DefaultProcess(const std::vector &, std::vector &){}; struct ObserverNode { std::shared_ptr observer_; bool enabled_; - ObserverNode(const std::shared_ptr &observer) : observer_(observer) + void *subscriber_; + ObserverNode(const std::shared_ptr &observer, void *subscriber) + : observer_(observer), subscriber_(subscriber) { enabled_ = true; }; - ObserverNode(const std::shared_ptr &observer, bool enabled) - : observer_(observer), enabled_(enabled){}; }; - bool IsRegistered(const Observer &, const std::vector &); + void DelLocalObservers(const Key &key, void *subscriber, std::vector &lastDelKeys, + std::vector &result); + void DelLocalObservers(void *subscriber, std::vector &lastDelKeys, std::vector &result); std::recursive_mutex mutex_{}; std::map> callbacks_; }; template std::vector CallbacksManager::AddObservers(const std::vector &keys, - const std::shared_ptr observer, - std::function &, const std::shared_ptr &observer, - std::vector &)> processOnFirstAdd) + void *subscriber, const std::shared_ptr observer, std::function &, + const std::shared_ptr &observer, std::vector &)> processOnFirstAdd) { std::vector result; std::vector firstRegisterKey; @@ -73,16 +82,12 @@ std::vector CallbacksManager::AddObservers(const std::lock_guard lck(mutex_); for (auto &key : keys) { std::vector> enabledObservers = GetEnabledObservers(key); - if (enabledObservers.size() == 0) { - callbacks_[key].emplace_back(ObserverNode(observer)); + if (enabledObservers.empty()) { + callbacks_[key].emplace_back(observer, subscriber); firstRegisterKey.emplace_back(key); continue; } - if (IsRegistered(*observer, callbacks_[key])) { - result.emplace_back(static_cast(key), E_REGISTERED_REPEATED); - continue; - } - callbacks_[key].emplace_back(observer); + callbacks_[key].emplace_back(observer, subscriber); result.emplace_back(key, E_OK); } } @@ -91,67 +96,94 @@ std::vector CallbacksManager::AddObservers(const } template -bool CallbacksManager::IsRegistered(const Observer &observer, const std::vector &observers) +void CallbacksManager::RecoverObservers(std::function &)> recoverObservers) { - for (auto &item : observers) { - if (*(item.observer_) == observer) { - return true; + std::vector keys; + { + std::lock_guard lck(mutex_); + for (auto &it : callbacks_) { + if (GetEnabledSubscriberSize(it.first) > 0) { + keys.emplace_back(it.first); + } } } - return false; + recoverObservers(keys); } + template -std::vector CallbacksManager::DelObservers(const std::vector &keys, - const std::shared_ptr observer, std::function &, - const std::shared_ptr &, std::vector &)> processOnLastDel) +void CallbacksManager::DelLocalObservers(void *subscriber, std::vector &lastDelKeys, + std::vector &result) +{ + for (auto &it : callbacks_) { + DelLocalObservers(it.first, subscriber, lastDelKeys, result); + } +} + +template +void CallbacksManager::DelLocalObservers(const Key &key, void *subscriber, + std::vector &lastDelKeys, std::vector &result) +{ + auto it = callbacks_.find(key); + if (it == callbacks_.end()) { + result.emplace_back(key, E_UNREGISTERED_EMPTY); + return; + } + std::vector &callbacks = it->second; + auto callbackIt = callbacks.begin(); + while (callbackIt != callbacks.end()) { + if (callbackIt->subscriber_ != subscriber) { + callbackIt++; + continue; + } + callbackIt = callbacks.erase(callbackIt); + } + if (!it->second.empty()) { + result.emplace_back(key, E_OK); + return; + } + lastDelKeys.emplace_back(key); +} + +template +std::vector CallbacksManager::DelObservers(void *subscriber, + std::function &, std::vector &)> processOnLastDel) { std::vector result; std::vector lastDelKeys; { std::lock_guard lck(mutex_); - if (keys.empty() && observer == nullptr) { - for (auto &it : callbacks_) { - lastDelKeys.emplace_back(it.first); - } - callbacks_.clear(); + DelLocalObservers(subscriber, lastDelKeys, result); + if (lastDelKeys.empty()) { + return result; } - for (auto &key : keys) { - auto it = callbacks_.find(key); - if (it == callbacks_.end()) { - result.emplace_back(key, E_UNREGISTERED_EMPTY); - continue; - } - if (observer == nullptr) { - callbacks_.erase(key); - lastDelKeys.emplace_back(key); - continue; - } - if (!IsRegistered(*observer, it->second)) { - result.emplace_back(key, E_UNREGISTERED_EMPTY); - continue; - } - std::vector &callbacks = it->second; - auto callbackIt = callbacks.begin(); - while (callbackIt != callbacks.end()) { - if (!(*(callbackIt->observer_) == *observer)) { - callbackIt++; - continue; - } - callbackIt = callbacks.erase(callbackIt); - } - if (!it->second.empty()) { - result.emplace_back(key, E_OK); - continue; - } + for (auto &key : lastDelKeys) { callbacks_.erase(key); - lastDelKeys.emplace_back(key); + } + } + processOnLastDel(lastDelKeys, result); + return result; +} + +template +std::vector CallbacksManager::DelObservers(const std::vector &keys, + void *subscriber, std::function &, std::vector &)> processOnLastDel) +{ + std::vector result; + std::vector lastDelKeys; + { + std::lock_guard lck(mutex_); + for (auto &key : keys) { + DelLocalObservers(key, subscriber, lastDelKeys, result); } if (lastDelKeys.empty()) { return result; } + for (auto &key : lastDelKeys) { + callbacks_.erase(key); + } } - processOnLastDel(lastDelKeys, observer, result); + processOnLastDel(lastDelKeys, result); return result; } @@ -173,7 +205,8 @@ std::vector> CallbacksManager::GetEnabl } template -std::vector CallbacksManager::EnableObservers(const std::vector &keys, +std::vector CallbacksManager::EnableObservers( + const std::vector &keys, void *subscriber, std::function &, std::vector &)> processOnFirstEnabled) { std::vector result; @@ -187,8 +220,16 @@ std::vector CallbacksManager::EnableObservers(co continue; } std::vector> enabledObservers = GetEnabledObservers(key); - for (auto &item: callbacks_[key]) { - item.enabled_ = true; + bool hasEnabled = false; + for (auto &item : callbacks_[key]) { + if (item.subscriber_ == subscriber) { + item.enabled_ = true; + hasEnabled = true; + } + } + if (!hasEnabled) { + result.emplace_back(key, E_SUBSCRIBER_NOT_EXIST); + continue; } if (!enabledObservers.empty()) { result.emplace_back(key, E_OK); @@ -202,7 +243,8 @@ std::vector CallbacksManager::EnableObservers(co } template -std::vector CallbacksManager::DisableObservers(const std::vector &keys, +std::vector CallbacksManager::DisableObservers( + const std::vector &keys, void *subscriber, std::function &, std::vector &)> processOnLastDisable) { std::vector result; @@ -216,10 +258,24 @@ std::vector CallbacksManager::DisableObservers(c continue; } std::vector> enabledObservers = GetEnabledObservers(key); - for (auto &item: callbacks_[key]) { - item.enabled_ = false; - } if (enabledObservers.empty()) { + result.emplace_back(key, E_SUBSCRIBER_NOT_EXIST); + continue; + } + + bool hasDisabled = false; + for (auto &item : callbacks_[key]) { + if (item.subscriber_ == subscriber) { + item.enabled_ = false; + hasDisabled = true; + } + } + if (!hasDisabled) { + result.emplace_back(key, E_SUBSCRIBER_NOT_EXIST); + continue; + } + enabledObservers = GetEnabledObservers(key); + if (!enabledObservers.empty()) { result.emplace_back(key, E_OK); continue; } @@ -229,16 +285,31 @@ std::vector CallbacksManager::DisableObservers(c processOnLastDisable(lastDisabledKeys, result); return result; } + template int CallbacksManager::GetEnabledSubscriberSize() { int count = 0; std::lock_guard lck(mutex_); for (auto &[key, value] : callbacks_) { - for (const auto &callback:value) { - if (callback.enabled_) { - count++; - } + count += GetEnabledSubscriberSize(key); + } + return count; +} + +template +int CallbacksManager::GetEnabledSubscriberSize(const Key &key) +{ + std::lock_guard lck(mutex_); + int count = 0; + auto it = callbacks_.find(key); + if (it == callbacks_.end()) { + return count; + } + std::vector &callbacks = it->second; + for (const auto &callback : callbacks) { + if (callback.enabled_) { + count++; } } return count; diff --git a/data_share/frameworks/native/common/include/datashare_log.h b/data_share/frameworks/native/common/include/datashare_log.h index 7f802535..0d8e5964 100644 --- a/data_share/frameworks/native/common/include/datashare_log.h +++ b/data_share/frameworks/native/common/include/datashare_log.h @@ -16,31 +16,65 @@ #ifndef DATASHARE_LOG_PRINT_H #define DATASHARE_LOG_PRINT_H -#ifndef LOG_TAG -#define LOG_TAG -#endif - #include "hilog/log.h" namespace OHOS::DataShare { -static const OHOS::HiviewDFX::HiLogLabel DATASHARE_LABEL = { LOG_CORE, 0xD001651, "DataShare" }; - -#define __FILENAME__ (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__) - -#define LOG_DEBUG(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Debug(DATASHARE_LABEL, \ - "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__) -#define LOG_INFO(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Info(DATASHARE_LABEL, \ - "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__) -#define LOG_WARN(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Warn(DATASHARE_LABEL, \ - "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__) -#define LOG_ERROR(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Error(DATASHARE_LABEL, \ - "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__) -#define LOG_FATAL(fmt, ...) \ - (void)OHOS::HiviewDFX::HiLog::Fatal(DATASHARE_LABEL, \ - "[%{public}s(%{public}s:%{public}d)]" fmt, __FILENAME__, __FUNCTION__, __LINE__, ##__VA_ARGS__) +static inline OHOS::HiviewDFX::HiLogLabel LogLabel() +{ + return { LOG_CORE, 0xD001651, "DataShare" }; +} } // namespace OHOS::DataShare -#endif + +#define FILENAME (__builtin_strrchr(__FILE__, '/') ? __builtin_strrchr(__FILE__, '/') + 1 : __FILE__) + +#define LOG_DEBUG(fmt, ...) \ + do { \ + using HiLog = OHOS::HiviewDFX::HiLog; \ + auto lable = LogLabel(); \ + if (HiLogIsLoggable(lable.domain, lable.tag, LogLevel::LOG_DEBUG)) { \ + HiLog::Debug(lable, "[%{public}s()-%{public}s:%{public}d]: " fmt, __FUNCTION__, FILENAME, __LINE__, \ + ##__VA_ARGS__); \ + } \ + } while (0) + +#define LOG_INFO(fmt, ...) \ + do { \ + using HiLog = OHOS::HiviewDFX::HiLog; \ + auto lable = LogLabel(); \ + if (HiLogIsLoggable(lable.domain, lable.tag, LogLevel::LOG_INFO)) { \ + HiLog::Info(lable, "[%{public}s()-%{public}s:%{public}d]: " fmt, __FUNCTION__, FILENAME, __LINE__, \ + ##__VA_ARGS__); \ + } \ + } while (0) + +#define LOG_WARN(fmt, ...) \ + do { \ + using HiLog = OHOS::HiviewDFX::HiLog; \ + auto lable = LogLabel(); \ + if (HiLogIsLoggable(lable.domain, lable.tag, LogLevel::LOG_WARN)) { \ + HiLog::Warn(lable, "[%{public}s()-%{public}s:%{public}d]: " fmt, __FUNCTION__, FILENAME, __LINE__, \ + ##__VA_ARGS__); \ + } \ + } while (0) + +#define LOG_ERROR(fmt, ...) \ + do { \ + using HiLog = OHOS::HiviewDFX::HiLog; \ + auto lable = LogLabel(); \ + if (HiLogIsLoggable(lable.domain, lable.tag, LogLevel::LOG_ERROR)) { \ + HiLog::Error(lable, "[%{public}s()-%{public}s:%{public}d]: " fmt, __FUNCTION__, FILENAME, __LINE__, \ + ##__VA_ARGS__); \ + } \ + } while (0) + +#define LOG_FATAL(fmt, ...) \ + do { \ + using HiLog = OHOS::HiviewDFX::HiLog; \ + auto lable = LogLabel(); \ + if (HiLogIsLoggable(lable.domain, lable.tag, LogLevel::LOG_FATAL)) { \ + HiLog::Fatal(lable, "[%{public}s()-%{public}s:%{public}d]: " fmt, __FUNCTION__, FILENAME, __LINE__, \ + ##__VA_ARGS__); \ + } \ + } while (0) + +#endif // DATASHARE_LOG_PRINT_H diff --git a/data_share/frameworks/native/proxy/include/idata_share_service.h b/data_share/frameworks/native/common/include/idata_share_service.h similarity index 40% rename from data_share/frameworks/native/proxy/include/idata_share_service.h rename to data_share/frameworks/native/common/include/idata_share_service.h index 568dd1a1..06f84e6a 100644 --- a/data_share/frameworks/native/proxy/include/idata_share_service.h +++ b/data_share/frameworks/native/common/include/idata_share_service.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 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,14 +13,21 @@ * limitations under the License. */ -#ifndef DISTRIBUTEDDATAFWK_IDATA_SHARE_SERVICE_H -#define DISTRIBUTEDDATAFWK_IDATA_SHARE_SERVICE_H +#ifndef IDATA_SHARE_SERVICE_H +#define IDATA_SHARE_SERVICE_H #include -#include "base_proxy.h" #include "iremote_broker.h" +#include "data_proxy_observer.h" +#include "datashare_business_error.h" +#include "datashare_predicates.h" +#include "datashare_result_set.h" +#include "datashare_template.h" +#include "datashare_values_bucket.h" +#include "uri.h" + namespace OHOS::DataShare { class IDataShareService : public IRemoteBroker { public: @@ -42,7 +49,7 @@ public: DATA_SHARE_SERVICE_CMD_UNSUBSCRIBE_PUBLISHED, DATA_SHARE_SERVICE_CMD_ENABLE_SUBSCRIBE_PUBLISHED, DATA_SHARE_SERVICE_CMD_DISABLE_SUBSCRIBE_PUBLISHED, - DATA_SHARE_SERVICE_CMD_QUERY_ASSERT, + DATA_SHARE_SERVICE_CMD_NOTIFY, DATA_SHARE_SERVICE_CMD_MAX }; @@ -50,21 +57,47 @@ public: DATA_SHARE_ERROR = -1, DATA_SHARE_OK = 0, }; -}; -class IKvStoreDataService : public IRemoteBroker { -public: - enum { GET_FEATURE_INTERFACE = 0 }; + virtual int Insert(const Uri &uri, const DataShareValuesBucket &value) = 0; - enum { - DATA_SHARE_ERROR = -1, - DATA_SHARE_OK = 0, - }; + virtual int Update(const Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value) = 0; - virtual sptr GetFeatureInterface(const std::string &name) = 0; + virtual int Delete(const Uri &uri, const DataSharePredicates &predicates) = 0; - DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreDataService"); -}; + virtual std::shared_ptr Query(const Uri &uri, const DataSharePredicates &predicates, + std::vector &columns, DatashareBusinessError &businessError) = 0; + + virtual int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) = 0; + + virtual int DelQueryTemplate(const std::string &uri, int64_t subscriberId) = 0; + virtual std::vector Publish(const Data &data, const std::string &bundleName) = 0; + + virtual Data GetPublishedData(const std::string &bundleName, int &resultCode) = 0; + + virtual std::vector SubscribeRdbData(const std::vector &uris, + const TemplateId &templateId, const sptr &observer) = 0; + + virtual std::vector UnSubscribeRdbData(const std::vector &uris, + const TemplateId &templateId) = 0; + + virtual std::vector EnableSubscribeRdbData(const std::vector &uris, + const TemplateId &templateId) = 0; + + virtual std::vector DisableSubscribeRdbData(const std::vector &uris, + const TemplateId &templateId) = 0; + + virtual std::vector SubscribePublishedData(const std::vector &uris, + int64_t subscriberId, const sptr &observer) = 0; + + virtual std::vector UnSubscribePublishedData(const std::vector &uris, + int64_t subscriberId) = 0; + + virtual std::vector EnableSubscribePublishedData(const std::vector &uris, + int64_t subscriberId) = 0; + + virtual std::vector DisableSubscribePublishedData(const std::vector &uris, + int64_t subscriberId) = 0; +}; } // namespace OHOS::DataShare #endif diff --git a/data_share/frameworks/native/common/include/idatashare.h b/data_share/frameworks/native/common/include/idatashare.h index a1124a33..0e28597a 100644 --- a/data_share/frameworks/native/common/include/idatashare.h +++ b/data_share/frameworks/native/common/include/idatashare.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 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,18 @@ #ifndef I_DATASHARE_H #define I_DATASHARE_H -#include -#include #include +#include "datashare_business_error.h" +#include "datashare_predicates.h" +#include "datashare_result_set.h" +#include "datashare_values_bucket.h" #include "uri.h" -#include "base_proxy.h" namespace OHOS { +namespace AAFwk { +class IDataAbilityObserver; +} namespace DataShare { class IDataShare : public IRemoteBroker { @@ -47,6 +51,35 @@ public: CMD_DENORMALIZE_URI, CMD_EXECUTE_BATCH, }; + + virtual int OpenFile(const Uri &uri, const std::string &mode) = 0; + + virtual int OpenRawFile(const Uri &uri, const std::string &mode) = 0; + + virtual int Insert(const Uri &uri, const DataShareValuesBucket &value) = 0; + + virtual int Update(const Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value) = 0; + + virtual int Delete(const Uri &uri, const DataSharePredicates &predicates) = 0; + + virtual std::shared_ptr Query(const Uri &uri, const DataSharePredicates &predicates, + std::vector &columns, DatashareBusinessError &businessError) = 0; + + virtual std::string GetType(const Uri &uri) = 0; + + virtual int BatchInsert(const Uri &uri, const std::vector &values) = 0; + + virtual bool RegisterObserver(const Uri &uri, const sptr &dataObserver) = 0; + + virtual bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) = 0; + + virtual bool NotifyChange(const Uri &uri) = 0; + + virtual Uri NormalizeUri(const Uri &uri) = 0; + + virtual Uri DenormalizeUri(const Uri &uri) = 0; + + virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) = 0; }; } // namespace DataShare } // namespace OHOS diff --git a/data_share/frameworks/native/common/include/ikvstore_data_service.h b/data_share/frameworks/native/common/include/ikvstore_data_service.h new file mode 100644 index 00000000..55b33a92 --- /dev/null +++ b/data_share/frameworks/native/common/include/ikvstore_data_service.h @@ -0,0 +1,49 @@ +/* + * 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 IKVSTORE_DATA_SERVICE_H +#define IKVSTORE_DATA_SERVICE_H + +#include "iremote_broker.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace DataShare { +class IKvStoreDataService : public IRemoteBroker { +public: + enum { + GET_FEATURE_INTERFACE = 0 + }; + + enum { + DATA_SHARE_ERROR = -1, + DATA_SHARE_OK = 0, + }; + + virtual sptr GetFeatureInterface(const std::string &name) = 0; + + DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.DistributedKv.IKvStoreDataService"); +}; + +class DataShareKvServiceProxy : public IRemoteProxy { +public: + explicit DataShareKvServiceProxy(const sptr &impl); + ~DataShareKvServiceProxy() = default; + sptr GetFeatureInterface(const std::string &name) override; +}; +} +} +#endif // IKVSTORE_DATA_SERVICE_H diff --git a/data_share/frameworks/native/common/include/itypes_utils.h b/data_share/frameworks/native/common/include/itypes_utils.h deleted file mode 100644 index af964dab..00000000 --- a/data_share/frameworks/native/common/include/itypes_utils.h +++ /dev/null @@ -1,292 +0,0 @@ -/* - * 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 DATASHARE_COMMON_ITYPES_UTIL_H -#define DATASHARE_COMMON_ITYPES_UTIL_H - -#include "datashare_predicates.h" -#include "datashare_values_bucket.h" -#include "parcel.h" - -namespace OHOS::DataShare { -class ITypesUtils final { -public: - static bool Marshal(Parcel &data); - static bool Unmarshal(Parcel &data); - - static bool Marshalling(bool input, Parcel &data); - static bool Unmarshalling(Parcel &data, bool &output); - - static bool Marshalling(const char *input, Parcel &data); - static bool Marshalling(const std::string &input, Parcel &data); - static bool Unmarshalling(Parcel &data, std::string &output); - - static bool Marshalling(int16_t input, Parcel &data); - static bool Unmarshalling(Parcel &data, int16_t &output); - - static bool Marshalling(int32_t input, Parcel &data); - static bool Unmarshalling(Parcel &data, int32_t &output); - - static bool Marshalling(int64_t input, Parcel &data); - static bool Unmarshalling(Parcel &data, int64_t &output); - - static bool Marshalling(double input, Parcel &data); - static bool Unmarshalling(Parcel &data, double &output); - - static bool Marshalling(const std::monostate &input, Parcel &data); - static bool Unmarshalling(Parcel &data, std::monostate &output); - - static bool Marshalling(const std::vector &input, Parcel &data); - static bool Unmarshalling(Parcel &data, std::vector &output); - - static bool Marshalling(const DataSharePredicates &predicates, Parcel &parcel); - static bool Unmarshalling(Parcel &parcel, DataSharePredicates &predicates); - - static bool Marshalling(const DataShareValuesBucket &valuesBucket, Parcel &parcel); - static bool Unmarshalling(Parcel &parcel, DataShareValuesBucket &valuesBucket); - - static bool Marshalling(const OperationItem &operationItem, Parcel &parcel); - static bool Unmarshalling(Parcel &parcel, OperationItem &operationItem); - - static bool Marshalling(const SingleValue &predicatesObject, Parcel &parcel); - static bool Unmarshalling(Parcel &parcel, SingleValue &predicatesObject); - - static bool Marshalling(const MutliValue &predicatesObject, Parcel &parcel); - static bool Unmarshalling(Parcel &parcel, MutliValue &predicatesObject); - - static bool Marshalling(const DataShareValueObject &valueObject, Parcel &parcel); - static bool Unmarshalling(Parcel &parcel, DataShareValueObject &valueObject); - - template - static bool Marshalling(const std::vector ¶ms, Parcel &parcel); - template - static bool Unmarshalling(Parcel &parcel, std::vector ¶ms); - - template - static bool Marshalling(const std::list ¶ms, Parcel &parcel); - template - static bool Unmarshalling(Parcel &parcel, std::list ¶ms); - - template - static bool Marshalling(const std::map &val, Parcel &parcel); - template - static bool Unmarshalling(Parcel &parcel, std::map &val); - - template - static bool Marshalling(const std::variant<_Types...> &input, Parcel &data); - - template - static bool Unmarshalling(Parcel &data, std::variant<_Types...> &output); - - template - static bool Marshal(Parcel &parcel, const T &first, const Types &...others); - template - static bool Unmarshal(Parcel &parcel, T &first, Types &...others); - -private: - template - static bool Marshalling(T *input, Parcel &data) = delete; - template - static bool Unmarshalling(T *&output, Parcel &data) = delete; - template - static bool ReadVariant(uint32_t step, uint32_t index, const _OutTp &output, Parcel &data) - { - return false; - } - - template - static bool ReadVariant(uint32_t step, uint32_t index, const _OutTp &output, Parcel &data) - { - if (step == index) { - _First value{}; - auto success = ITypesUtils::Unmarshalling(data, value); - output = value; - return success; - } - return ReadVariant<_OutTp, _Rest...>(step + 1, index, output, data); - } - - template - static bool WriteVariant(uint32_t step, const _InTp &input, Parcel &data) - { - return false; - } - - template - static bool WriteVariant(uint32_t step, const _InTp &input, Parcel &data) - { - if (step == input.index()) { - return ITypesUtils::Marshalling(std::get<_First>(input), data); - } - return WriteVariant<_InTp, _Rest...>(step + 1, input, data); - } -}; - -template -bool ITypesUtils::Marshal(Parcel &parcel, const T &first, const Types &...others) -{ - if (!Marshalling(first, parcel)) { - return false; - } - return Marshal(parcel, others...); -} - -template -bool ITypesUtils::Unmarshal(Parcel &parcel, T &first, Types &...others) -{ - if (!Unmarshalling(parcel, first)) { - return false; - } - return Unmarshal(parcel, others...); -} - -template -bool ITypesUtils::Marshalling(const std::vector ¶ms, Parcel &parcel) -{ - if (!parcel.WriteInt32(params.size())) { - return false; - } - for (unsigned long i = 0; i < params.size(); i++) { - if (!Marshalling(params[i], parcel)) { - return false; - } - } - return true; -} - -template -bool ITypesUtils::Unmarshalling(Parcel &parcel, std::vector ¶ms) -{ - size_t size = static_cast(parcel.ReadInt32()); - if (static_cast(size) < 0) { - return false; - } - if ((size > parcel.GetReadableBytes()) || (params.max_size() < size)) { - return false; - } - params.resize(static_cast(size)); - for (size_t i = 0; i < size; i++) { - T param; - if (!Unmarshalling(parcel, param)) { - return false; - } - params[static_cast(i)] = param; - } - return true; -} - -template -bool ITypesUtils::Marshalling(const std::list ¶ms, Parcel &parcel) -{ - if (!parcel.WriteInt32(params.size())) { - return false; - } - for (auto &item : params) { - if (!Marshalling(item, parcel)) { - return false; - } - } - return true; -} - -template -bool ITypesUtils::Unmarshalling(Parcel &parcel, std::list ¶ms) -{ - size_t size = static_cast(parcel.ReadInt32()); - if (static_cast(size) < 0) { - return false; - } - if ((size > parcel.GetReadableBytes()) || (params.max_size() < size)) { - return false; - } - for (size_t i = 0; i < size; i++) { - T param; - if (!Unmarshalling(parcel, param)) { - return false; - } - params.push_back(std::move(param)); - } - return true; -} -template -bool ITypesUtils::Marshalling(const std::map &result, Parcel &parcel) -{ - if (!parcel.WriteInt32(static_cast(result.size()))) { - return false; - } - for (const auto &entry : result) { - if (!Marshalling(entry.first, parcel)) { - return false; - } - if (!Marshalling(entry.second, parcel)) { - return false; - } - } - return true; -} - -template -bool ITypesUtils::Unmarshalling(Parcel &parcel, std::map &val) -{ - int32_t size = 0; - if (!parcel.ReadInt32(size)) { - return false; - } - if (size < 0) { - return false; - } - - size_t readAbleSize = parcel.GetReadableBytes(); - size_t len = static_cast(size); - if ((len > readAbleSize) || len > val.max_size()) { - return false; - } - - for (int32_t i = 0; i < size; i++) { - K key; - if (!Unmarshalling(parcel, key)) { - return false; - } - V value; - if (!Unmarshalling(parcel, value)) { - return false; - } - val.insert({ std::move(key), std::move(value) }); - } - return true; -} -template -bool ITypesUtils::Marshalling(const std::variant<_Types...> &input, Parcel &data) -{ - uint32_t index = static_cast(input.index()); - if (!data.WriteUint32(index)) { - return false; - } - - return WriteVariant(0, input, data); -} - -template -bool ITypesUtils::Unmarshalling(Parcel &data, std::variant<_Types...> &output) -{ - uint32_t index = data.ReadUint32(); - if (index >= sizeof...(_Types)) { - return false; - } - - return ReadVariant(0, index, output, data); -} -} // namespace OHOS::DataShare -#endif diff --git a/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp b/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp index e2795c93..59482ef6 100644 --- a/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp +++ b/data_share/frameworks/native/common/src/datashare_abs_result_set.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#define LOG_TAG "DataShareAbsResultSet" + #include "datashare_abs_result_set.h" #include diff --git a/data_share/frameworks/native/common/src/datashare_template.cpp b/data_share/frameworks/native/common/src/datashare_template.cpp new file mode 100644 index 00000000..285cc60e --- /dev/null +++ b/data_share/frameworks/native/common/src/datashare_template.cpp @@ -0,0 +1,137 @@ +/* + * 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. + */ + +#include "datashare_template.h" + +namespace OHOS { +namespace DataShare { +PublishedDataItem::~PublishedDataItem() +{ + Clear(); +} + +PublishedDataItem::PublishedDataItem(const std::string &key, int64_t subscriberId, DataType value) + : key_(key), subscriberId_(subscriberId) +{ + Set(value); +} + +PublishedDataItem::PublishedDataItem(PublishedDataItem &&item) +{ + key_ = std::move(item.key_); + subscriberId_ = std::move(item.subscriberId_); + value_ = std::move(item.value_); + if (item.IsAshmem()) { + item.MoveOutAshmem(); + } +} + +PublishedDataItem &PublishedDataItem::operator=(PublishedDataItem &&item) +{ + key_ = std::move(item.key_); + subscriberId_ = std::move(item.subscriberId_); + value_ = std::move(item.value_); + if (item.IsAshmem()) { + item.MoveOutAshmem(); + } + return *this; +} + +sptr PublishedDataItem::MoveOutAshmem() +{ + if (IsAshmem()) { + AshmemNode &node = std::get(value_); + if (!node.isManaged) { + return nullptr; + } + node.isManaged = false; + return std::move(node.ashmem); + } + return nullptr; +} + +bool PublishedDataItem::IsAshmem() const +{ + return value_.index() == 0; +} + +bool PublishedDataItem::IsString() const +{ + return value_.index() == 1; +} + +void PublishedDataItem::Set(DataType &value) +{ + Clear(); + if (value.index() == 0) { + std::vector &vecValue = std::get>(value); + auto size = vecValue.size(); + sptr mem = Ashmem::CreateAshmem((key_ + std::to_string(subscriberId_)).c_str(), size); + if (mem == nullptr) { + return; + } + if (!mem->MapReadAndWriteAshmem()) { + mem->CloseAshmem(); + return; + } + if (!mem->WriteToAshmem(vecValue.data(), size, 0)) { + mem->UnmapAshmem(); + mem->CloseAshmem(); + return; + } + AshmemNode node = { mem, true }; + value_ = std::move(node); + } else { + value_ = std::move(std::get(value)); + } +} + +PublishedDataItem::DataType PublishedDataItem::GetData() const +{ + if (IsAshmem()) { + const AshmemNode &node = std::get(value_); + if (node.ashmem != nullptr) { + node.ashmem->MapReadOnlyAshmem(); + uint8_t *data = (uint8_t *)node.ashmem->ReadFromAshmem(node.ashmem->GetAshmemSize(), 0); + if (data == nullptr) { + return std::vector(); + } + return std::vector(data, data + node.ashmem->GetAshmemSize()); + } + return std::vector(); + } else { + return std::get(value_); + } +} + +void PublishedDataItem::SetAshmem(sptr ashmem, bool isManaged) +{ + AshmemNode node = { ashmem, isManaged }; + value_ = std::move(node); +} + +void PublishedDataItem::Clear() +{ + AshmemNode *node = std::get_if(&value_); + if (node != nullptr) { + if (node->isManaged && node->ashmem != nullptr) { + node->ashmem->UnmapAshmem(); + node->ashmem->CloseAshmem(); + } + value_ = ""; + } +} +} // namespace DataShare +} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/common/src/ikvstore_data_service.cpp b/data_share/frameworks/native/common/src/ikvstore_data_service.cpp new file mode 100644 index 00000000..341a1f22 --- /dev/null +++ b/data_share/frameworks/native/common/src/ikvstore_data_service.cpp @@ -0,0 +1,55 @@ +/* + * 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 "ikvstore_data_service.h" +#include "datashare_log.h" + +namespace OHOS { +namespace DataShare { +DataShareKvServiceProxy::DataShareKvServiceProxy(const sptr &impl) + : IRemoteProxy(impl) +{ + LOG_DEBUG("Init data service proxy."); +} + +sptr DataShareKvServiceProxy::GetFeatureInterface(const std::string &name) +{ + LOG_INFO("GetDataShareService enter."); + MessageParcel data; + if (!data.WriteInterfaceToken(DataShareKvServiceProxy::GetDescriptor())) { + LOG_ERROR("Write descriptor failed"); + return nullptr; + } + if (!data.WriteString(name)) { + LOG_ERROR("Write name failed"); + return nullptr; + } + + MessageParcel reply; + MessageOption mo { MessageOption::TF_SYNC }; + int32_t error = Remote()->SendRequest(GET_FEATURE_INTERFACE, data, reply, mo); + if (error != 0) { + LOG_ERROR("SendRequest returned %{public}d", error); + return nullptr; + } + auto remoteObject = reply.ReadRemoteObject(); + if (remoteObject == nullptr) { + LOG_ERROR("Remote object is nullptr!"); + return nullptr; + } + return remoteObject; +} +} +} diff --git a/data_share/frameworks/native/common/src/itypes_utils.cpp b/data_share/frameworks/native/common/src/itypes_utils.cpp deleted file mode 100644 index 67beab1c..00000000 --- a/data_share/frameworks/native/common/src/itypes_utils.cpp +++ /dev/null @@ -1,172 +0,0 @@ -/* - * 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. - */ - -#include "itypes_utils.h" - -#include "datashare_log.h" -namespace OHOS::DataShare { -bool ITypesUtils::Marshal(Parcel &data) -{ - return true; -} - -bool ITypesUtils::Unmarshal(Parcel &data) -{ - return true; -} - -bool ITypesUtils::Marshalling(bool input, Parcel &data) -{ - return data.WriteBool(input); -} - -bool ITypesUtils::Unmarshalling(Parcel &data, bool &output) -{ - return data.ReadBool(output); -} - -bool ITypesUtils::Marshalling(const char *input, Parcel &data) -{ - return data.WriteString(input); -} - -bool ITypesUtils::Marshalling(const std::string &input, Parcel &data) -{ - return data.WriteString(input); -} - -bool ITypesUtils::Unmarshalling(Parcel &data, std::string &output) -{ - return data.ReadString(output); -} - -bool ITypesUtils::Marshalling(int16_t input, Parcel &data) -{ - return data.WriteInt16(input); -} - -bool ITypesUtils::Unmarshalling(Parcel &data, int16_t &output) -{ - return data.ReadInt16(output); -} - -bool ITypesUtils::Marshalling(int32_t input, Parcel &data) -{ - return data.WriteInt32(input); -} - -bool ITypesUtils::Unmarshalling(Parcel &data, int32_t &output) -{ - return data.ReadInt32(output); -} - -bool ITypesUtils::Marshalling(int64_t input, Parcel &data) -{ - return data.WriteInt64(input); -} -bool ITypesUtils::Unmarshalling(Parcel &data, int64_t &output) -{ - return data.ReadInt64(output); -} - -bool ITypesUtils::Marshalling(double input, Parcel &data) -{ - return data.WriteDouble(input); -} - -bool ITypesUtils::Unmarshalling(Parcel &data, double &output) -{ - return data.ReadDouble(output); -} - -bool ITypesUtils::Marshalling(const std::monostate &input, Parcel &data) -{ - return true; -} - -bool ITypesUtils::Unmarshalling(Parcel &data, std::monostate &output) -{ - return true; -} - -bool ITypesUtils::Marshalling(const std::vector &input, Parcel &data) -{ - return data.WriteUInt8Vector(input); -} - -bool ITypesUtils::Unmarshalling(Parcel &data, std::vector &output) -{ - return data.ReadUInt8Vector(&output); -} - -bool ITypesUtils::Marshalling(const DataSharePredicates &predicates, Parcel &parcel) -{ - const auto &operations = predicates.GetOperationList(); - int16_t mode = predicates.GetSettingMode(); - return ITypesUtils::Marshal(parcel, operations, predicates.GetWhereClause(), predicates.GetWhereArgs(), - predicates.GetOrder(), mode); -} - -bool ITypesUtils::Unmarshalling(Parcel &parcel, DataSharePredicates &predicates) -{ - std::vector operations{}; - std::string whereClause = ""; - std::vector whereArgs; - std::string order = ""; - int16_t mode = INVALID_MODE; - if (!ITypesUtils::Unmarshal(parcel, operations, whereClause, whereArgs, order, mode)) { - LOG_ERROR("read predicate failed"); - return false; - } - DataSharePredicates tmpPredicates(std::move(operations)); - tmpPredicates.SetWhereClause(whereClause); - tmpPredicates.SetWhereArgs(whereArgs); - tmpPredicates.SetOrder(order); - tmpPredicates.SetSettingMode(mode); - predicates = tmpPredicates; - return true; -} - -bool ITypesUtils::Marshalling(const DataShareValuesBucket &valuesBucket, Parcel &parcel) -{ - return ITypesUtils::Marshal(parcel, valuesBucket.valuesMap); -} - -bool ITypesUtils::Unmarshalling(Parcel &parcel, DataShareValuesBucket &valuesBucket) -{ - return ITypesUtils::Unmarshal(parcel, valuesBucket.valuesMap); -} - -bool ITypesUtils::Marshalling(const OperationItem &operationItem, Parcel &parcel) -{ - return ITypesUtils::Marshal(parcel, operationItem.operation, operationItem.singleParams, operationItem.multiParams); -} - -bool ITypesUtils::Unmarshalling(Parcel &parcel, OperationItem &operationItem) -{ - return ITypesUtils::Unmarshal(parcel, operationItem.operation, operationItem.singleParams, - operationItem.multiParams); -} - -bool ITypesUtils::Marshalling(const DataShareValueObject &valueObject, Parcel &parcel) -{ - return ITypesUtils::Marshal(parcel, valueObject.value); -} - -bool ITypesUtils::Unmarshalling(Parcel &parcel, DataShareValueObject &valueObject) -{ - return ITypesUtils::Unmarshal(parcel, valueObject.value); -} -} // namespace OHOS::DataShare diff --git a/datamgr_service/services/distributeddataservice/adapter/include/autils/kv_store_thread_pool.h b/data_share/frameworks/native/consumer/controller/common/general_controller.h similarity index 34% rename from datamgr_service/services/distributeddataservice/adapter/include/autils/kv_store_thread_pool.h rename to data_share/frameworks/native/consumer/controller/common/general_controller.h index 6b908a68..10a8d4ee 100644 --- a/datamgr_service/services/distributeddataservice/adapter/include/autils/kv_store_thread_pool.h +++ b/data_share/frameworks/native/consumer/controller/common/general_controller.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 @@ -13,34 +13,40 @@ * limitations under the License. */ -#ifndef KV_STORE_THREAD_POOL_H -#define KV_STORE_THREAD_POOL_H - #include -#include "kv_store_task.h" +#include + +#include "datashare_business_error.h" +#include "datashare_predicates.h" +#include "datashare_result_set.h" +#include "datashare_values_bucket.h" +#include "uri.h" +#ifndef GENERAL_CONTROLLER_H +#define GENERAL_CONTROLLER_H namespace OHOS { -namespace DistributedKv { -class KvStoreThreadPool { +namespace AAFwk { +class IDataAbilityObserver; +} + +namespace DataShare { +class GeneralController { public: - KvStoreThreadPool(KvStoreThreadPool &&) = delete; - KvStoreThreadPool(const KvStoreThreadPool &) = delete; - KvStoreThreadPool &operator=(KvStoreThreadPool &&) = delete; - KvStoreThreadPool &operator=(const KvStoreThreadPool &) = delete; - KVSTORE_API virtual ~KvStoreThreadPool() {} - - KVSTORE_API static std::shared_ptr GetPool( - int poolSize, std::string poolName, bool startImmediately = false); - KVSTORE_API virtual void Stop() = 0; - KVSTORE_API virtual bool AddTask(KvStoreTask &&task) = 0; - KVSTORE_API static constexpr int MAX_POOL_SIZE = 64; // the max thread pool size - KVSTORE_API static constexpr int DEFAULT_POOL_SIZE = 8; // the default thread pool size - std::string GetPoolName(); -protected: - KvStoreThreadPool() = default; - std::string poolName_ = ""; + virtual ~GeneralController() = default; + + virtual int Insert(const Uri &uri, const DataShareValuesBucket &value) = 0; + + virtual int Update(const Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value) = 0; + + virtual int Delete(const Uri &uri, const DataSharePredicates &predicates) = 0; + + virtual std::shared_ptr Query(const Uri &uri, const DataSharePredicates &predicates, + std::vector &columns, DatashareBusinessError &businessError) = 0; + + virtual void RegisterObserver(const Uri &uri, const sptr &dataObserver) = 0; + + virtual void UnregisterObserver(const Uri &uri, const sptr &dataObserver) = 0; }; -} // namespace DistributedKv +} // namespace DataShare } // namespace OHOS - -#endif // KV_STORE_THREAD_POOL_H +#endif // GENERAL_CONTROLLER_H diff --git a/data_share/frameworks/native/consumer/controller/provider/include/ext_special_controller.h b/data_share/frameworks/native/consumer/controller/provider/include/ext_special_controller.h new file mode 100644 index 00000000..32a5ba99 --- /dev/null +++ b/data_share/frameworks/native/consumer/controller/provider/include/ext_special_controller.h @@ -0,0 +1,55 @@ +/* + * 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 EXT_SPECIAL_CONTROLLER_H +#define EXT_SPECIAL_CONTROLLER_H + +#include "datashare_connection.h" +#include "datashare_values_bucket.h" +#include "uri.h" + +namespace OHOS { +namespace DataShare { +class ExtSpecialController { +public: + ExtSpecialController(std::shared_ptr connection, const Uri &uri, + const sptr &token); + virtual ~ExtSpecialController() = default; + + int OpenFile(const Uri &uri, const std::string &mode); + + int OpenRawFile(const Uri &uri, const std::string &mode); + + std::string GetType(const Uri &uri); + + int BatchInsert(const Uri &uri, const std::vector &values); + + Uri NormalizeUri(const Uri &uri); + + Uri DenormalizeUri(const Uri &uri); + + std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter); + + void NotifyChange(const Uri &uri); + +private: + std::shared_ptr connection_ = nullptr; + sptr token_ = {}; + Uri uri_ = Uri(""); +}; +} +} + +#endif // EXT_SPECIAL_CONTROLLER_H diff --git a/data_share/frameworks/native/consumer/controller/provider/include/general_controller_porvider_impl.h b/data_share/frameworks/native/consumer/controller/provider/include/general_controller_porvider_impl.h new file mode 100644 index 00000000..37c12b0f --- /dev/null +++ b/data_share/frameworks/native/consumer/controller/provider/include/general_controller_porvider_impl.h @@ -0,0 +1,55 @@ +/* + * 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 GENERAL_CONTROLLER_PORVIDER_IMPL_H +#define GENERAL_CONTROLLER_PORVIDER_IMPL_H + +#include "datashare_connection.h" +#include "general_controller.h" + +namespace OHOS { +namespace AAFwk { +class IDataAbilityObserver; +} + +namespace DataShare { +class GeneralControllerProviderImpl : public GeneralController { +public: + GeneralControllerProviderImpl(std::shared_ptr connection, + const Uri &uri, const sptr &token); + + virtual ~GeneralControllerProviderImpl() = default; + + int Insert(const Uri &uri, const DataShareValuesBucket &value) override; + + int Update(const Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value) override; + + int Delete(const Uri &uri, const DataSharePredicates &predicates) override; + + std::shared_ptr Query(const Uri &uri, const DataSharePredicates &predicates, + std::vector &columns, DatashareBusinessError &businessError) override; + + void RegisterObserver(const Uri &uri, const sptr &dataObserver) override; + + void UnregisterObserver(const Uri &uri, const sptr &dataObserver) override; + +private: + std::shared_ptr connection_ = nullptr; + sptr token_ = {}; + Uri uri_ = Uri(""); +}; +} // namespace DataShare +} // namespace OHOS +#endif // GENERAL_CONTROLLER_PORVIDER_IMPL_H diff --git a/data_share/frameworks/native/consumer/controller/provider/src/ext_special_controller.cpp b/data_share/frameworks/native/consumer/controller/provider/src/ext_special_controller.cpp new file mode 100644 index 00000000..b931115b --- /dev/null +++ b/data_share/frameworks/native/consumer/controller/provider/src/ext_special_controller.cpp @@ -0,0 +1,148 @@ +/* + * 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 "ext_special_controller.h" +#include "datashare_log.h" + +namespace OHOS { +namespace DataShare { +constexpr int INVALID_VALUE = -1; +int ExtSpecialController::OpenFile(const Uri &uri, const std::string &mode) +{ + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("connection is nullptr"); + return INVALID_VALUE; + } + auto proxy = connection->GetDataShareProxy(uri_, token_); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return INVALID_VALUE; + } + return proxy->OpenFile(uri, mode); +} + +int ExtSpecialController::OpenRawFile(const Uri &uri, const std::string &mode) +{ + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("connection is nullptr"); + return INVALID_VALUE; + } + auto proxy = connection->GetDataShareProxy(uri_, token_); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return INVALID_VALUE; + } + return proxy->OpenRawFile(uri, mode); +} + +std::string ExtSpecialController::GetType(const Uri &uri) +{ + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("connection is nullptr"); + return ""; + } + auto proxy = connection->GetDataShareProxy(uri_, token_); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return ""; + } + return proxy->GetType(uri); +} + +int ExtSpecialController::BatchInsert(const Uri &uri, const std::vector &values) +{ + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("connection is nullptr"); + return INVALID_VALUE; + } + auto proxy = connection->GetDataShareProxy(uri_, token_); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return INVALID_VALUE; + } + return proxy->BatchInsert(uri, values); +} + +Uri ExtSpecialController::NormalizeUri(const Uri &uri) +{ + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("connection is nullptr"); + return Uri(""); + } + auto proxy = connection->GetDataShareProxy(uri_, token_); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return Uri(""); + } + return proxy->NormalizeUri(uri); +} + +Uri ExtSpecialController::DenormalizeUri(const Uri &uri) +{ + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("connection is nullptr"); + return Uri(""); + } + auto proxy = connection->GetDataShareProxy(uri_, token_); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return Uri(""); + } + return proxy->DenormalizeUri(uri); +} + +std::vector ExtSpecialController::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) +{ + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("connection is nullptr"); + return std::vector(); + } + auto proxy = connection->GetDataShareProxy(uri_, token_); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + return proxy->GetFileTypes(uri, mimeTypeFilter); +} + +void ExtSpecialController::NotifyChange(const Uri &uri) +{ + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("connection is nullptr"); + return; + } + auto proxy = connection->GetDataShareProxy(uri_, token_); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return; + } + proxy->NotifyChange(uri); +} + +ExtSpecialController::ExtSpecialController(std::shared_ptr connection, const Uri &uri, + const sptr &token) + : connection_(connection), token_(token), uri_(uri) +{ +} +} // namespace DataShare +} // namespace OHOS diff --git a/data_share/frameworks/native/consumer/controller/provider/src/general_controller_provider_impl.cpp b/data_share/frameworks/native/consumer/controller/provider/src/general_controller_provider_impl.cpp new file mode 100644 index 00000000..ea310623 --- /dev/null +++ b/data_share/frameworks/native/consumer/controller/provider/src/general_controller_provider_impl.cpp @@ -0,0 +1,122 @@ +/* + * 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 "general_controller_porvider_impl.h" + +#include "datashare_log.h" + +namespace OHOS { +namespace DataShare { +constexpr int INVALID_VALUE = -1; +int GeneralControllerProviderImpl::Insert(const Uri &uri, const DataShareValuesBucket &value) +{ + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("connection is nullptr"); + return INVALID_VALUE; + } + auto proxy = connection->GetDataShareProxy(uri_, token_); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return INVALID_VALUE; + } + return proxy->Insert(uri, value); +} + +int GeneralControllerProviderImpl::Update(const Uri &uri, const DataSharePredicates &predicates, + const DataShareValuesBucket &value) +{ + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("connection is nullptr"); + return INVALID_VALUE; + } + auto proxy = connection->GetDataShareProxy(uri_, token_); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return INVALID_VALUE; + } + return proxy->Update(uri, predicates, value); +} + +int GeneralControllerProviderImpl::Delete(const Uri &uri, const DataSharePredicates &predicates) +{ + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("connection is nullptr"); + return INVALID_VALUE; + } + auto proxy = connection->GetDataShareProxy(uri_, token_); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return INVALID_VALUE; + } + return proxy->Delete(uri, predicates); +} + +std::shared_ptr GeneralControllerProviderImpl::Query(const Uri &uri, + const DataSharePredicates &predicates, std::vector &columns, DatashareBusinessError &businessError) +{ + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("connection is nullptr"); + return nullptr; + } + auto proxy = connection->GetDataShareProxy(uri_, token_); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return nullptr; + } + return proxy->Query(uri, predicates, columns, businessError); +} + +void GeneralControllerProviderImpl::RegisterObserver(const Uri &uri, + const sptr &dataObserver) +{ + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("connection is nullptr"); + return; + } + auto proxy = connection->GetDataShareProxy(uri_, token_); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return; + } + proxy->RegisterObserver(uri, dataObserver); +} + +void GeneralControllerProviderImpl::UnregisterObserver(const Uri &uri, + const sptr &dataObserver) +{ + auto connection = connection_; + if (connection == nullptr) { + LOG_ERROR("connection is nullptr"); + return; + } + auto proxy = connection->GetDataShareProxy(uri_, token_); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return; + } + proxy->UnregisterObserver(uri, dataObserver); +} + +GeneralControllerProviderImpl::GeneralControllerProviderImpl(std::shared_ptr connection, + const Uri &uri, const sptr &token) : connection_(connection), token_(token), uri_(uri) +{ +} +} // namespace DataShare +} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/consumer/controller/service/include/general_controller_service_impl.h b/data_share/frameworks/native/consumer/controller/service/include/general_controller_service_impl.h new file mode 100644 index 00000000..bed139b8 --- /dev/null +++ b/data_share/frameworks/native/consumer/controller/service/include/general_controller_service_impl.h @@ -0,0 +1,49 @@ +/* + * 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 GENERAL_CONTROLLER_SERVICE_IMPL_H +#define GENERAL_CONTROLLER_SERVICE_IMPL_H + +#include "data_share_manager_impl.h" +#include "general_controller.h" + +namespace OHOS { +namespace AAFwk { +class IDataAbilityObserver; +} + +namespace DataShare { +class GeneralControllerServiceImpl : public GeneralController { +public: + GeneralControllerServiceImpl() = default; + + virtual ~GeneralControllerServiceImpl() = default; + + int Insert(const Uri &uri, const DataShareValuesBucket &value) override; + + int Update(const Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value) override; + + int Delete(const Uri &uri, const DataSharePredicates &predicates) override; + + std::shared_ptr Query(const Uri &uri, const DataSharePredicates &predicates, + std::vector &columns, DatashareBusinessError &businessError) override; + + void RegisterObserver(const Uri &uri, const sptr &dataObserver) override; + + void UnregisterObserver(const Uri &uri, const sptr &dataObserver) override; +}; +} // namespace DataShare +} // namespace OHOS +#endif // GENERAL_CONTROLLER_SERVICE_IMPL_H diff --git a/data_share/frameworks/native/consumer/controller/service/include/persistent_data_controller.h b/data_share/frameworks/native/consumer/controller/service/include/persistent_data_controller.h new file mode 100644 index 00000000..c8f194fd --- /dev/null +++ b/data_share/frameworks/native/consumer/controller/service/include/persistent_data_controller.h @@ -0,0 +1,49 @@ +/* + * 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 PERSISTENT_DATA_CONTROLLER_H +#define PERSISTENT_DATA_CONTROLLER_H + +#include "data_share_manager_impl.h" +#include "datashare_template.h" + +namespace OHOS { +namespace DataShare { +class PersistentDataController { +public: + PersistentDataController() = default; + + virtual ~PersistentDataController() = default; + + int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl); + + int DelQueryTemplate(const std::string &uri, int64_t subscriberId); + + std::vector SubscribeRdbData(void *subscriber, const std::vector &uris, + const TemplateId &templateId, std::function callback); + + std::vector UnSubscribeRdbData(void *subscriber, const std::vector &uris, + const TemplateId &templateId); + + std::vector EnableSubscribeRdbData(void *subscriber, const std::vector &uris, + const TemplateId &templateId); + + std::vector DisableSubscribeRdbData(void *subscriber, const std::vector &uris, + const TemplateId &templateId); +}; +} // namespace DataShare +} // namespace OHOS + +#endif // PERSISTENT_DATA_CONTROLLER_H diff --git a/data_share/frameworks/native/consumer/controller/service/include/published_data_controller.h b/data_share/frameworks/native/consumer/controller/service/include/published_data_controller.h new file mode 100644 index 00000000..acfbb2cc --- /dev/null +++ b/data_share/frameworks/native/consumer/controller/service/include/published_data_controller.h @@ -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. + */ + +#ifndef PUBLISHED_DATA_CONTROLLER_H +#define PUBLISHED_DATA_CONTROLLER_H + +#include "datashare_template.h" +#include "data_share_manager_impl.h" + +namespace OHOS { +namespace DataShare { +class PublishedDataController { +public: + PublishedDataController() = default; + + virtual ~PublishedDataController() = default; + + std::vector Publish(const Data &data, const std::string &bundleName); + + Data GetPublishedData(const std::string &bundleName, int &resultCode); + + std::vector SubscribePublishedData(void *subscriber, const std::vector &uris, + int64_t subscriberId, const std::function &callback); + + std::vector UnSubscribePublishedData(void *subscriber, const std::vector &uris, + int64_t subscriberId); + + std::vector EnableSubscribePublishedData(void *subscriber, const std::vector &uris, + int64_t subscriberId); + + std::vector DisableSubscribePublishedData(void *subscriber, const std::vector &uris, + int64_t subscriberId); +}; + +} // namespace DataShare +} // namespace OHOS + +#endif // PUBLISHED_DATA_CONTROLLER_H diff --git a/data_share/frameworks/native/consumer/controller/service/src/general_controller_service_impl.cpp b/data_share/frameworks/native/consumer/controller/service/src/general_controller_service_impl.cpp new file mode 100644 index 00000000..1163df66 --- /dev/null +++ b/data_share/frameworks/native/consumer/controller/service/src/general_controller_service_impl.cpp @@ -0,0 +1,94 @@ +/* + * 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 "general_controller_service_impl.h" + +#include "dataobs_mgr_client.h" +#include "datashare_log.h" + +namespace OHOS { +namespace DataShare { +constexpr int INVALID_VALUE = -1; +int GeneralControllerServiceImpl::Insert(const Uri &uri, const DataShareValuesBucket &value) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return INVALID_VALUE; + } + return proxy->Insert(uri, value); +} + +int GeneralControllerServiceImpl::Update(const Uri &uri, const DataSharePredicates &predicates, + const DataShareValuesBucket &value) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return INVALID_VALUE; + } + return proxy->Update(uri, predicates, value); +} + +int GeneralControllerServiceImpl::Delete(const Uri &uri, const DataSharePredicates &predicates) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return INVALID_VALUE; + } + return proxy->Delete(uri, predicates); +} + +std::shared_ptr GeneralControllerServiceImpl::Query(const Uri &uri, + const DataSharePredicates &predicates, std::vector &columns, DatashareBusinessError &businessError) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return nullptr; + } + return proxy->Query(uri, predicates, columns, businessError); +} + +void GeneralControllerServiceImpl::RegisterObserver(const Uri &uri, + const sptr &dataObserver) +{ + auto obsMgrClient = OHOS::AAFwk::DataObsMgrClient::GetInstance(); + if (obsMgrClient == nullptr) { + LOG_ERROR("get DataObsMgrClient failed"); + return; + } + ErrCode ret = obsMgrClient->RegisterObserver(uri, dataObserver); + if (ret != ERR_OK) { + LOG_ERROR("RegisterObserver failed"); + } +} + +void GeneralControllerServiceImpl::UnregisterObserver(const Uri &uri, + const sptr &dataObserver) +{ + auto obsMgrClient = OHOS::AAFwk::DataObsMgrClient::GetInstance(); + if (obsMgrClient == nullptr) { + LOG_ERROR("get DataObsMgrClient failed"); + return; + } + ErrCode ret = obsMgrClient->UnregisterObserver(uri, dataObserver); + if (ret != ERR_OK) { + LOG_ERROR("UnregisterObserver failed"); + } +} +} // namespace DataShare +} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/consumer/controller/service/src/persistent_data_controller.cpp b/data_share/frameworks/native/consumer/controller/service/src/persistent_data_controller.cpp new file mode 100644 index 00000000..9e1b5e50 --- /dev/null +++ b/data_share/frameworks/native/consumer/controller/service/src/persistent_data_controller.cpp @@ -0,0 +1,92 @@ +/* + * 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 "persistent_data_controller.h" + +#include "datashare_log.h" +#include "rdb_subscriber_manager.h" + +namespace OHOS { +namespace DataShare { +constexpr int INVALID_VALUE = -1; +int PersistentDataController::AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return INVALID_VALUE; + } + return proxy->AddQueryTemplate(uri, subscriberId, tpl); +} + +int PersistentDataController::DelQueryTemplate(const std::string &uri, int64_t subscriberId) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return INVALID_VALUE; + } + return proxy->DelQueryTemplate(uri, subscriberId); +} + +std::vector PersistentDataController::SubscribeRdbData(void *subscriber, + const std::vector &uris, const TemplateId &templateId, + std::function callback) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + return RdbSubscriberManager::GetInstance().AddObservers(subscriber, proxy, uris, templateId, callback); +} + +std::vector PersistentDataController::UnSubscribeRdbData(void *subscriber, + const std::vector &uris, const TemplateId &templateId) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + + if (uris.empty()) { + return RdbSubscriberManager::GetInstance().DelObservers(subscriber, proxy); + } + return RdbSubscriberManager::GetInstance().DelObservers(subscriber, proxy, uris, templateId); +} + +std::vector PersistentDataController::EnableSubscribeRdbData(void *subscriber, + const std::vector &uris, const TemplateId &templateId) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + return RdbSubscriberManager::GetInstance().EnableObservers(subscriber, proxy, uris, templateId); +} + +std::vector PersistentDataController::DisableSubscribeRdbData(void *subscriber, + const std::vector &uris, const TemplateId &templateId) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + return RdbSubscriberManager::GetInstance().DisableObservers(subscriber, proxy, uris, templateId); +} +} // namespace DataShare +} // namespace OHOS diff --git a/data_share/frameworks/native/consumer/controller/service/src/published_data_controller.cpp b/data_share/frameworks/native/consumer/controller/service/src/published_data_controller.cpp new file mode 100644 index 00000000..6bc8893a --- /dev/null +++ b/data_share/frameworks/native/consumer/controller/service/src/published_data_controller.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. + */ + +#include "published_data_controller.h" + +#include "datashare_log.h" +#include "published_data_subscriber_manager.h" + +namespace OHOS { +namespace DataShare { +std::vector PublishedDataController::Publish(const Data &data, const std::string &bundleName) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + return proxy->Publish(data, bundleName); +} + +Data PublishedDataController::GetPublishedData(const std::string &bundleName, int &resultCode) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return Data(); + } + return proxy->GetPublishedData(bundleName, resultCode); +} + +std::vector PublishedDataController::SubscribePublishedData(void *subscriber, + const std::vector &uris, int64_t subscriberId, + const std::function &callback) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + return PublishedDataSubscriberManager::GetInstance().AddObservers(subscriber, proxy, uris, subscriberId, callback); +} + +std::vector PublishedDataController::UnSubscribePublishedData(void *subscriber, + const std::vector &uris, int64_t subscriberId) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + if (uris.empty()) { + return PublishedDataSubscriberManager::GetInstance().DelObservers(subscriber, proxy); + } + return PublishedDataSubscriberManager::GetInstance().DelObservers(subscriber, proxy, uris, subscriberId); +} + +std::vector PublishedDataController::EnableSubscribePublishedData(void *subscriber, + const std::vector &uris, int64_t subscriberId) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + return PublishedDataSubscriberManager::GetInstance().EnableObservers(subscriber, proxy, uris, subscriberId); +} + +std::vector PublishedDataController::DisableSubscribePublishedData(void *subscriber, + const std::vector &uris, int64_t subscriberId) +{ + auto proxy = DataShareManagerImpl::GetInstance().GetServiceProxy(); + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + return PublishedDataSubscriberManager::GetInstance().DisableObservers(subscriber, proxy, uris, subscriberId); +} +} // namespace DataShare +} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/consumer/include/datashare_connection.h b/data_share/frameworks/native/consumer/include/datashare_connection.h index e1993281..a72461b2 100644 --- a/data_share/frameworks/native/consumer/include/datashare_connection.h +++ b/data_share/frameworks/native/consumer/include/datashare_connection.h @@ -20,7 +20,6 @@ #include #include "ability_connect_callback_stub.h" -#include "base_connection.h" #include "datashare_proxy.h" #include "event_handler.h" #include "want.h" @@ -28,7 +27,7 @@ namespace OHOS { namespace DataShare { using namespace AppExecFwk; -class DataShareConnection : public AAFwk::AbilityConnectionStub, public BaseConnection { +class DataShareConnection : public AAFwk::AbilityConnectionStub { public: DataShareConnection(const Uri &uri, const sptr &token) : uri_(uri), token_(token) {} virtual ~DataShareConnection(); @@ -66,15 +65,15 @@ public: * * @return the proxy of datashare extension ability. */ - std::shared_ptr GetDataShareProxy() override; - bool ConnectDataShare(const Uri &uri, const sptr &token) override ; + std::shared_ptr GetDataShareProxy(const Uri &uri, const sptr &token); + private: struct ConnectCondition { std::condition_variable condition; std::mutex mutex; }; void SetDataShareProxy(sptr proxy); - bool ConnectDataShareExtAbility(const Uri &uri, const sptr &token); + std::shared_ptr ConnectDataShareExtAbility(const Uri &uri, const sptr &token); std::mutex mutex_; std::shared_ptr dataShareProxy_; ConnectCondition condition_; diff --git a/data_share/frameworks/native/consumer/include/datashare_helper_impl.h b/data_share/frameworks/native/consumer/include/datashare_helper_impl.h new file mode 100644 index 00000000..24cf3930 --- /dev/null +++ b/data_share/frameworks/native/consumer/include/datashare_helper_impl.h @@ -0,0 +1,102 @@ +/* + * 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 DATA_SHARE_HELPER_IMPL_H +#define DATA_SHARE_HELPER_IMPL_H + +#include "datashare_helper.h" +#include "ext_special_controller.h" +#include "general_controller.h" +#include "persistent_data_controller.h" +#include "published_data_controller.h" + +namespace OHOS::DataShare { +class DataShareHelperImpl : public DataShareHelper { +public: + DataShareHelperImpl(const Uri &uri, const sptr &token, + std::shared_ptr connection); + DataShareHelperImpl(); + + ~DataShareHelperImpl() override; + + bool Release() override; + + std::vector GetFileTypes(Uri &uri, const string &mimeTypeFilter) override; + + int OpenFile(Uri &uri, const string &mode) override; + + int OpenRawFile(Uri &uri, const string &mode) override; + + int Insert(Uri &uri, const DataShareValuesBucket &value) override; + + int Update(Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value) override; + + int Delete(Uri &uri, const DataSharePredicates &predicates) override; + + std::shared_ptr Query(Uri &uri, const DataSharePredicates &predicates, + std::vector &columns, DatashareBusinessError *businessError) override; + + string GetType(Uri &uri) override; + + int BatchInsert(Uri &uri, const std::vector &values) override; + + void RegisterObserver(const Uri &uri, const sptr &dataObserver) override; + + void UnregisterObserver(const Uri &uri, const sptr &dataObserver) override; + + void NotifyChange(const Uri &uri) override; + + Uri NormalizeUri(Uri &uri) override; + + Uri DenormalizeUri(Uri &uri) override; + + int AddQueryTemplate(const string &uri, int64_t subscriberId, Template &tpl) override; + + int DelQueryTemplate(const string &uri, int64_t subscriberId) override; + + std::vector Publish(const Data &data, const string &bundleName) override; + + Data GetPublishedData(const string &bundleName, int &resultCode) override; + + std::vector SubscribeRdbData(const std::vector &uris, const TemplateId &templateId, + const std::function &callback) override; + + std::vector UnsubscribeRdbData(const std::vector &uris, + const TemplateId &templateId) override; + + std::vector EnableRdbSubs(const std::vector &uris, + const TemplateId &templateId) override; + + std::vector DisableRdbSubs(const std::vector &uris, + const TemplateId &templateId) override; + + std::vector SubscribePublishedData(const std::vector &uris, int64_t subscriberId, + const std::function &callback) override; + + std::vector UnsubscribePublishedData(const std::vector &uris, + int64_t subscriberId) override; + + std::vector EnablePubSubs(const std::vector &uris, int64_t subscriberId) override; + + std::vector DisablePubSubs(const std::vector &uris, int64_t subscriberId) override; + +private: + std::shared_ptr extSpCtl_ = nullptr; + std::shared_ptr generalCtl_ = nullptr; + std::shared_ptr persistentDataCtl_ = nullptr; + std::shared_ptr publishedDataCtl_ = nullptr; +}; +} // namespace OHOS::DataShare +#endif // DATA_SHARE_HELPER_IMPL_H diff --git a/data_share/frameworks/native/consumer/include/datashare_proxy.h b/data_share/frameworks/native/consumer/include/datashare_proxy.h index 81bef576..bf96e6c1 100644 --- a/data_share/frameworks/native/consumer/include/datashare_proxy.h +++ b/data_share/frameworks/native/consumer/include/datashare_proxy.h @@ -23,7 +23,7 @@ namespace OHOS { namespace DataShare { -class DataShareProxy : public IRemoteProxy, public BaseProxy { +class DataShareProxy final : public IRemoteProxy { public: explicit DataShareProxy(const sptr& remote) : IRemoteProxy(remote) {} @@ -59,38 +59,6 @@ public: virtual Uri DenormalizeUri(const Uri &uri) override; - int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) override; - - int DelQueryTemplate(const std::string &uri, int64_t subscriberId) override; - - std::vector Publish(const Data &data, const std::string &bundleName) override; - - Data GetPublishedData(const std::string &bundleName) override; - - std::vector SubscribeRdbData(const std::vector &uris, const TemplateId &templateId, - const sptr &observer) override; - - std::vector UnSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) override; - - std::vector EnableSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) override; - - std::vector DisableSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) override; - - std::vector SubscribePublishedData(const std::vector &uris, int64_t subscriberId, - const sptr &observer) override; - - std::vector UnSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) override; - - std::vector EnableSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) override; - - std::vector DisableSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) override; - private: static inline BrokerDelegator delegator_; }; diff --git a/data_share/frameworks/native/consumer/src/connection_factory.cpp b/data_share/frameworks/native/consumer/src/connection_factory.cpp deleted file mode 100644 index c411541d..00000000 --- a/data_share/frameworks/native/consumer/src/connection_factory.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* - * 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. - */ - -#include "connection_factory.h" - -#include - -#include "datashare_connection.h" -#include "datashare_log.h" -#include "data_share_manager_impl.h" - -namespace OHOS { -namespace DataShare { -std::shared_ptr ConnectionFactory::GetConnection(Uri &uri, const sptr token) -{ - if (uri.GetQuery().find("Proxy=true") != std::string::npos && service_->ConnectDataShare(uri, token)) { - return service_; - } - - sptr connection = new (std::nothrow) DataShareConnection(uri, token); - if (connection == nullptr) { - LOG_ERROR("Factory Create DataShareConnection failed."); - return nullptr; - } - return std::shared_ptr(connection.GetRefPtr(), [holder = connection](const auto *) { - holder->DisconnectDataShareExtAbility(); - }); -} - -std::shared_ptr ConnectionFactory::GetConnection(const Uri &uri, const CreateOptions &options) -{ - if (options.isProxy_ && service_->ConnectDataShare(uri, options.token_)) { - return service_; - } - - sptr connection = new (std::nothrow) DataShareConnection(uri, options.token_); - if (connection == nullptr) { - LOG_ERROR("Factory Create DataShareConnection failed."); - return nullptr; - } - return std::shared_ptr( - connection.GetRefPtr(), [holder = connection](const auto *) {}); -} - -ConnectionFactory& ConnectionFactory::GetInstance() -{ - static ConnectionFactory manager; - return manager; -} - -ConnectionFactory::ConnectionFactory() -{ - service_ = std::make_shared(); -} -} -} \ No newline at end of file diff --git a/data_share/frameworks/native/consumer/src/datashare_connection.cpp b/data_share/frameworks/native/consumer/src/datashare_connection.cpp index 14b74710..6bfd9f3c 100644 --- a/data_share/frameworks/native/consumer/src/datashare_connection.cpp +++ b/data_share/frameworks/native/consumer/src/datashare_connection.cpp @@ -70,10 +70,11 @@ void DataShareConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName /** * @brief connect remote ability of DataShareExtAbility. */ -bool DataShareConnection::ConnectDataShareExtAbility(const Uri &uri, const sptr &token) +std::shared_ptr DataShareConnection::ConnectDataShareExtAbility(const Uri &uri, + const sptr &token) { if (dataShareProxy_ != nullptr) { - return true; + return dataShareProxy_; } AAFwk::Want want; @@ -85,14 +86,14 @@ bool DataShareConnection::ConnectDataShareExtAbility(const Uri &uri, const sptr< ErrCode ret = AAFwk::AbilityManagerClient::GetInstance()->ConnectAbility(want, this, token); if (ret != ERR_OK) { LOG_ERROR("connect ability failed, ret = %{public}d", ret); - return false; + return nullptr; } std::unique_lock lock(condition_.mutex); if (condition_.condition.wait_for(lock, std::chrono::seconds(WAIT_TIME), [this] { return dataShareProxy_ != nullptr; })) { LOG_DEBUG("connect ability ended successfully"); } - return dataShareProxy_ != nullptr; + return dataShareProxy_; } /** @@ -133,12 +134,8 @@ DataShareConnection::~DataShareConnection() { } -std::shared_ptr DataShareConnection::GetDataShareProxy() -{ - return dataShareProxy_; -} - -bool DataShareConnection::ConnectDataShare(const Uri & uri, const sptr &token) +std::shared_ptr DataShareConnection::GetDataShareProxy(const Uri &uri, + const sptr &token) { return ConnectDataShareExtAbility(uri, token); } diff --git a/data_share/frameworks/native/consumer/src/datashare_helper.cpp b/data_share/frameworks/native/consumer/src/datashare_helper.cpp index f4636290..3017fc88 100644 --- a/data_share/frameworks/native/consumer/src/datashare_helper.cpp +++ b/data_share/frameworks/native/consumer/src/datashare_helper.cpp @@ -14,14 +14,13 @@ */ #include "datashare_helper.h" +#include "datashare_helper_impl.h" -#include "connection_factory.h" #include "concurrent_map.h" #include "data_ability_observer_interface.h" #include "data_ability_observer_stub.h" #include "dataobs_mgr_client.h" #include "datashare_log.h" -#include "datashare_result_set.h" namespace OHOS { namespace DataShare { @@ -29,10 +28,8 @@ using namespace AppExecFwk; namespace { static constexpr const char *SCHEME_DATASHARE = "datashare"; static constexpr const char *SCHEME_DATASHARE_PROXY = "datashareproxy"; -static constexpr const char *FILE_SCHEMA = "file"; static constexpr const char *DATA_SHARE_PREFIX = "datashare:///"; static constexpr const char *FILE_PREFIX = "file://"; -constexpr int INVALID_VALUE = -1; } // namespace class ObserverImpl : public AAFwk::DataAbilityObserverStub { public: @@ -47,7 +44,7 @@ public: static bool DeleteObserver(const Uri& uri, const std::shared_ptr &observer); private: struct ObserverParam { - sptr obs_; + sptr obs_; std::list uris_; }; std::shared_ptr dataShareObserver_; @@ -56,38 +53,6 @@ private: ConcurrentMap ObserverImpl::observers_; -DataShareHelper::DataShareHelper(const sptr &token, const Uri &uri, - std::shared_ptr dataShareConnection) -{ - token_ = token; - uri_ = uri; - isDataShareService_ = (uri_.GetQuery().find("Proxy=true") != std::string::npos); - connection_ = dataShareConnection; -} - -DataShareHelper::DataShareHelper(const sptr &token, const Uri &uri) -{ - token_ = token; - uri_ = uri; - isDataShareService_ = (uri_.GetQuery().find("Proxy=true") != std::string::npos); -} - -DataShareHelper::DataShareHelper(const CreateOptions &options, const Uri &uri, - std::shared_ptr dataShareConnection) -{ - token_ = options.token_; - uri_ = uri; - isDataShareService_ = options.isProxy_; - connection_ = dataShareConnection; - rdbSubscriberManager_ = std::make_shared(); - publishedDataSubscriberManager_ = - std::make_shared(); -} - -DataShareHelper::~DataShareHelper() -{ -} - std::string DataShareHelper::TransferUriPrefix(const std::string &originPrefix, const std::string &replacedPrefix, const std::string &originUriStr) { @@ -143,26 +108,14 @@ std::shared_ptr DataShareHelper::Creator(const sptr connection = ConnectionFactory::GetInstance().GetConnection(uri, token); - if (connection == nullptr) { - LOG_ERROR("create dataShareConnection failed"); - return nullptr; - } - if (!connection->ConnectDataShare(uri, token)) { - LOG_ERROR("connect failed"); - return nullptr; + if (uri.GetQuery().find("Proxy=true") != std::string::npos) { + return CreateServiceHelper(); } - DataShareHelper *ptrDataShareHelper = new (std::nothrow) DataShareHelper(token, uri, connection); - if (ptrDataShareHelper == nullptr) { - LOG_ERROR("create DataShareHelper failed"); - connection = nullptr; - return nullptr; - } - - return std::shared_ptr(ptrDataShareHelper); + return CreateExtHelper(uri, token); } -std::shared_ptr DataShareHelper::Creator(const string &strUri, const CreateOptions &options) +std::shared_ptr DataShareHelper::Creator(const string &strUri, const CreateOptions &options, + const std::string &bundleName) { Uri uri(strUri); if (!options.isProxy_ && options.token_ == nullptr) { @@ -173,409 +126,38 @@ std::shared_ptr DataShareHelper::Creator(const string &strUri, LOG_ERROR("the Scheme is not datashareproxy, Scheme: %{public}s", uri.GetScheme().c_str()); return nullptr; } - std::shared_ptr connection = ConnectionFactory::GetInstance().GetConnection(uri, options); - if (connection == nullptr) { - LOG_ERROR("create dataShareConnection failed"); - return nullptr; - } - if (!connection->ConnectDataShare(uri, options.token_)) { - LOG_ERROR("connect failed"); - return nullptr; - } - DataShareHelper *ptrDataShareHelper = new (std::nothrow) DataShareHelper(options, uri, connection); - if (ptrDataShareHelper == nullptr) { - LOG_ERROR("create DataShareHelper failed"); - connection = nullptr; - return nullptr; - } - return std::shared_ptr(ptrDataShareHelper); -} - -/** - * @brief Releases the client resource of the data share. - * You should call this method to releases client resource after the data operations are complete. - * - * @return Returns true if the resource is successfully released; returns false otherwise. - */ -bool DataShareHelper::Release() -{ - connection_ = nullptr; - uri_ = Uri(""); - return true; -} - -/** - * @brief Obtains the MIME types of files supported. - * - * @param uri Indicates the path of the files to obtain. - * @param mimeTypeFilter Indicates the MIME types of the files to obtain. This parameter cannot be null. - * - * @return Returns the matched MIME types. If there is no match, null is returned. - */ -std::vector DataShareHelper::GetFileTypes(Uri &uri, const std::string &mimeTypeFilter) -{ - std::vector matchedMIMEs; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return matchedMIMEs; - } - - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return matchedMIMEs; - } - - auto proxy = connection->GetDataShareProxy(); - if (proxy != nullptr) { - matchedMIMEs = proxy->GetFileTypes(uri, mimeTypeFilter); - } - return matchedMIMEs; -} - -/** - * @brief Opens a file in a specified remote path. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing data, - * or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the file descriptor. - */ -int DataShareHelper::OpenFile(Uri &uri, const std::string &mode) -{ - int fd = INVALID_VALUE; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return fd; - } - - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return fd; - } - - auto proxy = connection->GetDataShareProxy(); - if (proxy != nullptr) { - fd = proxy->OpenFile(uri, mode); - } - return fd; -} - -/** - * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets - * inside of their .hap. - * - * @param uri Indicates the path of the file to open. - * @param mode Indicates the file open mode, which can be "r" for read-only access, "w" for write-only access - * (erasing whatever data is currently in the file), "wt" for write access that truncates any existing file, - * "wa" for write-only access to append to any existing data, "rw" for read and write access on any existing - * data, or "rwt" for read and write access that truncates any existing file. - * - * @return Returns the RawFileDescriptor object containing file descriptor. - */ -int DataShareHelper::OpenRawFile(Uri &uri, const std::string &mode) -{ - int fd = INVALID_VALUE; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return fd; + if (options.isProxy_) { + return CreateServiceHelper(bundleName); } - - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return fd; - } - - auto proxy = connection->GetDataShareProxy(); - if (proxy != nullptr) { - fd = proxy->OpenRawFile(uri, mode); - } - return fd; + return CreateExtHelper(uri, options.token_); } -/** - * @brief Inserts a single data record into the database. - * - * @param uri Indicates the path of the data to operate. - * @param value Indicates the data record to insert. If this parameter is null, a blank row will be inserted. - * - * @return Returns the index of the inserted data record. - */ -int DataShareHelper::Insert(Uri &uri, const DataShareValuesBucket &value) +std::shared_ptr DataShareHelper::CreateServiceHelper(const std::string &bundleName) { - int index = INVALID_VALUE; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return index; - } - - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return index; - } - - auto proxy = connection->GetDataShareProxy(); - if (proxy != nullptr) { - index = proxy->Insert(uri, value); - } - return index; -} - -/** - * @brief Updates data records in the database. - * - * @param uri Indicates the path of data to update. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @param value Indicates the data to update. This parameter can be null. - * - * @return Returns the number of data records updated. - */ -int DataShareHelper::Update(Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value) -{ - int index = INVALID_VALUE; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return index; - } - - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return index; - } - - auto proxy = connection->GetDataShareProxy(); - if (proxy != nullptr) { - index = proxy->Update(uri, predicates, value); - } - return index; -} - -/** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of the data to operate. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * - * @return Returns the number of data records deleted. - */ -int DataShareHelper::Delete(Uri &uri, const DataSharePredicates &predicates) -{ - int index = INVALID_VALUE; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return index; - } - - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return index; - } - - auto proxy = connection->GetDataShareProxy(); - if (proxy != nullptr) { - index = proxy->Delete(uri, predicates); - } - return index; -} - -/** - * @brief Deletes one or more data records from the database. - * - * @param uri Indicates the path of data to query. - * @param predicates Indicates filter criteria. You should define the processing logic when this parameter is null. - * @param columns Indicates the columns to query. If this parameter is null, all columns are queried. - * - * @return Returns the query result. - */ -std::shared_ptr DataShareHelper::Query(Uri &uri, const DataSharePredicates &predicates, - std::vector &columns, DatashareBusinessError *businessError) -{ - std::shared_ptr resultset = nullptr; - - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return resultset; - } - - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return resultset; - } - - auto proxy = connection->GetDataShareProxy(); - if (proxy != nullptr) { - DatashareBusinessError error; - resultset = proxy->Query(uri, predicates, columns, error); - if (businessError != nullptr) { - *businessError = error; - } - } - return resultset; -} - -/** - * @brief Obtains the MIME type matching the data specified by the URI of the data share. This method should be - * implemented by a data share. Data abilities supports general data types, including text, HTML, and JPEG. - * - * @param uri Indicates the URI of the data. - * - * @return Returns the MIME type that matches the data specified by uri. - */ -std::string DataShareHelper::GetType(Uri &uri) -{ - std::string type; - - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return type; - } - - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return type; - } - - auto proxy = connection->GetDataShareProxy(); - if (proxy != nullptr) { - type = proxy->GetType(uri); + DataShareManagerImpl::GetInstance().SetBundleName(bundleName); + if (DataShareManagerImpl::GetInstance().GetServiceProxy() == nullptr) { + LOG_ERROR("service proxy is nullptr."); + return nullptr; } - return type; + return std::make_shared(); } -/** - * @brief Inserts multiple data records into the database. - * - * @param uri Indicates the path of the data to operate. - * @param values Indicates the data records to insert. - * - * @return Returns the number of data records inserted. - */ -int DataShareHelper::BatchInsert(Uri &uri, const std::vector &values) +std::shared_ptr DataShareHelper::CreateExtHelper(Uri &uri, const sptr &token) { - int ret = INVALID_VALUE; - auto connection = connection_; + sptr connection = new (std::nothrow) DataShareConnection(uri, token); if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return ret; - } - - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return ret; - } - - auto proxy = connection->GetDataShareProxy(); - if (proxy != nullptr) { - ret = proxy->BatchInsert(uri, values); - } - return ret; -} - -/** - * @brief Registers an observer to DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ -void DataShareHelper::RegisterObserver(const Uri &uri, const sptr &dataObserver) -{ - LOG_INFO("Start"); - if (dataObserver == nullptr) { - LOG_ERROR("dataObserver is nullptr"); - return; - } - if (isDataShareService_) { - if (!RegObserver(uri, dataObserver)) { - LOG_ERROR("RegisterObserver failed"); - } - return; - } - - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return; + LOG_ERROR("Create DataShareConnection failed."); + return nullptr; } - - if (!connection->ConnectDataShare(uri, token_)) { + auto dataShareConnection = + std::shared_ptr(connection.GetRefPtr(), [holder = connection](const auto *) { + holder->DisconnectDataShareExtAbility(); + }); + if (dataShareConnection->GetDataShareProxy(uri, token) == nullptr) { LOG_ERROR("connect failed"); - return; - } - - auto proxy = connection->GetDataShareProxy(); - if (proxy == nullptr) { - LOG_ERROR("proxy has disconnected"); - return; - } - proxy->RegisterObserver(uri, dataObserver); -} - -/** - * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. - * - * @param uri, Indicates the path of the data to operate. - * @param dataObserver, Indicates the IDataAbilityObserver object. - */ -void DataShareHelper::UnregisterObserver(const Uri &uri, const sptr &dataObserver) -{ - LOG_INFO("Start"); - if (dataObserver == nullptr) { - LOG_ERROR("dataObserver is nullptr"); - return; - } - - if (isDataShareService_) { - if (!UnregObserver(uri, dataObserver)) { - LOG_ERROR("UnregisterObserver failed"); - } - return; - } - - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return; - } - auto proxy = connection->GetDataShareProxy(); - if (proxy == nullptr) { - LOG_ERROR("dataShareConnection_->GetDataShareProxy() is nullptr"); - return; - } - proxy->UnregisterObserver(uri, dataObserver); -} - -/** - * @brief Notifies the registered observers of a change to the data resource specified by Uri. - * - * @param uri, Indicates the path of the data to operate. - */ -void DataShareHelper::NotifyChange(const Uri &uri) -{ - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return; - } - - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return; - } - - auto proxy = connection->GetDataShareProxy(); - if (proxy != nullptr) { - proxy->NotifyChange(uri); + return nullptr; } + return std::make_shared(uri, token, dataShareConnection); } /** @@ -608,7 +190,6 @@ void DataShareHelper::RegisterObserverExt(const Uri &uri, std::shared_ptrUnregisterObserverExt(uri, obs); if (ret != ERR_OK) { LOG_ERROR("UnregisterObserverExt failed"); - } else { - ObserverImpl::DeleteObserver(uri, dataObserver); + return; } - return; + ObserverImpl::DeleteObserver(uri, dataObserver); } /** @@ -668,101 +248,6 @@ void DataShareHelper::NotifyChangeExt(const DataShareObserver::ChangeInfo &chang if (ret != ERR_OK) { LOG_ERROR("NotifyChangeExt failed"); } - return; -} - -/** - * @brief Converts the given uri that refer to the data share into a normalized URI. A normalized URI can be used - * across devices, persisted, backed up, and restored. It can refer to the same item in the data share even if the - * context has changed. If you implement URI normalization for a data share, you must also implement - * denormalizeUri(ohos.utils.net.Uri) to enable URI denormalization. After this feature is enabled, URIs passed to any - * method that is called on the data share must require normalization verification and denormalization. The default - * implementation of this method returns null, indicating that this data share does not support URI normalization. - * - * @param uri Indicates the Uri object to normalize. - * - * @return Returns the normalized Uri object if the data share supports URI normalization; returns null otherwise. - */ -Uri DataShareHelper::NormalizeUri(Uri &uri) -{ - Uri uriValue(""); - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return uriValue; - } - - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return uriValue; - } - - auto proxy = connection->GetDataShareProxy(); - if (proxy != nullptr) { - uriValue = proxy->NormalizeUri(uri); - } - return uriValue; -} - -/** - * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. - * The default implementation of this method returns the original URI passed to it. - * - * @param uri uri Indicates the Uri object to denormalize. - * - * @return Returns the denormalized Uri object if the denormalization is successful; returns the original Uri passed to - * this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found in - * the current environment. - */ -Uri DataShareHelper::DenormalizeUri(Uri &uri) -{ - Uri uriValue(""); - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return uriValue; - } - - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return uriValue; - } - - auto proxy = connection->GetDataShareProxy(); - if (proxy != nullptr) { - uriValue = proxy->DenormalizeUri(uri); - } - return uriValue; -} - -bool DataShareHelper::RegObserver(const Uri &uri, const sptr &dataObserver) -{ - auto obsMgrClient = OHOS::AAFwk::DataObsMgrClient::GetInstance(); - if (obsMgrClient == nullptr) { - LOG_ERROR("get DataObsMgrClient failed"); - return false; - } - ErrCode ret = obsMgrClient->RegisterObserver(uri, dataObserver); - if (ret != ERR_OK) { - LOG_ERROR("RegisterObserver failed"); - return false; - } - return true; -} - -bool DataShareHelper::UnregObserver(const Uri &uri, const sptr &dataObserver) -{ - auto obsMgrClient = OHOS::AAFwk::DataObsMgrClient::GetInstance(); - if (obsMgrClient == nullptr) { - LOG_ERROR("get DataObsMgrClient failed"); - return false; - } - ErrCode ret = obsMgrClient->UnregisterObserver(uri, dataObserver); - if (ret != ERR_OK) { - LOG_ERROR("UnregisterObserver failed"); - return false; - } - return true; } void ObserverImpl::OnChange() {} @@ -834,301 +319,5 @@ bool ObserverImpl::DeleteObserver(const Uri& uri, const std::shared_ptrConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return errNum; - } - auto proxy = connection->GetDataShareProxy(); - if (proxy == nullptr) { - LOG_ERROR("GetDataShareProxy is nullptr"); - return errNum; - } - return proxy->AddQueryTemplate(uri, subscriberId, tpl); -} - -int DataShareHelper::DelQueryTemplate(const std::string &uri, int64_t subscriberId) -{ - int errNum = INVALID_VALUE; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return errNum; - } - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return errNum; - } - auto proxy = connection->GetDataShareProxy(); - if (proxy == nullptr) { - LOG_ERROR("GetDataShareProxy is nullptr"); - return errNum; - } - return proxy->DelQueryTemplate(uri, subscriberId); -} - -std::vector DataShareHelper::Publish(const Data &data, - const std::string &bundleName) -{ - std::vector results; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return results; - } - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto proxy = connection->GetDataShareProxy(); - if (proxy == nullptr) { - LOG_ERROR("GetDataShareProxy is nullptr"); - return results; - } - return proxy->Publish(data, bundleName); -} - -Data DataShareHelper::GetPublishedData(const std::string &bundleName) -{ - Data results; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return results; - } - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto proxy = connection->GetDataShareProxy(); - if (proxy == nullptr) { - LOG_ERROR("GetDataShareProxy is nullptr"); - return results; - } - return proxy->GetPublishedData(bundleName); -} - -std::vector DataShareHelper::SubscribeRdbData(const std::vector &uris, - const TemplateId &templateId, const std::function &callback) -{ - LOG_DEBUG("Start SubscribeRdbData"); - std::vector results; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return results; - } - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto proxy = connection->GetDataShareProxy(); - if (proxy == nullptr) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto manager = rdbSubscriberManager_; - if (manager == nullptr) { - LOG_ERROR("rdbSubscriberManager_ is nullptr"); - return results; - } - return manager->AddObservers(proxy, uris, templateId, callback); -} - -std::vector DataShareHelper::UnsubscribeRdbData(const std::vector &uris, - const TemplateId &templateId) -{ - LOG_DEBUG("Start UnsubscribeRdbData"); - std::vector results; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return results; - } - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto proxy = connection->GetDataShareProxy(); - if (proxy == nullptr) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto manager = rdbSubscriberManager_; - if (manager == nullptr) { - LOG_ERROR("rdbSubscriberManager_ is nullptr"); - return results; - } - return manager->DelObservers(proxy, uris, templateId); -} - -std::vector DataShareHelper::EnableRdbSubs(const std::vector &uris, - const TemplateId &templateId) -{ - LOG_DEBUG("Start EnableSubscribeRdbData"); - std::vector results; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return results; - } - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto proxy = connection->GetDataShareProxy(); - if (proxy == nullptr) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto manager = rdbSubscriberManager_; - if (manager == nullptr) { - LOG_ERROR("rdbSubscriberManager_ is nullptr"); - return results; - } - return manager->EnableObservers(proxy, uris, templateId); -} - -std::vector DataShareHelper::DisableRdbSubs(const std::vector &uris, - const TemplateId &templateId) -{ - LOG_DEBUG("Start DisableSubscribeRdbData"); - std::vector results; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return results; - } - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto proxy = connection->GetDataShareProxy(); - if (proxy == nullptr) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto manager = rdbSubscriberManager_; - if (manager == nullptr) { - LOG_ERROR("rdbSubscriberManager_ is nullptr"); - return results; - } - return manager->DisableObservers(proxy, uris, templateId); -} - -std::vector DataShareHelper::SubscribePublishedData(const std::vector &uris, - int64_t subscriberId, const std::function &callback) -{ - std::vector results; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return results; - } - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto proxy = connection->GetDataShareProxy(); - if (proxy == nullptr) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto manager = publishedDataSubscriberManager_; - if (manager == nullptr) { - LOG_ERROR("rdbSubscriberManager_ is nullptr"); - return results; - } - return manager->AddObservers(proxy, uris, subscriberId, callback); -} - -std::vector DataShareHelper::UnsubscribePublishedData(const std::vector &uris, - int64_t subscriberId) -{ - LOG_DEBUG("Start UnSubscribePublishedData"); - std::vector results; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return results; - } - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto proxy = connection->GetDataShareProxy(); - if (proxy == nullptr) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto manager = publishedDataSubscriberManager_; - if (manager == nullptr) { - LOG_ERROR("rdbSubscriberManager_ is nullptr"); - return results; - } - return manager->DelObservers(proxy, uris, subscriberId); -} - -std::vector DataShareHelper::EnablePubSubs(const std::vector &uris, - int64_t subscriberId) -{ - LOG_DEBUG("Start UnSubscribePublishedData"); - std::vector results; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return results; - } - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto proxy = connection->GetDataShareProxy(); - if (proxy == nullptr) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto manager = publishedDataSubscriberManager_; - if (manager == nullptr) { - LOG_ERROR("rdbSubscriberManager_ is nullptr"); - return results; - } - return manager->EnableObservers(proxy, uris, subscriberId); -} - -std::vector DataShareHelper::DisablePubSubs(const std::vector &uris, - int64_t subscriberId) -{ - LOG_DEBUG("Start UnSubscribePublishedData"); - std::vector results; - auto connection = connection_; - if (connection == nullptr) { - LOG_ERROR("dataShareConnection_ is nullptr"); - return results; - } - if (!connection->ConnectDataShare(uri_, token_)) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto proxy = connection->GetDataShareProxy(); - if (proxy == nullptr) { - LOG_ERROR("dataShareProxy is nullptr"); - return results; - } - auto manager = publishedDataSubscriberManager_; - if (manager == nullptr) { - LOG_ERROR("rdbSubscriberManager_ is nullptr"); - return results; - } - return manager->DisableObservers(proxy, uris, subscriberId); -} } // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/consumer/src/datashare_helper_impl.cpp b/data_share/frameworks/native/consumer/src/datashare_helper_impl.cpp new file mode 100644 index 00000000..f845c627 --- /dev/null +++ b/data_share/frameworks/native/consumer/src/datashare_helper_impl.cpp @@ -0,0 +1,352 @@ +/* + * 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 "datashare_helper_impl.h" + +#include "concurrent_map.h" +#include "data_ability_observer_interface.h" +#include "dataobs_mgr_client.h" +#include "datashare_log.h" +#include "datashare_result_set.h" + +#include "general_controller_porvider_impl.h" +#include "general_controller_service_impl.h" + +namespace OHOS { +namespace DataShare { +using namespace AppExecFwk; +constexpr int INVALID_VALUE = -1; +DataShareHelperImpl::DataShareHelperImpl(const Uri &uri, const sptr &token, + std::shared_ptr connection) +{ + generalCtl_ = std::make_shared(connection, uri, token); + extSpCtl_ = std::make_shared(connection, uri, token); +} + +DataShareHelperImpl::DataShareHelperImpl() +{ + generalCtl_ = std::make_shared(); + persistentDataCtl_ = std::make_shared(); + publishedDataCtl_ = std::make_shared(); +} + +DataShareHelperImpl::~DataShareHelperImpl() +{ + if (persistentDataCtl_ != nullptr && publishedDataCtl_ != nullptr) { + persistentDataCtl_->UnSubscribeRdbData(this, {}, {}); + publishedDataCtl_->UnSubscribePublishedData(this, {}, {}); + } +} + +bool DataShareHelperImpl::Release() +{ + extSpCtl_ = nullptr; + generalCtl_ = nullptr; + return true; +} + +std::vector DataShareHelperImpl::GetFileTypes(Uri &uri, const std::string &mimeTypeFilter) +{ + auto extSpCtl = extSpCtl_; + if (extSpCtl == nullptr) { + LOG_ERROR("extSpCtl is nullptr"); + return std::vector(); + } + return extSpCtl->GetFileTypes(uri, mimeTypeFilter); +} + +int DataShareHelperImpl::OpenFile(Uri &uri, const std::string &mode) +{ + auto extSpCtl = extSpCtl_; + if (extSpCtl == nullptr) { + LOG_ERROR("extSpCtl is nullptr"); + return INVALID_VALUE; + } + return extSpCtl->OpenFile(uri, mode); +} + +int DataShareHelperImpl::OpenRawFile(Uri &uri, const std::string &mode) +{ + auto extSpCtl = extSpCtl_; + if (extSpCtl == nullptr) { + LOG_ERROR("extSpCtl is nullptr"); + return INVALID_VALUE; + } + return extSpCtl->OpenRawFile(uri, mode); +} + +int DataShareHelperImpl::Insert(Uri &uri, const DataShareValuesBucket &value) +{ + auto generalCtl = generalCtl_; + if (generalCtl == nullptr) { + LOG_ERROR("generalCtl_ is nullptr"); + return INVALID_VALUE; + } + return generalCtl->Insert(uri, value); +} + +int DataShareHelperImpl::Update(Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value) +{ + auto generalCtl = generalCtl_; + if (generalCtl == nullptr) { + LOG_ERROR("generalCtl is nullptr"); + return INVALID_VALUE; + } + return generalCtl->Update(uri, predicates, value); +} + +int DataShareHelperImpl::Delete(Uri &uri, const DataSharePredicates &predicates) +{ + auto generalCtl = generalCtl_; + if (generalCtl == nullptr) { + LOG_ERROR("generalCtl is nullptr"); + return INVALID_VALUE; + } + return generalCtl->Delete(uri, predicates); +} + +std::shared_ptr DataShareHelperImpl::Query(Uri &uri, const DataSharePredicates &predicates, + std::vector &columns, DatashareBusinessError *businessError) +{ + auto generalCtl = generalCtl_; + if (generalCtl == nullptr) { + LOG_ERROR("generalCtl is nullptr"); + return nullptr; + } + DatashareBusinessError error; + auto resultSet = generalCtl->Query(uri, predicates, columns, error); + if (businessError != nullptr) { + *businessError = error; + } + return resultSet; +} + +std::string DataShareHelperImpl::GetType(Uri &uri) +{ + auto extSpCtl = extSpCtl_; + if (extSpCtl == nullptr) { + LOG_ERROR("extSpCtl is nullptr"); + return ""; + } + return extSpCtl->GetType(uri); +} + +int DataShareHelperImpl::BatchInsert(Uri &uri, const std::vector &values) +{ + auto extSpCtl = extSpCtl_; + if (extSpCtl == nullptr) { + LOG_ERROR("providerSepOperator is nullptr"); + return INVALID_VALUE; + } + return extSpCtl->BatchInsert(uri, values); +} + +void DataShareHelperImpl::RegisterObserver(const Uri &uri, const sptr &dataObserver) +{ + LOG_INFO("Start"); + if (dataObserver == nullptr) { + LOG_ERROR("dataObserver is nullptr"); + return; + } + auto generalCtl = generalCtl_; + if (generalCtl == nullptr) { + LOG_ERROR("generalCtl is nullptr"); + return; + } + return generalCtl->RegisterObserver(uri, dataObserver); +} + +void DataShareHelperImpl::UnregisterObserver(const Uri &uri, const sptr &dataObserver) +{ + LOG_INFO("Start"); + if (dataObserver == nullptr) { + LOG_ERROR("dataObserver is nullptr"); + return; + } + auto generalCtl = generalCtl_; + if (generalCtl == nullptr) { + LOG_ERROR("generalCtl is nullptr"); + return; + } + return generalCtl->UnregisterObserver(uri, dataObserver); +} + +void DataShareHelperImpl::NotifyChange(const Uri &uri) +{ + auto extSpCtl = extSpCtl_; + if (extSpCtl == nullptr) { + LOG_ERROR("extSpCtl is nullptr"); + return; + } + return extSpCtl->NotifyChange(uri); +} + +Uri DataShareHelperImpl::NormalizeUri(Uri &uri) +{ + auto extSpCtl = extSpCtl_; + if (extSpCtl == nullptr) { + LOG_ERROR("extSpCtl is nullptr"); + return Uri(""); + } + return extSpCtl->NormalizeUri(uri); +} + +Uri DataShareHelperImpl::DenormalizeUri(Uri &uri) +{ + auto extSpCtl = extSpCtl_; + if (extSpCtl == nullptr) { + LOG_ERROR("extSpCtl is nullptr"); + return Uri(""); + } + return extSpCtl->DenormalizeUri(uri); +} + +int DataShareHelperImpl::AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) +{ + auto persistentDataCtl = persistentDataCtl_; + if (persistentDataCtl == nullptr) { + LOG_ERROR("persistentDataCtl is nullptr"); + return INVALID_VALUE; + } + return persistentDataCtl->AddQueryTemplate(uri, subscriberId, tpl); +} + +int DataShareHelperImpl::DelQueryTemplate(const std::string &uri, int64_t subscriberId) +{ + auto persistentDataCtl = persistentDataCtl_; + if (persistentDataCtl == nullptr) { + LOG_ERROR("persistentDataCtl is nullptr"); + return INVALID_VALUE; + } + return persistentDataCtl->DelQueryTemplate(uri, subscriberId); +} + +std::vector DataShareHelperImpl::Publish(const Data &data, const std::string &bundleName) +{ + auto publishedDataCtl = publishedDataCtl_; + if (publishedDataCtl == nullptr) { + LOG_ERROR("publishedDataCtl is nullptr"); + return std::vector(); + } + return publishedDataCtl->Publish(data, bundleName); +} + +Data DataShareHelperImpl::GetPublishedData(const std::string &bundleName, int &resultCode) +{ + auto publishedDataCtl = publishedDataCtl_; + if (publishedDataCtl == nullptr) { + LOG_ERROR("publishedDataCtl is nullptr"); + return Data(); + } + return publishedDataCtl->GetPublishedData(bundleName, resultCode); +} + +std::vector DataShareHelperImpl::SubscribeRdbData(const std::vector &uris, + const TemplateId &templateId, const std::function &callback) +{ + LOG_DEBUG("Start SubscribeRdbData"); + auto persistentDataCtl = persistentDataCtl_; + if (persistentDataCtl == nullptr) { + LOG_ERROR("persistentDataCtl is nullptr"); + return std::vector(); + } + return persistentDataCtl->SubscribeRdbData(this, uris, templateId, callback); +} + +std::vector DataShareHelperImpl::UnsubscribeRdbData(const std::vector &uris, + const TemplateId &templateId) +{ + LOG_DEBUG("Start UnsubscribeRdbData"); + auto persistentDataCtl = persistentDataCtl_; + if (persistentDataCtl == nullptr) { + LOG_ERROR("persistentDataCtl is nullptr"); + return std::vector(); + } + return persistentDataCtl->UnSubscribeRdbData(this, uris, templateId); +} + +std::vector DataShareHelperImpl::EnableRdbSubs(const std::vector &uris, + const TemplateId &templateId) +{ + LOG_DEBUG("Start EnableSubscribeRdbData"); + auto persistentDataCtl = persistentDataCtl_; + if (persistentDataCtl == nullptr) { + LOG_ERROR("persistentDataCtl is nullptr"); + return std::vector(); + } + return persistentDataCtl->EnableSubscribeRdbData(this, uris, templateId); +} + +std::vector DataShareHelperImpl::DisableRdbSubs(const std::vector &uris, + const TemplateId &templateId) +{ + LOG_DEBUG("Start DisableSubscribeRdbData"); + auto persistentDataCtl = persistentDataCtl_; + if (persistentDataCtl == nullptr) { + LOG_ERROR("persistentDataCtl is nullptr"); + return std::vector(); + } + return persistentDataCtl->DisableSubscribeRdbData(this, uris, templateId); +} + +std::vector DataShareHelperImpl::SubscribePublishedData(const std::vector &uris, + int64_t subscriberId, const std::function &callback) +{ + LOG_DEBUG("Start SubscribePublishedData"); + auto publishedDataCtl = publishedDataCtl_; + if (publishedDataCtl == nullptr) { + LOG_ERROR("publishedDataCtl is nullptr"); + return std::vector(); + } + return publishedDataCtl->SubscribePublishedData(this, uris, subscriberId, callback); +} + +std::vector DataShareHelperImpl::UnsubscribePublishedData(const std::vector &uris, + int64_t subscriberId) +{ + LOG_DEBUG("Start UnSubscribePublishedData"); + auto publishedDataCtl = publishedDataCtl_; + if (publishedDataCtl == nullptr) { + LOG_ERROR("publishedDataCtl is nullptr"); + return std::vector(); + } + return publishedDataCtl->UnSubscribePublishedData(this, uris, subscriberId); +} + +std::vector DataShareHelperImpl::EnablePubSubs(const std::vector &uris, + int64_t subscriberId) +{ + LOG_DEBUG("Start UnSubscribePublishedData"); + auto publishedDataCtl = publishedDataCtl_; + if (publishedDataCtl == nullptr) { + LOG_ERROR("publishedDataCtl is nullptr"); + return std::vector(); + } + return publishedDataCtl->EnableSubscribePublishedData(this, uris, subscriberId); +} + +std::vector DataShareHelperImpl::DisablePubSubs(const std::vector &uris, + int64_t subscriberId) +{ + LOG_DEBUG("Start UnSubscribePublishedData"); + auto publishedDataCtl = publishedDataCtl_; + if (publishedDataCtl == nullptr) { + LOG_ERROR("publishedDataCtl is nullptr"); + return std::vector(); + } + return publishedDataCtl->DisableSubscribePublishedData(this, uris, subscriberId); +} +} // namespace DataShare +} // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/consumer/src/datashare_proxy.cpp b/data_share/frameworks/native/consumer/src/datashare_proxy.cpp index a9f48779..157f6119 100644 --- a/data_share/frameworks/native/consumer/src/datashare_proxy.cpp +++ b/data_share/frameworks/native/consumer/src/datashare_proxy.cpp @@ -443,73 +443,5 @@ Uri DataShareProxy::DenormalizeUri(const Uri &uri) LOG_INFO("end successfully."); return info; } - -int DataShareProxy::AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) -{ - return -1; -} - -int DataShareProxy::DelQueryTemplate(const std::string &uri, int64_t subscriberId) -{ - return -1; -} - -std::vector DataShareProxy::Publish(const Data &data, const std::string &bundleName) -{ - return std::vector(); -} - -Data DataShareProxy::GetPublishedData(const std::string &bundleName) -{ - return Data(); -} - -std::vector DataShareProxy::SubscribeRdbData(const std::vector &uris, - const TemplateId &templateId, const sptr &observer) -{ - return std::vector(); -} - -std::vector DataShareProxy::UnSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) -{ - return {}; -} - -std::vector DataShareProxy::EnableSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) -{ - return {}; -} - -std::vector DataShareProxy::DisableSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) -{ - return {}; -} - -std::vector DataShareProxy::SubscribePublishedData( - const std::vector &uris, int64_t subscriberId, const sptr &observer) -{ - return {}; -} - -std::vector DataShareProxy::UnSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) -{ - return {}; -} - -std::vector DataShareProxy::EnableSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) -{ - return {}; -} - -std::vector DataShareProxy::DisableSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) -{ - return {}; -} } // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/provider/include/datashare_stub.h b/data_share/frameworks/native/provider/include/datashare_stub.h index ddd7c23c..02c0f15d 100644 --- a/data_share/frameworks/native/provider/include/datashare_stub.h +++ b/data_share/frameworks/native/provider/include/datashare_stub.h @@ -24,7 +24,7 @@ namespace OHOS { namespace DataShare { -class DataShareStub : public IRemoteStub, public BaseProxy { +class DataShareStub : public IRemoteStub { public: DataShareStub(); ~DataShareStub(); @@ -46,27 +46,6 @@ private: ErrCode CmdNormalizeUri(MessageParcel &data, MessageParcel &reply); ErrCode CmdDenormalizeUri(MessageParcel &data, MessageParcel &reply); - int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) override; - int DelQueryTemplate(const std::string &uri, int64_t subscriberId) override; - std::vector Publish(const Data &data, const std::string &bundleName) override; - Data GetPublishedData(const std::string &bundleName) override; - std::vector SubscribeRdbData(const std::vector &uris, const TemplateId &templateId, - const sptr &observer) override; - std::vector UnSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) override; - std::vector EnableSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) override; - std::vector DisableSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) override; - std::vector SubscribePublishedData(const std::vector &uris, int64_t subscriberId, - const sptr &observer) override; - std::vector UnSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) override; - std::vector EnableSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) override; - std::vector DisableSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) override; - using RequestFuncType = int (DataShareStub::*)(MessageParcel &data, MessageParcel &reply); std::map stubFuncMap_; static constexpr int VALUEBUCKET_MAX_COUNT = 3000; diff --git a/data_share/frameworks/native/provider/include/datashare_stub_impl.h b/data_share/frameworks/native/provider/include/datashare_stub_impl.h index 6f5bc2d7..620b1e26 100644 --- a/data_share/frameworks/native/provider/include/datashare_stub_impl.h +++ b/data_share/frameworks/native/provider/include/datashare_stub_impl.h @@ -64,26 +64,6 @@ public: Uri NormalizeUri(const Uri &uri) override; Uri DenormalizeUri(const Uri &uri) override; - int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) override; - int DelQueryTemplate(const std::string &uri, int64_t subscriberId) override; - std::vector Publish(const Data &data, const std::string &bundleName) override; - Data GetPublishedData(const std::string &bundleName) override; - std::vector SubscribeRdbData(const std::vector &uris, const TemplateId &templateId, - const sptr &observer) override; - std::vector UnSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) override; - std::vector EnableSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) override; - std::vector DisableSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) override; - std::vector SubscribePublishedData(const std::vector &uris, int64_t subscriberId, - const sptr &observer) override; - std::vector UnSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) override; - std::vector EnableSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) override; - std::vector DisableSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) override; private: std::shared_ptr GetOwner(); 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 41a61e33..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 @@ -300,14 +300,23 @@ public: { businessError_ = businessError; } - + struct AsyncContext { + bool isNeedNotify_ = false; + }; private: + struct AsyncPoint { + std::shared_ptr context; + }; NativeValue* CallObjectMethod(const char *name, NativeValue * const *argv = nullptr, size_t argc = 0, bool isAsync = true); + NativeValue *CallObjectMethod( + const char *name, NativeValue **argv, size_t argc, std::shared_ptr asyncContext); void GetSrcPath(std::string &srcPath); napi_value MakePredicates(napi_env env, const DataSharePredicates &predicates); static NativeValue* AsyncCallback(NativeEngine* engine, NativeCallbackInfo* info); + static NativeValue* AsyncCallbackWithContext(NativeEngine* engine, NativeCallbackInfo* info); void CheckAndSetAsyncResult(NativeEngine* engine); + static void NotifyToDataShareService(); static void UnWrapBusinessError(napi_env env, napi_value info, DatashareBusinessError &businessError); static napi_valuetype UnWrapPropertyType(napi_env env, napi_value info, const std::string &key); diff --git a/data_share/frameworks/native/provider/src/datashare_stub.cpp b/data_share/frameworks/native/provider/src/datashare_stub.cpp index 4d0ba05c..03ff16b1 100644 --- a/data_share/frameworks/native/provider/src/datashare_stub.cpp +++ b/data_share/frameworks/native/provider/src/datashare_stub.cpp @@ -351,73 +351,5 @@ ErrCode DataShareStub::CmdDenormalizeUri(MessageParcel &data, MessageParcel &rep } return DATA_SHARE_NO_ERROR; } - -int DataShareStub::AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) -{ - return -1; -} - -int DataShareStub::DelQueryTemplate(const std::string &uri, int64_t subscriberId) -{ - return -1; -} - -std::vector DataShareStub::Publish(const Data &data, const std::string &bundleName) -{ - return {}; -} - -Data DataShareStub::GetPublishedData(const std::string &bundleName) -{ - return {}; -} - -std::vector DataShareStub::SubscribeRdbData(const std::vector &uris, - const TemplateId &templateId, const sptr &observer) -{ - return {}; -} - -std::vector DataShareStub::UnSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) -{ - return {}; -} - -std::vector DataShareStub::EnableSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) -{ - return {}; -} - -std::vector DataShareStub::DisableSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) -{ - return {}; -} - -std::vector DataShareStub::SubscribePublishedData(const std::vector &uris, - int64_t subscriberId, const sptr &observer) -{ - return {}; -} - -std::vector DataShareStub::UnSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) -{ - return {}; -} - -std::vector DataShareStub::EnableSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) -{ - return {}; -} - -std::vector DataShareStub::DisableSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) -{ - return {}; -} } // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/provider/src/datashare_stub_impl.cpp b/data_share/frameworks/native/provider/src/datashare_stub_impl.cpp index 35da5630..811ce0ba 100644 --- a/data_share/frameworks/native/provider/src/datashare_stub_impl.cpp +++ b/data_share/frameworks/native/provider/src/datashare_stub_impl.cpp @@ -384,74 +384,5 @@ void DataShareStubImpl::GetCallingInfo(CallingInfo& callingInfo) callingInfo.callingPid = GetCallingPid(); callingInfo.callingUid = GetCallingUid(); } - -int DataShareStubImpl::AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) -{ - return 0; -} - -int DataShareStubImpl::DelQueryTemplate(const std::string &uri, int64_t subscriberId) -{ - return 0; -} - -std::vector DataShareStubImpl::Publish( - const Data &data, const std::string &bundleName) -{ - return std::vector(); -} - -Data DataShareStubImpl::GetPublishedData(const std::string &bundleName) -{ - return Data(); -} - -std::vector DataShareStubImpl::SubscribeRdbData( - const std::vector &uris, const TemplateId &templateId, const sptr &observer) -{ - return std::vector(); -} - -std::vector DataShareStubImpl::UnSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) -{ - return std::vector(); -} - -std::vector DataShareStubImpl::EnableSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) -{ - return std::vector(); -} - -std::vector DataShareStubImpl::DisableSubscribeRdbData( - const std::vector &uris, const TemplateId &templateId) -{ - return std::vector(); -} - -std::vector DataShareStubImpl::SubscribePublishedData( - const std::vector &uris, int64_t subscriberId, const sptr &observer) -{ - return std::vector(); -} - -std::vector DataShareStubImpl::UnSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) -{ - return std::vector(); -} - -std::vector DataShareStubImpl::EnableSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) -{ - return std::vector(); -} - -std::vector DataShareStubImpl::DisableSubscribePublishedData( - const std::vector &uris, int64_t subscriberId) -{ - return std::vector(); -} } // namespace DataShare } // namespace OHOS \ No newline at end of file diff --git a/data_share/frameworks/native/provider/src/js_datashare_ext_ability.cpp b/data_share/frameworks/native/provider/src/js_datashare_ext_ability.cpp index dfbe00de..7e95f706 100644 --- a/data_share/frameworks/native/provider/src/js_datashare_ext_ability.cpp +++ b/data_share/frameworks/native/provider/src/js_datashare_ext_ability.cpp @@ -17,19 +17,20 @@ #include "ability_info.h" #include "dataobs_mgr_client.h" -#include "datashare_stub_impl.h" #include "datashare_log.h" +#include "datashare_predicates_proxy.h" +#include "datashare_stub_impl.h" +#include "ikvstore_data_service.h" +#include "idata_share_service.h" +#include "iservice_registry.h" #include "js_datashare_ext_ability_context.h" #include "js_runtime.h" #include "js_runtime_utils.h" -#include "napi/native_api.h" -#include "napi/native_node_api.h" #include "napi_common_util.h" #include "napi_common_want.h" -#include "napi_remote_object.h" - #include "napi_datashare_values_bucket.h" -#include "datashare_predicates_proxy.h" +#include "napi_remote_object.h" +#include "system_ability_definition.h" namespace OHOS { namespace DataShare { @@ -129,7 +130,9 @@ void JsDataShareExtAbility::OnStart(const AAFwk::Want &want) napi_value napiWant = OHOS::AppExecFwk::WrapWant(env, want); NativeValue* nativeWant = reinterpret_cast(napiWant); NativeValue* argv[] = {nativeWant}; - CallObjectMethod("onCreate", argv, sizeof(argv)/sizeof(argv[0])); + std::shared_ptr context = std::make_shared(); + context->isNeedNotify_ = true; + CallObjectMethod("onCreate", argv, sizeof(argv)/sizeof(argv[0]), context); napi_close_handle_scope(env, scope); } @@ -214,6 +217,76 @@ NativeValue* JsDataShareExtAbility::AsyncCallback(NativeEngine* engine, NativeCa return engine->CreateUndefined(); } +NativeValue* JsDataShareExtAbility::AsyncCallbackWithContext(NativeEngine* engine, NativeCallbackInfo* info) +{ + if (engine == nullptr || info == nullptr) { + LOG_ERROR("invalid param."); + return nullptr; + } + if (info->functionInfo == nullptr || info->functionInfo->data == nullptr) { + LOG_ERROR("invalid object."); + return engine->CreateUndefined(); + } + + AsyncPoint* instance = static_cast(info->functionInfo->data); + if (instance != nullptr) { + if (instance->context->isNeedNotify_) { + NotifyToDataShareService(); + } + } + delete instance; + return engine->CreateUndefined(); +} + +NativeValue *JsDataShareExtAbility::CallObjectMethod( + const char *name, NativeValue *argv[], size_t argc, std::shared_ptr asyncContext) +{ + if (!jsObj_) { + LOG_WARN("Not found DataShareExtAbility.js"); + return nullptr; + } + + HandleEscape handleEscape(jsRuntime_); + auto &nativeEngine = jsRuntime_.GetNativeEngine(); + + NativeValue *value = jsObj_->Get(); + NativeObject *obj = ConvertNativeValueTo(value); + if (obj == nullptr) { + LOG_ERROR("Failed to get DataShareExtAbility object"); + return nullptr; + } + + NativeValue *method = obj->GetProperty(name); + if (method == nullptr) { + LOG_ERROR("Failed to get '%{public}s' from DataShareExtAbility object", name); + return nullptr; + } + + AsyncPoint *point = new (std::nothrow)AsyncPoint(); + if (point == nullptr) { + LOG_ERROR("JsDataShareExtAbility::CallObjectMethod new AsyncPoint error."); + return nullptr; + } + point->context = asyncContext; + size_t count = argc + 1; + NativeValue **args = new (std::nothrow) NativeValue *[count]; + if (args == nullptr) { + LOG_ERROR("JsDataShareExtAbility::CallObjectMethod new NativeValue error."); + delete point; + return nullptr; + } + for (size_t i = 0; i < argc; i++) { + args[i] = argv[i]; + } + + args[argc] = nativeEngine.CreateFunction(ASYNC_CALLBACK_NAME.c_str(), ASYNC_CALLBACK_NAME.length(), + JsDataShareExtAbility::AsyncCallbackWithContext, point); + + auto result = handleEscape.Escape(nativeEngine.CallFunction(value, method, args, count)); + delete[] args; + return result; +} + NativeValue* JsDataShareExtAbility::CallObjectMethod(const char* name, NativeValue* const* argv, size_t argc, bool isAsync) { @@ -780,6 +853,38 @@ napi_valuetype JsDataShareExtAbility::UnWrapPropertyType(napi_env env, napi_valu return type; } +void JsDataShareExtAbility::NotifyToDataShareService() +{ + auto manager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (manager == nullptr) { + LOG_ERROR("get system ability manager failed"); + return; + } + auto remoteObject = manager->CheckSystemAbility(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); + if (remoteObject == nullptr) { + LOG_ERROR("CheckSystemAbility failed"); + return; + } + auto serviceProxy = std::make_shared(remoteObject); + if (serviceProxy == nullptr) { + LOG_ERROR("make_shared failed"); + return; + } + auto remote = serviceProxy->GetFeatureInterface("data_share"); + if (remote == nullptr) { + LOG_ERROR("Get DataShare service failed!"); + return; + } + MessageParcel data; + MessageParcel reply; + MessageOption option(MessageOption::TF_ASYNC); + if (!data.WriteInterfaceToken(IDataShareService::GetDescriptor())) { + LOG_ERROR("Write descriptor failed!"); + return; + } + remote->SendRequest(IDataShareService::DATA_SHARE_SERVICE_CMD_NOTIFY, data, reply, option); +} + bool MakeNapiColumn(napi_env env, napi_value &napiColumns, const std::vector &columns) { napi_status status = napi_create_array(env, &napiColumns); diff --git a/data_share/frameworks/native/proxy/include/data_share_manager_impl.h b/data_share/frameworks/native/proxy/include/data_share_manager_impl.h index 6a1d3536..6605e9c3 100644 --- a/data_share/frameworks/native/proxy/include/data_share_manager_impl.h +++ b/data_share/frameworks/native/proxy/include/data_share_manager_impl.h @@ -22,26 +22,32 @@ #include "data_share_service_proxy.h" #include "data_share_errno.h" -#include "idata_share_service.h" #include "iremote_object.h" #include "refbase.h" -#include "base_connection.h" -namespace OHOS::DataShare { +namespace OHOS { +class ExecutorPool; +namespace DataShare { class DataShareKvServiceProxy; -class DataShareManagerImpl : public BaseConnection { +class DataShareManagerImpl { public: - std::shared_ptr GetDataShareService(); + static DataShareManagerImpl& GetInstance(); - DataShareManagerImpl(); virtual ~DataShareManagerImpl(); + + std::shared_ptr GetServiceProxy(); + void OnRemoteDied(); - std::shared_ptr GetDataShareProxy() override; - bool ConnectDataShare(const Uri &uri, const sptr &token) override; + + void SetDeathCallback(std::function)> deathCallback); + + void SetBundleName(const std::string &bundleName); class ServiceDeathRecipient : public IRemoteObject::DeathRecipient { public: - explicit ServiceDeathRecipient(DataShareManagerImpl *owner) : owner_(owner) {} + explicit ServiceDeathRecipient(DataShareManagerImpl *owner) : owner_(owner) + { + } void OnRemoteDied(const wptr &object) override { if (owner_ != nullptr) { @@ -54,6 +60,8 @@ public: }; private: + DataShareManagerImpl(); + void LinkToDeath(const sptr remote); sptr GetDataShareServiceProxy(); @@ -69,13 +77,11 @@ private: static constexpr int GET_SA_RETRY_TIMES = 3; static constexpr int RETRY_INTERVAL = 1; static constexpr int WAIT_TIME = 2; + static constexpr int MAX_THREADS = 2; + static constexpr int MIN_THREADS = 0; + std::shared_ptr pool_; + std::function)> deathCallback_ = {}; }; - -class DataShareKvServiceProxy : public IRemoteProxy { -public: - explicit DataShareKvServiceProxy(const sptr &impl); - ~DataShareKvServiceProxy() = default; - sptr GetFeatureInterface(const std::string &name) override; -}; +} } // namespace OHOS::DataShare #endif diff --git a/data_share/frameworks/native/proxy/include/data_share_service_proxy.h b/data_share/frameworks/native/proxy/include/data_share_service_proxy.h index 6d03833d..41340503 100644 --- a/data_share/frameworks/native/proxy/include/data_share_service_proxy.h +++ b/data_share/frameworks/native/proxy/include/data_share_service_proxy.h @@ -20,53 +20,29 @@ #include #include -#include "data_proxy_observer.h" -#include "datashare_business_error.h" -#include "datashare_values_bucket.h" #include "idata_share_service.h" -#include "uri.h" namespace OHOS::DataShare { -class DataShareServiceProxy : public IRemoteProxy, public BaseProxy { +class DataShareServiceProxy final : public IRemoteProxy { public: explicit DataShareServiceProxy(const sptr &object); - virtual int Insert(const Uri &uri, const DataShareValuesBucket &valuesBucket) override; + int Insert(const Uri &uri, const DataShareValuesBucket &valuesBucket) override; - virtual int Update(const Uri &uri, const DataSharePredicates &predicate, + int Update(const Uri &uri, const DataSharePredicates &predicate, const DataShareValuesBucket &valuesBucket) override; - virtual int Delete(const Uri &uri, const DataSharePredicates &predicate) override; + int Delete(const Uri &uri, const DataSharePredicates &predicate) override; - virtual std::shared_ptr Query(const Uri &uri, const DataSharePredicates &predicates, + std::shared_ptr Query(const Uri &uri, const DataSharePredicates &predicates, std::vector &columns, DatashareBusinessError &businessError) override; - virtual std::vector GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) override; - - virtual int OpenFile(const Uri &uri, const std::string &mode) override; - - virtual int OpenRawFile(const Uri &uri, const std::string &mode) override; - - virtual std::string GetType(const Uri &uri) override; - - virtual int BatchInsert(const Uri &uri, const std::vector &values) override; - - virtual bool RegisterObserver(const Uri &uri, const sptr &dataObserver) override; - - virtual bool UnregisterObserver(const Uri &uri, const sptr &dataObserver) override; - - virtual bool NotifyChange(const Uri &uri) override; - - virtual Uri NormalizeUri(const Uri &uri) override; - - virtual Uri DenormalizeUri(const Uri &uri) override; - int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) override; int DelQueryTemplate(const std::string &uri, int64_t subscriberId) override; std::vector Publish(const Data &data, const std::string &bundleName) override; - Data GetPublishedData(const std::string &bundleName) override; + Data GetPublishedData(const std::string &bundleName, int &resultCode) override; std::vector SubscribeRdbData(const std::vector &uris, const TemplateId &templateId, const sptr &observer) override; diff --git a/data_share/frameworks/native/proxy/include/published_data_subscriber_manager.h b/data_share/frameworks/native/proxy/include/published_data_subscriber_manager.h index d9ff5a54..d24f11f7 100644 --- a/data_share/frameworks/native/proxy/include/published_data_subscriber_manager.h +++ b/data_share/frameworks/native/proxy/include/published_data_subscriber_manager.h @@ -23,17 +23,26 @@ #include "datashare_template.h" #include "idatashare.h" #include "iremote_stub.h" +#include "data_share_service_proxy.h" namespace OHOS { namespace DataShare { struct PublishedObserverMapKey { std::string uri_; + std::string clearUri_; int64_t subscriberId_; - PublishedObserverMapKey(const std::string &uri, int64_t subscriberId) - : uri_(uri), subscriberId_(subscriberId){}; + PublishedObserverMapKey(const std::string &uri, int64_t subscriberId) : uri_(uri), subscriberId_(subscriberId) + { + auto pos = uri_.find_first_of('?'); + if (pos != std::string::npos) { + clearUri_ = uri_.substr(0, pos); + } else { + clearUri_ = uri_; + } + }; bool operator==(const PublishedObserverMapKey &node) const { - return uri_ == node.uri_ && subscriberId_ == node.subscriberId_; + return clearUri_ == node.clearUri_ && subscriberId_ == node.subscriberId_; } bool operator!=(const PublishedObserverMapKey &node) const { @@ -41,12 +50,12 @@ struct PublishedObserverMapKey { } bool operator<(const PublishedObserverMapKey &node) const { - if (uri_ != node.uri_) { - return uri_ < node.uri_; + if (clearUri_ != node.clearUri_) { + return clearUri_ < node.clearUri_; } return subscriberId_ < node.subscriberId_; } - operator std::string () const + operator std::string() const { return uri_; } @@ -63,23 +72,27 @@ private: PublishedDataCallback callback_; }; -class PublishedDataSubscriberManager : public CallbacksManager { +class PublishedDataSubscriberManager : public CallbacksManager { public: using Key = PublishedObserverMapKey; using Observer = PublishedDataObserver; using BaseCallbacks = CallbacksManager; - PublishedDataSubscriberManager(); - std::vector AddObservers(std::shared_ptr proxy, + static PublishedDataSubscriberManager &GetInstance(); + + std::vector AddObservers(void *subscriber, std::shared_ptr proxy, const std::vector &uris, int64_t subscriberId, const PublishedDataCallback &callback); - std::vector DelObservers(std::shared_ptr proxy, const std::vector &uris, - int64_t subscriberId); - std::vector EnableObservers(std::shared_ptr proxy, + std::vector DelObservers(void *subscriber, std::shared_ptr proxy, + const std::vector &uris, int64_t subscriberId); + std::vector DelObservers(void *subscriber, std::shared_ptr proxy); + std::vector EnableObservers(void *subscriber, std::shared_ptr proxy, const std::vector &uris, int64_t subscriberId); - std::vector DisableObservers(std::shared_ptr proxy, + std::vector DisableObservers(void *subscriber, std::shared_ptr proxy, const std::vector &uris, int64_t subscriberId); + void RecoverObservers(std::shared_ptr proxy); void Emit(PublishedDataChangeNode &changeNode); private: + PublishedDataSubscriberManager(); bool Init(); void Destroy(); sptr serviceCallback_; diff --git a/data_share/frameworks/native/proxy/include/rdb_subscriber_manager.h b/data_share/frameworks/native/proxy/include/rdb_subscriber_manager.h index 21c6d765..47462d09 100644 --- a/data_share/frameworks/native/proxy/include/rdb_subscriber_manager.h +++ b/data_share/frameworks/native/proxy/include/rdb_subscriber_manager.h @@ -24,16 +24,26 @@ #include "datashare_template.h" #include "idatashare.h" #include "iremote_stub.h" +#include "data_share_service_proxy.h" namespace OHOS { namespace DataShare { struct RdbObserverMapKey { std::string uri_; + std::string clearUri_; TemplateId templateId_; - RdbObserverMapKey(const std::string &uri, const TemplateId &templateId) : uri_(uri), templateId_(templateId){}; + RdbObserverMapKey(const std::string &uri, const TemplateId &templateId) : uri_(uri), templateId_(templateId) + { + auto pos = uri_.find_first_of('?'); + if (pos != std::string::npos) { + clearUri_ = uri_.substr(0, pos); + } else { + clearUri_ = uri_; + } + } bool operator==(const RdbObserverMapKey &node) const { - return uri_ == node.uri_ && templateId_ == node.templateId_; + return clearUri_ == node.clearUri_ && templateId_ == node.templateId_; } bool operator!=(const RdbObserverMapKey &node) const { @@ -41,12 +51,12 @@ struct RdbObserverMapKey { } bool operator<(const RdbObserverMapKey &node) const { - if (uri_ != node.uri_) { - return uri_ < node.uri_; + if (clearUri_ != node.clearUri_) { + return clearUri_ < node.clearUri_; } return templateId_ < node.templateId_; } - operator std::string () const + operator std::string() const { return uri_; } @@ -68,18 +78,22 @@ public: using Key = RdbObserverMapKey; using Observer = RdbObserver; using BaseCallbacks = CallbacksManager; - RdbSubscriberManager(); - std::vector AddObservers(std::shared_ptr proxy, const std::vector &uris, - const TemplateId &templateId, const RdbCallback &callback); - std::vector DelObservers(std::shared_ptr proxy, const std::vector &uris, - const TemplateId &templateId); - std::vector EnableObservers(std::shared_ptr proxy, + static RdbSubscriberManager &GetInstance(); + + std::vector AddObservers(void *subscriber, std::shared_ptr proxy, + const std::vector &uris, const TemplateId &templateId, const RdbCallback &callback); + std::vector DelObservers(void *subscriber, std::shared_ptr proxy, + const std::vector &uris, const TemplateId &templateId); + std::vector DelObservers(void *subscriber, std::shared_ptr proxy); + std::vector EnableObservers(void *subscriber, std::shared_ptr proxy, const std::vector &uris, const TemplateId &templateId); - std::vector DisableObservers(std::shared_ptr proxy, + std::vector DisableObservers(void *subscriber, std::shared_ptr proxy, const std::vector &uris, const TemplateId &templateId); + void RecoverObservers(std::shared_ptr proxy); void Emit(const RdbChangeNode &changeNode); private: + RdbSubscriberManager(); bool Init(); void Destroy(); sptr serviceCallback_; diff --git a/data_share/frameworks/native/proxy/src/data_share_manager_impl.cpp b/data_share/frameworks/native/proxy/src/data_share_manager_impl.cpp index d545fd29..88110b64 100644 --- a/data_share/frameworks/native/proxy/src/data_share_manager_impl.cpp +++ b/data_share/frameworks/native/proxy/src/data_share_manager_impl.cpp @@ -17,15 +17,23 @@ #include -#include "data_share_service_proxy.h" #include "datashare_log.h" -#include "idata_share_service.h" +#include "ikvstore_data_service.h" #include "ipc_skeleton.h" #include "iservice_registry.h" #include "system_ability_definition.h" +#include "executor_pool.h" +#include "rdb_subscriber_manager.h" +#include "published_data_subscriber_manager.h" namespace OHOS { namespace DataShare { +DataShareManagerImpl& DataShareManagerImpl::GetInstance() +{ + static DataShareManagerImpl manager; + return manager; +} + std::shared_ptr DataShareManagerImpl::GetDistributedDataManager() { int retry = 0; @@ -80,26 +88,15 @@ sptr DataShareManagerImpl::GetDataShareServiceProxy() return iface_cast(remote); } -std::shared_ptr DataShareManagerImpl::GetDataShareService() -{ - std::lock_guard lock(mutex_); - if (dataShareService_ != nullptr) { - return dataShareService_; - } - auto service = GetDataShareServiceProxy(); - if (service == nullptr) { - return nullptr; - } - sptr serviceBase = service; - LinkToDeath(serviceBase->AsObject().GetRefPtr()); - dataShareService_ = - std::shared_ptr(service.GetRefPtr(), [holder = service](const auto *) {}); - return dataShareService_; -} - -DataShareManagerImpl::DataShareManagerImpl() : BaseConnection(ConnectionType::SILENCE) +DataShareManagerImpl::DataShareManagerImpl() { LOG_INFO("construct"); + pool_ = std::make_shared(MAX_THREADS, MIN_THREADS); + SetDeathCallback([](std::shared_ptr proxy) { + LOG_INFO("RecoverObs start"); + RdbSubscriberManager::GetInstance().RecoverObservers(proxy); + PublishedDataSubscriberManager::GetInstance().RecoverObservers(proxy); + }); } DataShareManagerImpl::~DataShareManagerImpl() @@ -107,26 +104,25 @@ DataShareManagerImpl::~DataShareManagerImpl() LOG_INFO("destroy"); } -bool DataShareManagerImpl::ConnectDataShare(const Uri &uri, const sptr &token) +std::shared_ptr DataShareManagerImpl::GetServiceProxy() { if (dataShareService_ != nullptr) { - return true; + return dataShareService_; } std::lock_guard lock(mutex_); + if (dataShareService_ != nullptr) { + return dataShareService_; + } + auto service = GetDataShareServiceProxy(); if (service == nullptr) { - return false; + return nullptr; } sptr serviceBase = service; LinkToDeath(serviceBase->AsObject().GetRefPtr()); dataShareService_ = std::shared_ptr( service.GetRefPtr(), [holder = service](const auto *) {}); - return true; -} - -std::shared_ptr DataShareManagerImpl::GetDataShareProxy() -{ return dataShareService_; } @@ -138,44 +134,30 @@ void DataShareManagerImpl::ResetServiceHandle() dataShareService_ = nullptr; } -void DataShareManagerImpl::OnRemoteDied() +void DataShareManagerImpl::SetDeathCallback(std::function)> deathCallback) { - LOG_INFO("#######datashare service has dead"); - ResetServiceHandle(); + deathCallback_ = deathCallback; } -DataShareKvServiceProxy::DataShareKvServiceProxy(const sptr &impl) - : IRemoteProxy(impl) +void DataShareManagerImpl::SetBundleName(const std::string &bundleName) { - LOG_DEBUG("Init data service proxy."); + bundleName_ = bundleName; } -sptr DataShareKvServiceProxy::GetFeatureInterface(const std::string &name) +void DataShareManagerImpl::OnRemoteDied() { - LOG_INFO("GetDataShareService enter."); - MessageParcel data; - if (!data.WriteInterfaceToken(DataShareKvServiceProxy::GetDescriptor())) { - LOG_ERROR("Write descriptor failed"); - return nullptr; - } - if (!data.WriteString(name)) { - LOG_ERROR("Write name failed"); - return nullptr; - } - - MessageParcel reply; - MessageOption mo { MessageOption::TF_SYNC }; - int32_t error = Remote()->SendRequest(GET_FEATURE_INTERFACE, data, reply, mo); - if (error != 0) { - LOG_ERROR("SendRequest returned %{public}d", error); - return nullptr; - } - auto remoteObject = reply.ReadRemoteObject(); - if (remoteObject == nullptr) { - LOG_ERROR("Remote object is nullptr!"); - return nullptr; + LOG_INFO("#######datashare service has dead"); + ResetServiceHandle(); + auto taskid = pool_->Schedule(std::chrono::seconds(WAIT_TIME), [this]() { + if (GetServiceProxy() != nullptr) { + deathCallback_(dataShareService_); + } + }); + if (taskid == ExecutorPool::INVALID_TASK_ID) { + LOG_ERROR("create scheduler failed, over the max capacity"); + return; } - return remoteObject; + LOG_DEBUG("create scheduler success"); } } } \ No newline at end of file diff --git a/data_share/frameworks/native/proxy/src/data_share_service_proxy.cpp b/data_share/frameworks/native/proxy/src/data_share_service_proxy.cpp index f1334a1c..2f874640 100644 --- a/data_share/frameworks/native/proxy/src/data_share_service_proxy.cpp +++ b/data_share/frameworks/native/proxy/src/data_share_service_proxy.cpp @@ -125,56 +125,6 @@ std::shared_ptr DataShareServiceProxy::Query(const Uri &uri, return result; } -int DataShareServiceProxy::OpenFile(const Uri &uri, const std::string &mode) -{ - return 0; -} - -std::vector DataShareServiceProxy::GetFileTypes(const Uri &uri, const std::string &mimeTypeFilter) -{ - return std::vector(); -} - -int DataShareServiceProxy::OpenRawFile(const Uri &uri, const std::string &mode) -{ - return 0; -} - -std::string DataShareServiceProxy::GetType(const Uri &uri) -{ - return std::string(); -} - -int DataShareServiceProxy::BatchInsert(const Uri &uri, const std::vector &values) -{ - return 0; -} - -bool DataShareServiceProxy::RegisterObserver(const Uri &uri, const sptr &dataObserver) -{ - return false; -} - -bool DataShareServiceProxy::UnregisterObserver(const Uri &uri, const sptr &dataObserver) -{ - return false; -} - -bool DataShareServiceProxy::NotifyChange(const Uri &uri) -{ - return false; -} - -Uri DataShareServiceProxy::NormalizeUri(const Uri &uri) -{ - return Uri(""); -} - -Uri DataShareServiceProxy::DenormalizeUri(const Uri &uri) -{ - return Uri(""); -} - int DataShareServiceProxy::AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) { MessageParcel data; @@ -244,7 +194,7 @@ std::vector DataShareServiceProxy::Publish(const Data &data, co return results; } -Data DataShareServiceProxy::GetPublishedData(const std::string &bundleName) +Data DataShareServiceProxy::GetPublishedData(const std::string &bundleName, int &resultCode) { Data results; MessageParcel data; @@ -264,7 +214,7 @@ Data DataShareServiceProxy::GetPublishedData(const std::string &bundleName) LOG_ERROR("AddTemplate fail to SendRequest, err: %{public}d", err); return results; } - ITypesUtil::Unmarshal(reply, results.datas_); + ITypesUtil::Unmarshal(reply, results.datas_, resultCode); return results; } diff --git a/data_share/frameworks/native/proxy/src/published_data_subscriber_manager.cpp b/data_share/frameworks/native/proxy/src/published_data_subscriber_manager.cpp index 19f10b08..59f75d18 100644 --- a/data_share/frameworks/native/proxy/src/published_data_subscriber_manager.cpp +++ b/data_share/frameworks/native/proxy/src/published_data_subscriber_manager.cpp @@ -20,8 +20,9 @@ namespace OHOS { namespace DataShare { -std::vector PublishedDataSubscriberManager::AddObservers(std::shared_ptr proxy, - const std::vector &uris, int64_t subscriberId, const PublishedDataCallback &callback) +std::vector PublishedDataSubscriberManager::AddObservers(void *subscriber, + std::shared_ptr proxy, const std::vector &uris, int64_t subscriberId, + const PublishedDataCallback &callback) { if (proxy == nullptr) { LOG_ERROR("proxy is nullptr"); @@ -31,9 +32,9 @@ std::vector PublishedDataSubscriberManager::AddObservers(std::s std::for_each(uris.begin(), uris.end(), [&keys, &subscriberId](auto &uri) { keys.emplace_back(uri, subscriberId); }); - return BaseCallbacks::AddObservers(keys, std::make_shared(callback), - [&proxy, &subscriberId, this](const std::vector &firstAddKeys, const std::shared_ptr observer, - std::vector &opResult) { + return BaseCallbacks::AddObservers(keys, subscriber, std::make_shared(callback), + [&proxy, subscriber, &subscriberId, this](const std::vector &firstAddKeys, + const std::shared_ptr observer, std::vector &opResult) { std::vector firstAddUris; std::for_each(firstAddKeys.begin(), firstAddKeys.end(), [&firstAddUris](auto &result) { firstAddUris.emplace_back(result); @@ -53,34 +54,51 @@ std::vector PublishedDataSubscriberManager::AddObservers(std::s } } if (failedKeys.size() > 0) { - BaseCallbacks::DelObservers(failedKeys, observer); + BaseCallbacks::DelObservers(failedKeys, subscriber); } Destroy(); }); } -std::vector PublishedDataSubscriberManager::DelObservers(std::shared_ptr proxy, - const std::vector &uris, int64_t subscriberId) +std::vector PublishedDataSubscriberManager::DelObservers(void *subscriber, + std::shared_ptr proxy) { if (proxy == nullptr) { LOG_ERROR("proxy is nullptr"); return std::vector(); } + return BaseCallbacks::DelObservers(subscriber, + [&proxy, this](const std::vector &lastDelKeys, std::vector &opResult) { + // delete all obs by subscriber + std::map> keysMap; + for (auto const &key : lastDelKeys) { + keysMap[key.subscriberId_].emplace_back(key.uri_); + } + for (auto const &[subscriberId, uris] : keysMap) { + auto results = proxy->UnSubscribePublishedData(uris, subscriberId); + opResult.insert(opResult.end(), results.begin(), results.end()); + } + Destroy(); + }); +} + +std::vector PublishedDataSubscriberManager::DelObservers(void *subscriber, + std::shared_ptr proxy, const std::vector &uris, int64_t subscriberId) +{ + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + if (uris.empty()) { + return DelObservers(subscriber, proxy); + } + std::vector keys; std::for_each(uris.begin(), uris.end(), [&keys, &subscriberId](auto &uri) { keys.emplace_back(uri, subscriberId); }); - return BaseCallbacks::DelObservers(keys, nullptr, - [&proxy, &subscriberId, &uris, this](const std::vector &lastDelKeys, - const std::shared_ptr &observer, std::vector &opResult) { - // delete all obs - if (uris.empty()) { - for (const auto &key : lastDelKeys) { - proxy->UnSubscribePublishedData(std::vector(1, key.uri_), key.subscriberId_); - } - Destroy(); - return; - } + return BaseCallbacks::DelObservers(keys, subscriber, + [&proxy, &subscriberId, this](const std::vector &lastDelKeys, std::vector &opResult) { std::vector lastDelUris; std::for_each(lastDelKeys.begin(), lastDelKeys.end(), [&lastDelUris](auto &result) { lastDelUris.emplace_back(result); @@ -98,8 +116,8 @@ std::vector PublishedDataSubscriberManager::DelObservers(std::s }); } -std::vector PublishedDataSubscriberManager::EnableObservers(std::shared_ptr proxy, - const std::vector &uris, int64_t subscriberId) +std::vector PublishedDataSubscriberManager::EnableObservers(void *subscriber, + std::shared_ptr proxy, const std::vector &uris, int64_t subscriberId) { if (proxy == nullptr) { LOG_ERROR("proxy is nullptr"); @@ -109,8 +127,9 @@ std::vector PublishedDataSubscriberManager::EnableObservers(std std::for_each(uris.begin(), uris.end(), [&keys, &subscriberId](auto &uri) { keys.emplace_back(uri, subscriberId); }); - return BaseCallbacks::EnableObservers(keys, - [&proxy, &subscriberId, this](const std::vector &firstAddKeys, std::vector &opResult) { + return BaseCallbacks::EnableObservers(keys, subscriber, + [&proxy, &subscriberId, subscriber, this](const std::vector &firstAddKeys, + std::vector &opResult) { std::vector firstAddUris; std::for_each(firstAddKeys.begin(), firstAddKeys.end(), [&firstAddUris](auto &result) { firstAddUris.emplace_back(result); @@ -128,13 +147,13 @@ std::vector PublishedDataSubscriberManager::EnableObservers(std } } if (failedKeys.size() > 0) { - BaseCallbacks::DisableObservers(failedKeys); + BaseCallbacks::DisableObservers(failedKeys, subscriber); } }); } -std::vector PublishedDataSubscriberManager::DisableObservers(std::shared_ptr proxy, - const std::vector &uris, int64_t subscriberId) +std::vector PublishedDataSubscriberManager::DisableObservers(void *subscriber, + std::shared_ptr proxy, const std::vector &uris, int64_t subscriberId) { if (proxy == nullptr) { LOG_ERROR("proxy is nullptr"); @@ -144,9 +163,9 @@ std::vector PublishedDataSubscriberManager::DisableObservers(st std::for_each(uris.begin(), uris.end(), [&keys, &subscriberId](auto &uri) { keys.emplace_back(uri, subscriberId); }); - return BaseCallbacks::DisableObservers(keys, + return BaseCallbacks::DisableObservers(keys, subscriber, [&proxy, &subscriberId, this](const std::vector &lastDisabledKeys, - std::vector &opResult) { + std::vector &opResult) { std::vector lastDisabledUris; std::for_each(lastDisabledKeys.begin(), lastDisabledKeys.end(), [&lastDisabledUris](auto &result) { lastDisabledUris.emplace_back(result); @@ -157,10 +176,32 @@ std::vector PublishedDataSubscriberManager::DisableObservers(st auto results = proxy->DisableSubscribePublishedData(lastDisabledUris, subscriberId); opResult.insert(opResult.end(), results.begin(), results.end()); - Destroy(); }); } +void PublishedDataSubscriberManager::RecoverObservers(std::shared_ptr proxy) +{ + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return; + } + return BaseCallbacks::RecoverObservers([&proxy, this](const std::vector &Keys) { + std::map> keysMap; + for (auto const &key : Keys) { + keysMap[key.subscriberId_].emplace_back(key.uri_); + } + for (auto const &[subscriberId, uris] : keysMap) { + auto results = proxy->SubscribePublishedData(uris, subscriberId, serviceCallback_); + for (const auto& result : results) { + if (result.errCode_ != E_OK) { + LOG_WARN("RecoverObservers failed, uri is %{public}s, errCode is %{public}d", + result.key_.c_str(), result.errCode_); + } + } + } + }); +} + void PublishedDataSubscriberManager::Emit(PublishedDataChangeNode &changeNode) { std::map, PublishedDataChangeNode> results; @@ -203,6 +244,12 @@ void PublishedDataSubscriberManager::Destroy() } } +PublishedDataSubscriberManager &PublishedDataSubscriberManager::GetInstance() +{ + static PublishedDataSubscriberManager manager; + return manager; +} + PublishedDataSubscriberManager::PublishedDataSubscriberManager() { serviceCallback_ = nullptr; diff --git a/data_share/frameworks/native/proxy/src/rdb_subscriber_manager.cpp b/data_share/frameworks/native/proxy/src/rdb_subscriber_manager.cpp index d88fee9e..6ffb4208 100644 --- a/data_share/frameworks/native/proxy/src/rdb_subscriber_manager.cpp +++ b/data_share/frameworks/native/proxy/src/rdb_subscriber_manager.cpp @@ -20,12 +20,19 @@ namespace OHOS { namespace DataShare { +RdbSubscriberManager &RdbSubscriberManager::GetInstance() +{ + static RdbSubscriberManager manager; + return manager; +} + RdbSubscriberManager::RdbSubscriberManager() { serviceCallback_ = nullptr; } -std::vector RdbSubscriberManager::AddObservers(std::shared_ptr proxy, +std::vector RdbSubscriberManager::AddObservers(void *subscriber, + std::shared_ptr proxy, const std::vector &uris, const TemplateId &templateId, const RdbCallback &callback) { if (proxy == nullptr) { @@ -36,8 +43,8 @@ std::vector RdbSubscriberManager::AddObservers(std::shared_ptr< std::for_each(uris.begin(), uris.end(), [&keys, &templateId](auto &uri) { keys.emplace_back(uri, templateId); }); - return BaseCallbacks::AddObservers(keys, std::make_shared(callback), - [&proxy, &templateId, this](const std::vector &firstAddKeys, + return BaseCallbacks::AddObservers(keys, subscriber, std::make_shared(callback), + [&proxy, subscriber, &templateId, this](const std::vector &firstAddKeys, const std::shared_ptr observer, std::vector &opResult) { std::vector firstAddUris; std::for_each(firstAddKeys.begin(), firstAddKeys.end(), [&firstAddUris](auto &result) { @@ -58,34 +65,29 @@ std::vector RdbSubscriberManager::AddObservers(std::shared_ptr< } } if (!failedKeys.empty()) { - BaseCallbacks::DelObservers(failedKeys, observer); + BaseCallbacks::DelObservers(failedKeys, subscriber); } Destroy(); }); } -std::vector RdbSubscriberManager::DelObservers(std::shared_ptr proxy, - const std::vector &uris, const TemplateId &templateId) +std::vector RdbSubscriberManager::DelObservers(void *subscriber, + std::shared_ptr proxy, const std::vector &uris, const TemplateId &templateId) { if (proxy == nullptr) { LOG_ERROR("proxy is nullptr"); return std::vector(); } + if (uris.empty()) { + return DelObservers(subscriber, proxy); + } + std::vector keys; std::for_each(uris.begin(), uris.end(), [&keys, &templateId](auto &uri) { keys.emplace_back(uri, templateId); }); - return BaseCallbacks::DelObservers(keys, nullptr, - [&proxy, &templateId, &uris, this](const std::vector &lastDelKeys, - const std::shared_ptr &observer, std::vector &opResult) { - // delete all obs - if (uris.empty()) { - for (const auto& key : lastDelKeys) { - proxy->UnSubscribeRdbData(std::vector(1, key.uri_), key.templateId_); - } - Destroy(); - return; - } + return BaseCallbacks::DelObservers(keys, subscriber, + [&proxy, &templateId, this](const std::vector &lastDelKeys, std::vector &opResult) { std::vector lastDelUris; std::for_each(lastDelKeys.begin(), lastDelKeys.end(), [&lastDelUris](auto &result) { lastDelUris.emplace_back(result); @@ -103,8 +105,26 @@ std::vector RdbSubscriberManager::DelObservers(std::shared_ptr< }); } -std::vector RdbSubscriberManager::EnableObservers(std::shared_ptr proxy, - const std::vector &uris, const TemplateId &templateId) +std::vector RdbSubscriberManager::DelObservers(void *subscriber, + std::shared_ptr proxy) +{ + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return std::vector(); + } + return BaseCallbacks::DelObservers(subscriber, + [&proxy, this](const std::vector &lastDelKeys, std::vector &opResult) { + // delete all obs by subscriber + for (const auto &key : lastDelKeys) { + auto unsubResult = proxy->UnSubscribeRdbData(std::vector(1, key.uri_), key.templateId_); + opResult.insert(opResult.end(), unsubResult.begin(), unsubResult.end()); + } + Destroy(); + }); +} + +std::vector RdbSubscriberManager::EnableObservers(void *subscriber, + std::shared_ptr proxy, const std::vector &uris, const TemplateId &templateId) { if (proxy == nullptr) { LOG_ERROR("proxy is nullptr"); @@ -114,8 +134,9 @@ std::vector RdbSubscriberManager::EnableObservers(std::shared_p std::for_each(uris.begin(), uris.end(), [&keys, &templateId](auto &uri) { keys.emplace_back(uri, templateId); }); - return BaseCallbacks::EnableObservers(keys, - [&proxy, &templateId, this](const std::vector &firstAddKeys, std::vector &opResult) { + return BaseCallbacks::EnableObservers(keys, subscriber, + [&proxy, subscriber, &templateId, this](const std::vector &firstAddKeys, + std::vector &opResult) { std::vector firstAddUris; std::for_each(firstAddKeys.begin(), firstAddKeys.end(), [&firstAddUris](auto &result) { firstAddUris.emplace_back(result); @@ -133,13 +154,13 @@ std::vector RdbSubscriberManager::EnableObservers(std::shared_p } } if (!failedKeys.empty()) { - BaseCallbacks::DisableObservers(failedKeys); + BaseCallbacks::DisableObservers(failedKeys, subscriber); } }); } -std::vector RdbSubscriberManager::DisableObservers(std::shared_ptr proxy, - const std::vector &uris, const TemplateId &templateId) +std::vector RdbSubscriberManager::DisableObservers(void *subscriber, + std::shared_ptr proxy, const std::vector &uris, const TemplateId &templateId) { if (proxy == nullptr) { LOG_ERROR("proxy is nullptr"); @@ -149,7 +170,7 @@ std::vector RdbSubscriberManager::DisableObservers(std::shared_ std::for_each(uris.begin(), uris.end(), [&keys, &templateId](auto &uri) { keys.emplace_back(uri, templateId); }); - return BaseCallbacks::DisableObservers(keys, + return BaseCallbacks::DisableObservers(keys, subscriber, [&proxy, &templateId, this](const std::vector &lastDisabledKeys, std::vector &opResult) { std::vector lastDisabledUris; std::for_each(lastDisabledKeys.begin(), lastDisabledKeys.end(), [&lastDisabledUris](auto &result) { @@ -165,6 +186,29 @@ std::vector RdbSubscriberManager::DisableObservers(std::shared_ }); } +void RdbSubscriberManager::RecoverObservers(std::shared_ptr proxy) +{ + if (proxy == nullptr) { + LOG_ERROR("proxy is nullptr"); + return; + } + return BaseCallbacks::RecoverObservers([&proxy, this](const std::vector &Keys) { + std::map> keysMap; + for (auto const &key : Keys) { + keysMap[key.templateId_].emplace_back(key.uri_); + } + for (auto const &[templateId, uris] : keysMap) { + auto results = proxy->SubscribeRdbData(uris, templateId, serviceCallback_); + for (const auto& result : results) { + if (result.errCode_ != E_OK) { + LOG_WARN("RecoverObservers failed, uri is %{public}s, errCode is %{public}d", + result.key_.c_str(), result.errCode_); + } + } + } + }); +} + void RdbSubscriberManager::Emit(const RdbChangeNode &changeNode) { RdbObserverMapKey key(changeNode.uri_, changeNode.templateId_); @@ -180,10 +224,13 @@ bool RdbSubscriberManager::Init() { if (serviceCallback_ == nullptr) { LOG_INFO("callback init"); - serviceCallback_ = new RdbObserverStub([this](const RdbChangeNode &changeNode) { Emit(changeNode); }); + serviceCallback_ = new RdbObserverStub([this](const RdbChangeNode &changeNode) { + Emit(changeNode); + }); } return true; } + void RdbSubscriberManager::Destroy() { if (BaseCallbacks::GetEnabledSubscriberSize() == 0) { diff --git a/data_share/interfaces/inner_api/BUILD.gn b/data_share/interfaces/inner_api/BUILD.gn index ca280e64..bb6d232c 100644 --- a/data_share/interfaces/inner_api/BUILD.gn +++ b/data_share/interfaces/inner_api/BUILD.gn @@ -42,6 +42,9 @@ config("datashare_public_config") { "provider/include", "${datashare_common_napi_path}/include", "${datashare_common_native_path}/include", + "${datashare_native_consumer_path}/controller/common", + "${datashare_native_consumer_path}/controller/provider/include", + "${datashare_native_consumer_path}/controller/service/include", "${datashare_native_consumer_path}/include", "${datashare_native_provider_path}/include", "${datashare_native_proxy_path}/include", @@ -53,9 +56,14 @@ ohos_shared_library("datashare_consumer") { [ "//foundation/distributeddatamgr/kv_store/frameworks/common" ] sources = [ - "${datashare_native_consumer_path}/src/connection_factory.cpp", + "${datashare_native_consumer_path}/controller/provider/src/ext_special_controller.cpp", + "${datashare_native_consumer_path}/controller/provider/src/general_controller_provider_impl.cpp", + "${datashare_native_consumer_path}/controller/service/src/general_controller_service_impl.cpp", + "${datashare_native_consumer_path}/controller/service/src/persistent_data_controller.cpp", + "${datashare_native_consumer_path}/controller/service/src/published_data_controller.cpp", "${datashare_native_consumer_path}/src/datashare_connection.cpp", "${datashare_native_consumer_path}/src/datashare_helper.cpp", + "${datashare_native_consumer_path}/src/datashare_helper_impl.cpp", "${datashare_native_consumer_path}/src/datashare_proxy.cpp", "${datashare_native_proxy_path}/src/data_proxy_observer_stub.cpp", "${datashare_native_proxy_path}/src/data_share_manager_impl.cpp", @@ -123,6 +131,7 @@ ohos_shared_library("datashare_provider") { "ipc:ipc_single", "ipc_js:rpc", "napi:ace_napi", + "samgr:samgr_proxy", ] subsystem_name = "distributeddatamgr" diff --git a/data_share/interfaces/inner_api/common/BUILD.gn b/data_share/interfaces/inner_api/common/BUILD.gn index 06abf4c7..14d97ae0 100644 --- a/data_share/interfaces/inner_api/common/BUILD.gn +++ b/data_share/interfaces/inner_api/common/BUILD.gn @@ -37,6 +37,7 @@ ohos_shared_library("datashare_common") { "${datashare_base_path}/interfaces/inner_api/common/include", "${datashare_base_path}/interfaces/inner_api/consumer/include", "${datashare_base_path}/interfaces/inner_api/provider/include", + "${datashare_native_proxy_path}/include", "//foundation/communication/ipc/ipc/native/src/napi_common/include", "//foundation/distributeddatamgr/kv_store/frameworks/common", ] @@ -51,13 +52,15 @@ ohos_shared_library("datashare_common") { "${datashare_common_native_path}/src/datashare_block_writer_impl.cpp", "${datashare_common_native_path}/src/datashare_itypes_utils.cpp", "${datashare_common_native_path}/src/datashare_result_set.cpp", + "${datashare_common_native_path}/src/datashare_template.cpp", + "${datashare_common_native_path}/src/ikvstore_data_service.cpp", "${datashare_common_native_path}/src/ishared_result_set.cpp", "${datashare_common_native_path}/src/ishared_result_set_proxy.cpp", "${datashare_common_native_path}/src/ishared_result_set_stub.cpp", "${datashare_common_native_path}/src/shared_block.cpp", ] - deps = [ "${ability_runtime_path}/frameworks/native/ability/native:abilitykit_native" ] + deps = [] public_deps = [] @@ -68,6 +71,7 @@ ohos_shared_library("datashare_common") { external_deps = [ "ability_base:zuri", + "ability_runtime:abilitykit_native", "c_utils:utils", "hisysevent_native:libhisysevent", "hitrace_native:hitrace_meter", diff --git a/data_share/interfaces/inner_api/common/include/datashare_errno.h b/data_share/interfaces/inner_api/common/include/datashare_errno.h index 950d24f8..e2e8c7f0 100644 --- a/data_share/interfaces/inner_api/common/include/datashare_errno.h +++ b/data_share/interfaces/inner_api/common/include/datashare_errno.h @@ -84,6 +84,11 @@ constexpr int E_SUBSCRIBER_NOT_EXIST = (E_BASE + 47); * @brief Cannot find the uri */ constexpr int E_URI_NOT_EXIST = (E_BASE + 48); + +/** +* @brief Cannot find the bundleName +*/ +constexpr int E_BUNDLE_NAME_NOT_EXIST = (E_BASE + 49); } // namespace DataShare } // namespace OHOS diff --git a/data_share/interfaces/inner_api/common/include/datashare_predicates_objects.h b/data_share/interfaces/inner_api/common/include/datashare_predicates_objects.h index 21d269d5..4335157d 100644 --- a/data_share/interfaces/inner_api/common/include/datashare_predicates_objects.h +++ b/data_share/interfaces/inner_api/common/include/datashare_predicates_objects.h @@ -48,7 +48,8 @@ public: /** * @brief Use Type replace variant namespace. */ - using Type = std::variant, std::vector, std::vector, std::vector>; + using Type = std::variant, std::vector, + std::vector, std::vector>; Type value; /** diff --git a/data_share/interfaces/inner_api/common/include/datashare_template.h b/data_share/interfaces/inner_api/common/include/datashare_template.h index d2b9ddbf..2e2643c3 100644 --- a/data_share/interfaces/inner_api/common/include/datashare_template.h +++ b/data_share/interfaces/inner_api/common/include/datashare_template.h @@ -19,7 +19,6 @@ #include #include #include -#include "hilog/log.h" #include "iremote_object.h" namespace OHOS { @@ -95,6 +94,7 @@ struct AshmemNode { * Specifies the published item structure. */ struct PublishedDataItem { + using DataType = std::variant, std::string>; /** The key of the published data. */ std::string key_; /** The subscriber id */ @@ -104,114 +104,20 @@ struct PublishedDataItem { PublishedDataItem(){}; PublishedDataItem(const PublishedDataItem &) = delete; PublishedDataItem &operator=(const PublishedDataItem &) = delete; - virtual ~PublishedDataItem() - { - if (value_.index() == 0) { - AshmemNode &node = std::get(value_); - if (node.isManaged && node.ashmem != nullptr) { - node.ashmem->UnmapAshmem(); - node.ashmem->CloseAshmem(); - } - } - } - PublishedDataItem( - const std::string &key, int64_t subscriberId, std::variant, std::string> value) - : key_(key), subscriberId_(subscriberId) - { - if (value.index() == 0) { - std::vector &vecValue = std::get>(value); - sptr mem = Ashmem::CreateAshmem((key_ + std::to_string(subscriberId_)).c_str(), vecValue.size()); - if (mem == nullptr) { - return; - } - if (!mem->MapReadAndWriteAshmem()) { - mem->CloseAshmem(); - return; - } - if (!mem->WriteToAshmem(vecValue.data(), vecValue.size(), 0)) { - mem->UnmapAshmem(); - mem->CloseAshmem(); - return; - } - AshmemNode node = { mem, true }; - value_ = std::move(node); - } else { - value_ = std::move(std::get(value)); - } - } - - PublishedDataItem(PublishedDataItem &&item) - { - key_ = std::move(item.key_); - subscriberId_ = std::move(item.subscriberId_); - value_ = std::move(item.value_); - if (item.IsAshmem()) { - item.MoveOutAshmem(); - } - } - - PublishedDataItem &operator=(PublishedDataItem &&item) - { - key_ = std::move(item.key_); - subscriberId_ = std::move(item.subscriberId_); - value_ = std::move(item.value_); - if (item.IsAshmem()) { - item.MoveOutAshmem(); - } - return *this; - } - - inline bool IsAshmem() const - { - return value_.index() == 0; - } - - inline bool IsString() const - { - return value_.index() == 1; - } - - sptr MoveOutAshmem() - { - if (IsAshmem()) { - AshmemNode &node = std::get(value_); - if (!node.isManaged) { - return nullptr; - } - node.isManaged = false; - return std::move(node.ashmem); - } - return nullptr; - } - - void SetAshmem(sptr ashmem, bool isManaged = false) - { - AshmemNode node = { ashmem, isManaged }; - value_ = std::move(node); - } - - void Set(const std::string &value) - { - value_ = value; - } - - std::variant, std::string> GetData() const - { - if (IsAshmem()) { - const AshmemNode &node = std::get(value_); - if (node.ashmem != nullptr) { - node.ashmem->MapReadOnlyAshmem(); - uint8_t *data = (uint8_t *)node.ashmem->ReadFromAshmem(node.ashmem->GetAshmemSize(), 0); - if (data == nullptr) { - return std::vector(); - } - return std::vector(data, data + node.ashmem->GetAshmemSize()); - } - return std::vector(); - } else { - return std::get(value_); - } - } + virtual ~PublishedDataItem(); + PublishedDataItem(const std::string &key, + int64_t subscriberId, DataType value); + PublishedDataItem(PublishedDataItem &&item); + PublishedDataItem &operator=(PublishedDataItem &&item); + bool IsAshmem() const; + bool IsString() const; + sptr MoveOutAshmem(); + void SetAshmem(sptr ashmem, bool isManaged = false); + void Set(DataType &value); + DataType GetData() const; + +private: + void Clear(); }; /** Specifies the published data structure. */ diff --git a/data_share/interfaces/inner_api/common/include/datashare_values_bucket.h b/data_share/interfaces/inner_api/common/include/datashare_values_bucket.h index 68bf6727..03f15ab6 100644 --- a/data_share/interfaces/inner_api/common/include/datashare_values_bucket.h +++ b/data_share/interfaces/inner_api/common/include/datashare_values_bucket.h @@ -35,7 +35,8 @@ public: * @param string Specifies the parameter of the type. * @param values is the value of the corresponding type. */ - explicit DataShareValuesBucket(std::map values) : valuesMap(std::move(values)){}; + explicit DataShareValuesBucket(std::map values) + : valuesMap(std::move(values)){}; /** * @brief Destructor. */ diff --git a/data_share/interfaces/inner_api/common/libdatashare_common.map b/data_share/interfaces/inner_api/common/libdatashare_common.map index d0120308..f7a02edf 100644 --- a/data_share/interfaces/inner_api/common/libdatashare_common.map +++ b/data_share/interfaces/inner_api/common/libdatashare_common.map @@ -22,6 +22,8 @@ *Error*; *ISharedResultSet*; *ITypesUtil*; + *DataShareKvServiceProxy*; + *PublishedDataItem*; local: *; }; \ No newline at end of file diff --git a/data_share/interfaces/inner_api/consumer/include/datashare_helper.h b/data_share/interfaces/inner_api/consumer/include/datashare_helper.h index ff2bc8a8..babb0d7d 100644 --- a/data_share/interfaces/inner_api/consumer/include/datashare_helper.h +++ b/data_share/interfaces/inner_api/consumer/include/datashare_helper.h @@ -19,14 +19,15 @@ #include #include #include -#include +#include #include -#include "base_connection.h" #include "app/context.h" #include "datashare_business_error.h" +#include "datashare_predicates.h" +#include "datashare_result_set.h" #include "datashare_template.h" -#include "rdb_subscriber_manager.h" +#include "datashare_values_bucket.h" #include "uri.h" using Uri = OHOS::Uri; @@ -61,12 +62,12 @@ public: virtual void OnChange(const ChangeInfo &changeInfo) = 0; }; -class DataShareHelper final : public std::enable_shared_from_this { +class DataShareHelper : public std::enable_shared_from_this { public: /** * @brief Destructor. */ - ~DataShareHelper(); + virtual ~DataShareHelper() = default; /** * @brief Creates a DataShareHelper instance with the Uri specified based on the given Context. @@ -99,7 +100,8 @@ public: * * @return Returns the created DataShareHelper instance with a specified Uri. */ - static std::shared_ptr Creator(const std::string &strUri, const CreateOptions &options); + static std::shared_ptr Creator(const std::string &strUri, const CreateOptions &options, + const std::string &bundleName = ""); /** * @brief Releases the client resource of the Data share. @@ -107,7 +109,7 @@ public: * * @return Returns true if the resource is successfully released; returns false otherwise. */ - bool Release(); + virtual bool Release() = 0; /** * @brief Obtains the MIME types of files supported. @@ -117,7 +119,7 @@ public: * * @return Returns the matched MIME types. If there is no match, null is returned. */ - std::vector GetFileTypes(Uri &uri, const std::string &mimeTypeFilter); + virtual std::vector GetFileTypes(Uri &uri, const std::string &mimeTypeFilter) = 0; /** * @brief Opens a file in a specified remote path. @@ -130,7 +132,7 @@ public: * * @return Returns the file descriptor. */ - int OpenFile(Uri &uri, const std::string &mode); + virtual int OpenFile(Uri &uri, const std::string &mode) = 0; /** * @brief This is like openFile, open a file that need to be able to return sub-sections of files,often assets @@ -144,7 +146,7 @@ public: * * @return Returns the RawFileDescriptor object containing file descriptor. */ - int OpenRawFile(Uri &uri, const std::string &mode); + virtual int OpenRawFile(Uri &uri, const std::string &mode) = 0; /** * @brief Inserts a single data record into the database. @@ -154,7 +156,7 @@ public: * * @return Returns the index of the inserted data record. */ - int Insert(Uri &uri, const DataShareValuesBucket &value); + virtual int Insert(Uri &uri, const DataShareValuesBucket &value) = 0; /** * @brief Updates data records in the database. @@ -165,7 +167,7 @@ public: * * @return Returns the number of data records updated. */ - int Update(Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value); + virtual int Update(Uri &uri, const DataSharePredicates &predicates, const DataShareValuesBucket &value) = 0; /** * @brief Deletes one or more data records from the database. @@ -175,7 +177,7 @@ public: * * @return Returns the number of data records deleted. */ - int Delete(Uri &uri, const DataSharePredicates &predicates); + virtual int Delete(Uri &uri, const DataSharePredicates &predicates) = 0; /** * @brief Query records from the database. @@ -187,8 +189,8 @@ public: * * @return Returns the query result. */ - std::shared_ptr Query(Uri &uri, const DataSharePredicates &predicates, - std::vector &columns, DatashareBusinessError *businessError = nullptr); + virtual std::shared_ptr Query(Uri &uri, const DataSharePredicates &predicates, + std::vector &columns, DatashareBusinessError *businessError = nullptr) = 0; /** * @brief Obtains the MIME type matching the data specified by the URI of the Data share. This method should be @@ -198,7 +200,7 @@ public: * * @return Returns the MIME type that matches the data specified by uri. */ - std::string GetType(Uri &uri); + virtual std::string GetType(Uri &uri) = 0; /** * @brief Inserts multiple data records into the database. @@ -208,7 +210,7 @@ public: * * @return Returns the number of data records inserted. */ - int BatchInsert(Uri &uri, const std::vector &values); + virtual int BatchInsert(Uri &uri, const std::vector &values) = 0; /** * @brief Registers an observer to DataObsMgr specified by the given Uri. @@ -216,7 +218,7 @@ public: * @param uri, Indicates the path of the data to operate. * @param dataObserver, Indicates the IDataAbilityObserver object. */ - void RegisterObserver(const Uri &uri, const sptr &dataObserver); + virtual void RegisterObserver(const Uri &uri, const sptr &dataObserver) = 0; /** * @brief Deregisters an observer used for DataObsMgr specified by the given Uri. @@ -224,14 +226,14 @@ public: * @param uri, Indicates the path of the data to operate. * @param dataObserver, Indicates the IDataAbilityObserver object. */ - void UnregisterObserver(const Uri &uri, const sptr &dataObserver); + virtual void UnregisterObserver(const Uri &uri, const sptr &dataObserver) = 0; /** * @brief Notifies the registered observers of a change to the data resource specified by Uri. * * @param uri, Indicates the path of the data to operate. */ - void NotifyChange(const Uri &uri); + virtual void NotifyChange(const Uri &uri) = 0; /** * Registers an observer to DataObsMgr specified by the given Uri. @@ -240,8 +242,7 @@ public: * @param dataObserver, Indicates the IDataAbilityObserver object. * @param isDescendants, Indicates the Whether to note the change of descendants. */ - void RegisterObserverExt(const Uri &uri, std::shared_ptr dataObserver, - bool isDescendants); + void RegisterObserverExt(const Uri &uri, std::shared_ptr dataObserver, bool isDescendants); /** * Deregisters an observer used for DataObsMgr specified by the given Uri. @@ -271,7 +272,7 @@ public: * * @return Returns the normalized Uri object if the Data share supports URI normalization; returns null otherwise. */ - Uri NormalizeUri(Uri &uri); + virtual Uri NormalizeUri(Uri &uri) = 0; /** * @brief Converts the given normalized uri generated by normalizeUri(ohos.utils.net.Uri) into a denormalized one. @@ -283,7 +284,7 @@ public: * to this method if there is nothing to do; returns null if the data identified by the original Uri cannot be found * in the current environment. */ - Uri DenormalizeUri(Uri &uri); + virtual Uri DenormalizeUri(Uri &uri) = 0; /** * @brief Adds a template of {@link #SubscribeRdbData}. @@ -292,7 +293,7 @@ public: * @param tpl, the template to add. * @return Returns the error code. */ - int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl); + virtual int AddQueryTemplate(const std::string &uri, int64_t subscriberId, Template &tpl) = 0; /** * @brief Deletes a template of {@link #SubscribeRdbData} @@ -300,7 +301,7 @@ public: * @param subscriberId, the subscribe id to delete. * @return Returns the error code. */ - int DelQueryTemplate(const std::string &uri, int64_t subscriberId); + virtual int DelQueryTemplate(const std::string &uri, int64_t subscriberId) = 0; /** * @brief Update a single data into host data area. @@ -308,14 +309,15 @@ public: * @param bundleName the bundleName of data to publish. * @return Returns the error code. */ - std::vector Publish(const Data &data, const std::string &bundleName); + virtual std::vector Publish(const Data &data, const std::string &bundleName) = 0; /** * @brief Get published data by bundleName. * @param bundleName, the bundleName of data. + * @param resultCode, the errcode returned by function * @return Data {@link #Data} */ - Data GetPublishedData(const std::string &bundleName); + virtual Data GetPublishedData(const std::string &bundleName, int &resultCode) = 0; /** * @brief Registers observers to observe rdb data specified by the given uris and template. @@ -324,8 +326,8 @@ public: * @param callback, the callback function of observers. * @return Returns the error code. */ - std::vector SubscribeRdbData(const std::vector &uris, const TemplateId &templateId, - const std::function &callback); + virtual std::vector SubscribeRdbData(const std::vector &uris, + const TemplateId &templateId, const std::function &callback) = 0; /** * @brief Unregisters observers used for monitoring data specified by the given uris and template. @@ -333,8 +335,8 @@ public: * @param templateId, the template of observers. * @return Returns the error code. */ - std::vector UnsubscribeRdbData(const std::vector &uris = std::vector(), - const TemplateId &templateId = TemplateId()); + virtual std::vector UnsubscribeRdbData(const std::vector &uris, + const TemplateId &templateId) = 0; /** * @brief Enable observers by the given uris and template. @@ -342,7 +344,8 @@ public: * @param templateId, the template of observers. * @return Returns the error code. */ - std::vector EnableRdbSubs(const std::vector &uris, const TemplateId &templateId); + virtual std::vector EnableRdbSubs(const std::vector &uris, + const TemplateId &templateId) = 0; /** * @brief Disable observers by the given uris and template. @@ -350,7 +353,8 @@ public: * @param templateId, the template of observers. * @return Returns the error code. */ - std::vector DisableRdbSubs(const std::vector &uris, const TemplateId &templateId); + virtual std::vector DisableRdbSubs(const std::vector &uris, + const TemplateId &templateId) = 0; /** * @brief Registers observers to observe published data specified by the given uris and subscriberId. @@ -359,8 +363,8 @@ public: * @param callback, the callback function of observers. * @return Returns the error code. */ - std::vector SubscribePublishedData(const std::vector &uris, int64_t subscriberId, - const std::function &callback); + virtual std::vector SubscribePublishedData(const std::vector &uris, + int64_t subscriberId, const std::function &callback) = 0; /** * @brief Unregisters observers used for monitoring data specified by the given uris and subscriberId. @@ -368,8 +372,8 @@ public: * @param subscriberId, the subscriberId of observers. * @return Returns the error code. */ - std::vector UnsubscribePublishedData( - const std::vector &uris = std::vector(), int64_t subscriberId = 0); + virtual std::vector UnsubscribePublishedData(const std::vector &uris, + int64_t subscriberId) = 0; /** * @brief Enable observers by the given uris and subscriberId. @@ -377,7 +381,7 @@ public: * @param subscriberId, the subscriberId of observers. * @return Returns the error code. */ - std::vector EnablePubSubs(const std::vector &uris, int64_t subscriberId); + virtual std::vector EnablePubSubs(const std::vector &uris, int64_t subscriberId) = 0; /** * @brief Disable observers by the given uris and template. @@ -385,23 +389,15 @@ public: * @param subscriberId, the subscriberId of observers. * @return Returns the error code. */ - std::vector DisablePubSubs(const std::vector &uris, int64_t subscriberId); + virtual std::vector DisablePubSubs(const std::vector &uris, int64_t subscriberId) = 0; private: - DataShareHelper(const sptr &token, const Uri &uri, - std::shared_ptr dataShareConnection); - DataShareHelper(const sptr &token, const Uri &uri); - DataShareHelper(const CreateOptions &options, const Uri &uri, std::shared_ptr dataShareConnection); - bool isDataShareService_ = false; - sptr token_ = {}; - Uri uri_ = Uri(""); - std::shared_ptr connection_ = nullptr; - static bool RegObserver(const Uri &uri, const sptr &dataObserver); - static bool UnregObserver(const Uri &uri, const sptr &dataObserver); + static std::shared_ptr CreateServiceHelper(const std::string &bundleName = ""); + + static std::shared_ptr CreateExtHelper(Uri &uri, const sptr &token); + static std::string TransferUriPrefix(const std::string &originPrefix, const std::string &replacedPrefix, const std::string &originUriStr); - std::shared_ptr rdbSubscriberManager_ = nullptr; - std::shared_ptr publishedDataSubscriberManager_ = nullptr; }; } // namespace DataShare } // namespace OHOS diff --git a/data_share/interfaces/inner_api/consumer/libdatashare_consumer.map b/data_share/interfaces/inner_api/consumer/libdatashare_consumer.map index ab2ae67d..ae4289ff 100644 --- a/data_share/interfaces/inner_api/consumer/libdatashare_consumer.map +++ b/data_share/interfaces/inner_api/consumer/libdatashare_consumer.map @@ -18,6 +18,9 @@ *DataShareAbsResultSet*; *DataShareSharedResultSet*; *DataShareProxy*; + *PublishedDataItem*; + *DataShareManagerImpl*; + *DataShareServiceProxy*; local: *; }; \ No newline at end of file diff --git a/data_share/test/native/BUILD.gn b/data_share/test/native/BUILD.gn index 58a614ed..dbb1d37d 100644 --- a/data_share/test/native/BUILD.gn +++ b/data_share/test/native/BUILD.gn @@ -12,7 +12,7 @@ # limitations under the License. import("//build/test.gni") -import("//foundation/multimedia/media_library/media_library.gni") +import("//foundation/distributeddatamgr/data_share/datashare.gni") group("unittest") { testonly = true @@ -37,47 +37,42 @@ ohos_unittest("NativeDataShareTest") { include_dirs = [ "//foundation/ability/ability_runtime/interfaces/inner_api/ability_manager/include", "//foundation/ability/ability_runtime/interfaces/inner_api/app_manager/include/appmgr", + "//foundation/ability/ability_runtime/interfaces/inner_api/dataobs_manager/include", "//foundation/ability/ability_runtime/interfaces/kits/native/ability/native", "./unittest/mediadatashare_test/include", "//base/security/access_token/frameworks/common/include", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "${MEDIALIB_ROOT_PATH}/interfaces/innerkits/native/include", "//foundation/aafwk/standard/interfaces/innerkits/uri/include", - "${MEDIALIB_INNERKITS_PATH}/media_library_helper/include", "//commonlibrary/c_utils/base/include", "//utils/system/safwk/native/include", "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "${MEDIALIB_SERVICES_PATH}/media_library/include", - "${MEDIALIB_ROOT_PATH}/frameworks/innerkitsimpl/medialibrary_data_extension/include", - "${MEDIALIB_ROOT_PATH}/interfaces/inner_api/media_library_helper/include", - "${MEDIALIB_UTILS_PATH}/include", "//third_party/json/include", ] - sources = [ - "./unittest/mediadatashare_test/src/get_self_permissions.cpp", - "./unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp", - ] + sources = + [ "./unittest/mediadatashare_test/src/mediadatashare_unit_test.cpp" ] - deps = [] + deps = [ + "${datashare_innerapi_path}:datashare_consumer", + "${datashare_innerapi_path}/common:datashare_common", + ] external_deps = [ "ability_base:want", "ability_base:zuri", "ability_runtime:ability_manager", "ability_runtime:abilitykit_native", + "ability_runtime:dataobs_manager", "access_token:libaccesstoken_sdk", "access_token:libnativetoken", "access_token:libtoken_setproc", "c_utils:utils", "common_event_service:cesfwk_innerkits", - "data_share:datashare_common", - "data_share:datashare_consumer", "hilog_native:libhilog", "hitrace_native:hitrace_meter", "ipc:ipc_single", "media_library:media_library", - "relational_store:native_rdb", + "relational_store:rdb_data_ability_adapter", "safwk:system_ability_fwk", "samgr:samgr_proxy", ] @@ -97,7 +92,10 @@ ohos_unittest("SlientAccessTest") { sources = [ "./unittest/mediadatashare_test/src/slientaccess_test.cpp" ] - deps = [] + deps = [ + "${datashare_innerapi_path}:datashare_consumer", + "${datashare_innerapi_path}/common:datashare_common", + ] external_deps = [ "ability_base:want", @@ -109,8 +107,6 @@ ohos_unittest("SlientAccessTest") { "access_token:libtoken_setproc", "c_utils:utils", "common_event_service:cesfwk_innerkits", - "data_share:datashare_common", - "data_share:datashare_consumer", "hilog_native:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", @@ -132,7 +128,10 @@ ohos_unittest("ErrorCodeTest") { sources = [ "./unittest/mediadatashare_test/src/errorcode_test.cpp" ] - deps = [] + deps = [ + "${datashare_innerapi_path}:datashare_consumer", + "${datashare_innerapi_path}/common:datashare_common", + ] external_deps = [ "ability_base:want", @@ -144,8 +143,6 @@ ohos_unittest("ErrorCodeTest") { "access_token:libtoken_setproc", "c_utils:utils", "common_event_service:cesfwk_innerkits", - "data_share:datashare_common", - "data_share:datashare_consumer", "hilog_native:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", @@ -167,7 +164,10 @@ ohos_unittest("JoinTest") { sources = [ "./unittest/mediadatashare_test/src/join_test.cpp" ] - deps = [] + deps = [ + "${datashare_innerapi_path}:datashare_consumer", + "${datashare_innerapi_path}/common:datashare_common", + ] external_deps = [ "ability_base:want", @@ -179,8 +179,6 @@ ohos_unittest("JoinTest") { "access_token:libtoken_setproc", "c_utils:utils", "common_event_service:cesfwk_innerkits", - "data_share:datashare_common", - "data_share:datashare_consumer", "hilog_native:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", @@ -203,7 +201,10 @@ ohos_unittest("ProxyDatasTest") { sources = [ "./unittest/datashareproxy_test/proxydatas_with_permission_test.cpp" ] - deps = [] + deps = [ + "${datashare_innerapi_path}:datashare_consumer", + "${datashare_innerapi_path}/common:datashare_common", + ] external_deps = [ "ability_base:want", @@ -214,9 +215,6 @@ ohos_unittest("ProxyDatasTest") { "access_token:libnativetoken", "access_token:libtoken_setproc", "c_utils:utils", - "common_event_service:cesfwk_innerkits", - "data_share:datashare_common", - "data_share:datashare_consumer", "hilog_native:libhilog", "ipc:ipc_single", "safwk:system_ability_fwk", diff --git a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/DataShareExtAbility/DataShareExtAbility.ts b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/DataShareExtAbility/DataShareExtAbility.ts index b16b4be8..49f49627 100644 --- a/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/DataShareExtAbility/DataShareExtAbility.ts +++ b/data_share/test/native/resource/datashare_ext_bundle/entry/src/main/ets/DataShareExtAbility/DataShareExtAbility.ts @@ -21,7 +21,7 @@ let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " + TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; ++ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY, number INTEGER)"; let DDL_TABLE_USER_SQL = "CREATE TABLE IF NOT EXISTS user (userId INTEGER PRIMARY KEY AUTOINCREMENT, firstName TEXT, lastName TEXT, age INTEGER , balance DOUBLE NOT NULL)"; let DDL_TABLE_BOOK_SQL = "CREATE TABLE IF NOT EXISTS book (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, userId INTEGER, FOREIGN KEY (userId) REFERENCES user (userId) ON UPDATE NO ACTION ON DELETE CASCADE)"; @@ -44,23 +44,6 @@ extends Extension { console.log('[ttt] [DataShareTest] <> DataShareExtAbility onCreate end'); } - async getFileTypes(uri: string, mimeTypeFilter: string, callback) { - console.info('[ttt] [DataShareTest] <> [getFileTypes] enter'); - let ret = new Array("type01", "type00", "type03"); - console.info('[ttt] [DataShareTest] <> [getFileTypes] leave, ret:' + ret); - let err = {"code":0}; - await callback(err,ret); - return ret; - } - - async openFile(uri: string, mode: string, callback) { - console.info('[ttt] [DataShareTest] <> [openFile] enter'); - let ret = 12345; - let err = {"code":0}; - await callback(err,ret); - console.info('[ttt] [DataShareTest] <> [openFile] leave, ret:' + ret); - } - async insert(uri, value, callback) { console.info('[ttt] [DataShareTest] <> [insert] enter'); if (value == null) { @@ -152,15 +135,6 @@ extends Extension { console.info('[ttt] [DataShareTest] <> [query] leave'); } - async getType(uri: string, callback) { - console.info('[ttt] [DataShareTest] <> [getType] enter'); - let ret = "image"; - console.info('[ttt] [DataShareTest] <> [getType] leave, ret:' + ret); - let err = {"code":0}; - await callback(err,ret); - return ret; - } - async batchInsert(uri: string, valueBuckets, callback) { console.info('[ttt] [DataShareTest] <> [batchInsert] enter'); if (valueBuckets == null || valueBuckets.length == undefined) { @@ -169,7 +143,7 @@ extends Extension { } console.info('[ttt] [DataShareTest] <> [batchInsert] valueBuckets.length:' + valueBuckets.length); let resultNum = valueBuckets.length - await rdbStore.batchinsert(TBL_NAME, valueBuckets, function (err, ret) { + await rdbStore.batchInsert(TBL_NAME, valueBuckets, function (err, ret) { console.info('[ttt] [DataShareTest] <> [batchInsert] callback ret:' + ret); if (callback != undefined) { callback(err, ret); diff --git a/data_share/test/native/resource/ohos_test/ohos_test.xml b/data_share/test/native/resource/ohos_test/ohos_test.xml index 95dc9f0d..40ebbfd6 100644 --- a/data_share/test/native/resource/ohos_test/ohos_test.xml +++ b/data_share/test/native/resource/ohos_test/ohos_test.xml @@ -14,6 +14,15 @@ limitations under the License. --> + + + + + +